2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008 Marco Costalba
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
39 #include "ucioption.h"
43 //// Local definitions
50 // The RootMove class is used for moves at the root at the tree. For each
51 // root move, we store a score, a node count, and a PV (really a refutation
52 // in the case of moves which fail low).
57 bool operator<(const RootMove&); // used to sort
61 int64_t nodes, cumulativeNodes;
62 Move pv[PLY_MAX_PLUS_2];
66 // The RootMoveList class is essentially an array of RootMove objects, with
67 // a handful of methods for accessing the data in the individual moves.
72 RootMoveList(Position &pos, Move searchMoves[]);
73 inline Move get_move(int moveNum) const;
74 inline Value get_move_score(int moveNum) const;
75 inline void set_move_score(int moveNum, Value score);
76 inline void set_move_nodes(int moveNum, int64_t nodes);
77 void set_move_pv(int moveNum, const Move pv[]);
78 inline Move get_move_pv(int moveNum, int i) const;
79 inline int64_t get_move_cumulative_nodes(int moveNum) const;
80 inline int move_count() const;
81 Move scan_for_easy_move() const;
83 void sort_multipv(int n);
86 static const int MaxRootMoves = 500;
87 RootMove moves[MaxRootMoves];
92 /// Constants and variables
94 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
97 int LMRNonPVMoves = 4;
99 // Depth limit for use of dynamic threat detection:
100 Depth ThreatDepth = 5*OnePly;
102 // Depth limit for selective search:
103 Depth SelectiveDepth = 7*OnePly;
105 // Use internal iterative deepening?
106 const bool UseIIDAtPVNodes = true;
107 const bool UseIIDAtNonPVNodes = false;
109 // Internal iterative deepening margin. At Non-PV moves, when
110 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
111 // when the static evaluation is at most IIDMargin below beta.
112 const Value IIDMargin = Value(0x100);
115 const bool UseEasyMove = true;
117 // Easy move margin. An easy move candidate must be at least this much
118 // better than the second best move.
119 const Value EasyMoveMargin = Value(0x200);
121 // Problem margin. If the score of the first move at iteration N+1 has
122 // dropped by more than this since iteration N, the boolean variable
123 // "Problem" is set to true, which will make the program spend some extra
124 // time looking for a better move.
125 const Value ProblemMargin = Value(0x28);
127 // No problem margin. If the boolean "Problem" is true, and a new move
128 // is found at the root which is less than NoProblemMargin worse than the
129 // best move from the previous iteration, Problem is set back to false.
130 const Value NoProblemMargin = Value(0x14);
132 // Null move margin. A null move search will not be done if the approximate
133 // evaluation of the position is more than NullMoveMargin below beta.
134 const Value NullMoveMargin = Value(0x300);
136 // Pruning criterions. See the code and comments in ok_to_prune() to
137 // understand their precise meaning.
138 const bool PruneEscapeMoves = false;
139 const bool PruneDefendingMoves = false;
140 const bool PruneBlockingMoves = false;
142 // Use futility pruning?
143 bool UseQSearchFutilityPruning = true;
144 bool UseFutilityPruning = true;
146 // Margins for futility pruning in the quiescence search, at frontier
147 // nodes, and at pre-frontier nodes
148 Value FutilityMargin0 = Value(0x80);
149 Value FutilityMargin1 = Value(0x100);
150 Value FutilityMargin2 = Value(0x300);
153 Depth RazorDepth = 4*OnePly;
154 Value RazorMargin = Value(0x300);
156 // Last seconds noise filtering (LSN)
157 bool UseLSNFiltering = false;
158 bool looseOnTime = false;
159 int LSNTime = 4 * 1000; // In milliseconds
160 Value LSNValue = Value(0x200);
162 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
163 Depth CheckExtension[2] = {OnePly, OnePly};
164 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
165 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
166 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
167 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
168 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
170 // Search depth at iteration 1
171 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
175 int NodesBetweenPolls = 30000;
181 // Scores and number of times the best move changed for each iteration:
182 Value ValueByIteration[PLY_MAX_PLUS_2];
183 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
188 // Time managment variables
190 int MaxNodes, MaxDepth;
191 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, TimeAdvantage;
192 Move BestRootMove, PonderMove, EasyMove;
196 bool StopOnPonderhit;
201 bool PonderingEnabled;
204 // Show current line?
205 bool ShowCurrentLine = false;
208 bool UseLogFile = false;
209 std::ofstream LogFile;
211 // MP related variables
212 Depth MinimumSplitDepth = 4*OnePly;
213 int MaxThreadsPerSplitPoint = 4;
214 Thread Threads[THREAD_MAX];
216 bool AllThreadsShouldExit = false;
217 const int MaxActiveSplitPoints = 8;
218 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
221 #if !defined(_MSC_VER)
222 pthread_cond_t WaitCond;
223 pthread_mutex_t WaitLock;
225 HANDLE SitIdleEvent[THREAD_MAX];
231 Value id_loop(const Position &pos, Move searchMoves[]);
232 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
233 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
234 Depth depth, int ply, int threadID);
235 Value search(Position &pos, SearchStack ss[], Value beta,
236 Depth depth, int ply, bool allowNullmove, int threadID);
237 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
238 Depth depth, int ply, int threadID);
239 void sp_search(SplitPoint *sp, int threadID);
240 void sp_search_pv(SplitPoint *sp, int threadID);
241 void init_search_stack(SearchStack ss);
242 void init_search_stack(SearchStack ss[]);
243 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
244 void update_pv(SearchStack ss[], int ply);
245 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
246 bool connected_moves(const Position &pos, Move m1, Move m2);
247 Depth extension(const Position &pos, Move m, bool pvNode, bool check,
248 bool singleReply, bool mateThreat);
249 bool ok_to_do_nullmove(const Position &pos);
250 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
251 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
252 bool ok_to_history(const Position &pos, Move m);
253 void update_history(const Position& pos, Move m, Depth depth,
254 Move movesSearched[], int moveCount);
256 bool fail_high_ply_1();
257 int current_search_time();
261 void print_current_line(SearchStack ss[], int ply, int threadID);
262 void wait_for_stop_or_ponderhit();
264 void idle_loop(int threadID, SplitPoint *waitSp);
265 void init_split_point_stack();
266 void destroy_split_point_stack();
267 bool thread_should_stop(int threadID);
268 bool thread_is_available(int slave, int master);
269 bool idle_thread_exists(int master);
270 bool split(const Position &pos, SearchStack *ss, int ply,
271 Value *alpha, Value *beta, Value *bestValue, Depth depth,
272 int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
274 void wake_sleeping_threads();
276 #if !defined(_MSC_VER)
277 void *init_thread(void *threadID);
279 DWORD WINAPI init_thread(LPVOID threadID);
286 //// Global variables
289 // The main transposition table
290 TranspositionTable TT = TranspositionTable(TTDefaultSize);
293 // Number of active threads:
294 int ActiveThreads = 1;
296 // Locks. In principle, there is no need for IOLock to be a global variable,
297 // but it could turn out to be useful for debugging.
300 History H; // Should be made local?
302 // The empty search stack
303 SearchStack EmptySearchStack;
310 /// think() is the external interface to Stockfish's search, and is called when
311 /// the program receives the UCI 'go' command. It initializes various
312 /// search-related global variables, and calls root_search()
314 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
315 int time[], int increment[], int movesToGo, int maxDepth,
316 int maxNodes, int maxTime, Move searchMoves[]) {
318 // Look for a book move
319 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
322 if (get_option_value_string("Book File") != OpeningBook.file_name())
325 OpeningBook.open("book.bin");
327 bookMove = OpeningBook.get_move(pos);
328 if (bookMove != MOVE_NONE)
330 std::cout << "bestmove " << bookMove << std::endl;
335 // Initialize global search variables
337 SearchStartTime = get_system_time();
338 BestRootMove = MOVE_NONE;
339 PonderMove = MOVE_NONE;
340 EasyMove = MOVE_NONE;
341 for (int i = 0; i < THREAD_MAX; i++)
343 Threads[i].nodes = 0ULL;
344 Threads[i].failHighPly1 = false;
347 InfiniteSearch = infinite;
348 PonderSearch = ponder;
349 StopOnPonderhit = false;
354 ExactMaxTime = maxTime;
356 // Read UCI option values
357 TT.set_size(get_option_value_int("Hash"));
358 if (button_was_pressed("Clear Hash"))
361 PonderingEnabled = get_option_value_bool("Ponder");
362 MultiPV = get_option_value_int("MultiPV");
364 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
365 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
367 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
368 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
370 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
371 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
373 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
374 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
376 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
377 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
379 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
380 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
382 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
383 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
384 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
385 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
387 Chess960 = get_option_value_bool("UCI_Chess960");
388 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
389 UseLogFile = get_option_value_bool("Use Search Log");
391 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
393 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
394 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
396 FutilityMargin0 = value_from_centipawns(get_option_value_int("Futility Margin 0"));
397 FutilityMargin1 = value_from_centipawns(get_option_value_int("Futility Margin 1"));
398 FutilityMargin2 = value_from_centipawns(get_option_value_int("Futility Margin 2"));
400 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
401 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
403 UseLSNFiltering = get_option_value_bool("LSN filtering");
404 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
405 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
407 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
408 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
410 read_weights(pos.side_to_move());
412 int newActiveThreads = get_option_value_int("Threads");
413 if (newActiveThreads != ActiveThreads)
415 ActiveThreads = newActiveThreads;
416 init_eval(ActiveThreads);
419 // Wake up sleeping threads:
420 wake_sleeping_threads();
422 for (int i = 1; i < ActiveThreads; i++)
423 assert(thread_is_available(i, 0));
425 // Set thinking time:
426 int myTime = time[side_to_move];
427 int myIncrement = increment[side_to_move];
428 int oppTime = time[1 - side_to_move];
430 TimeAdvantage = myTime - oppTime;
432 if (!movesToGo) // Sudden death time control
436 MaxSearchTime = myTime / 30 + myIncrement;
437 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
438 } else { // Blitz game without increment
439 MaxSearchTime = myTime / 40;
440 AbsoluteMaxSearchTime = myTime / 8;
443 else // (x moves) / (y minutes)
447 MaxSearchTime = myTime / 2;
448 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
450 MaxSearchTime = myTime / Min(movesToGo, 20);
451 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
455 if (PonderingEnabled)
457 MaxSearchTime += MaxSearchTime / 4;
458 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
461 // Fixed depth or fixed number of nodes?
464 InfiniteSearch = true; // HACK
469 NodesBetweenPolls = Min(MaxNodes, 30000);
470 InfiniteSearch = true; // HACK
473 NodesBetweenPolls = 30000;
476 // Write information to search log file:
478 LogFile << "Searching: " << pos.to_fen() << std::endl
479 << "infinite: " << infinite
480 << " ponder: " << ponder
481 << " time: " << myTime
482 << " increment: " << myIncrement
483 << " moves to go: " << movesToGo << std::endl;
486 // We're ready to start thinking. Call the iterative deepening loop
490 Value v = id_loop(pos, searchMoves);
491 looseOnTime = ( UseLSNFiltering
498 looseOnTime = false; // reset for next match
499 while (SearchStartTime + myTime + 1000 > get_system_time())
501 id_loop(pos, searchMoves); // to fail gracefully
518 /// init_threads() is called during startup. It launches all helper threads,
519 /// and initializes the split point stack and the global locks and condition
522 void init_threads() {
526 #if !defined(_MSC_VER)
527 pthread_t pthread[1];
530 for (i = 0; i < THREAD_MAX; i++)
531 Threads[i].activeSplitPoints = 0;
533 // Initialize global locks:
534 lock_init(&MPLock, NULL);
535 lock_init(&IOLock, NULL);
537 init_split_point_stack();
539 #if !defined(_MSC_VER)
540 pthread_mutex_init(&WaitLock, NULL);
541 pthread_cond_init(&WaitCond, NULL);
543 for (i = 0; i < THREAD_MAX; i++)
544 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
547 // All threads except the main thread should be initialized to idle state
548 for (i = 1; i < THREAD_MAX; i++)
550 Threads[i].stop = false;
551 Threads[i].workIsWaiting = false;
552 Threads[i].idle = true;
553 Threads[i].running = false;
556 // Launch the helper threads
557 for(i = 1; i < THREAD_MAX; i++)
559 #if !defined(_MSC_VER)
560 pthread_create(pthread, NULL, init_thread, (void*)(&i));
563 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
566 // Wait until the thread has finished launching:
567 while (!Threads[i].running);
570 // Init also the empty search stack
571 init_search_stack(EmptySearchStack);
575 /// stop_threads() is called when the program exits. It makes all the
576 /// helper threads exit cleanly.
578 void stop_threads() {
580 ActiveThreads = THREAD_MAX; // HACK
581 Idle = false; // HACK
582 wake_sleeping_threads();
583 AllThreadsShouldExit = true;
584 for (int i = 1; i < THREAD_MAX; i++)
586 Threads[i].stop = true;
587 while(Threads[i].running);
589 destroy_split_point_stack();
593 /// nodes_searched() returns the total number of nodes searched so far in
594 /// the current search.
596 int64_t nodes_searched() {
598 int64_t result = 0ULL;
599 for (int i = 0; i < ActiveThreads; i++)
600 result += Threads[i].nodes;
607 // id_loop() is the main iterative deepening loop. It calls root_search
608 // repeatedly with increasing depth until the allocated thinking time has
609 // been consumed, the user stops the search, or the maximum search depth is
612 Value id_loop(const Position &pos, Move searchMoves[]) {
615 SearchStack ss[PLY_MAX_PLUS_2];
617 // searchMoves are verified, copied, scored and sorted
618 RootMoveList rml(p, searchMoves);
623 init_search_stack(ss);
625 ValueByIteration[0] = Value(0);
626 ValueByIteration[1] = rml.get_move_score(0);
628 LastIterations = false;
630 EasyMove = rml.scan_for_easy_move();
632 // Iterative deepening loop
633 while (!AbortSearch && Iteration < PLY_MAX)
635 // Initialize iteration
638 BestMoveChangesByIteration[Iteration] = 0;
642 std::cout << "info depth " << Iteration << std::endl;
644 // Search to the current depth
645 ValueByIteration[Iteration] = root_search(p, ss, rml);
647 // Erase the easy move if it differs from the new best move
648 if (ss[0].pv[0] != EasyMove)
649 EasyMove = MOVE_NONE;
656 bool stopSearch = false;
658 // Stop search early if there is only a single legal move:
659 if (Iteration >= 6 && rml.move_count() == 1)
662 // Stop search early when the last two iterations returned a mate score
664 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
665 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
668 // Stop search early if one move seems to be much better than the rest
669 int64_t nodes = nodes_searched();
671 && EasyMove == ss[0].pv[0]
672 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
673 && current_search_time() > MaxSearchTime / 16)
674 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
675 && current_search_time() > MaxSearchTime / 32)))
678 // Add some extra time if the best move has changed during the last two iterations
679 if (Iteration > 5 && Iteration <= 50)
680 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
681 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
683 // If we need some more and we are in time advantage take it
684 if (ExtraSearchTime > 0 && TimeAdvantage > 2 * MaxSearchTime)
685 ExtraSearchTime += MaxSearchTime / 2;
687 // Try to guess if the current iteration is the last one or the last two
688 LastIterations = (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*58) / 128);
690 // Stop search if most of MaxSearchTime is consumed at the end of the
691 // iteration. We probably don't have enough time to search the first
692 // move at the next iteration anyway.
693 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
701 StopOnPonderhit = true;
704 // Write PV to transposition table, in case the relevant entries have
705 // been overwritten during the search:
706 TT.insert_pv(p, ss[0].pv);
708 if (MaxDepth && Iteration >= MaxDepth)
714 // If we are pondering, we shouldn't print the best move before we
717 wait_for_stop_or_ponderhit();
719 // Print final search statistics
720 std::cout << "info nodes " << nodes_searched()
722 << " time " << current_search_time()
723 << " hashfull " << TT.full() << std::endl;
725 // Print the best move and the ponder move to the standard output
726 std::cout << "bestmove " << ss[0].pv[0];
727 if (ss[0].pv[1] != MOVE_NONE)
728 std::cout << " ponder " << ss[0].pv[1];
730 std::cout << std::endl;
735 LogFile << "Nodes: " << nodes_searched() << std::endl
736 << "Nodes/second: " << nps() << std::endl
737 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
739 p.do_move(ss[0].pv[0], u);
740 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
741 << std::endl << std::endl;
743 return rml.get_move_score(0);
747 // root_search() is the function which searches the root node. It is
748 // similar to search_pv except that it uses a different move ordering
749 // scheme (perhaps we should try to use this at internal PV nodes, too?)
750 // and prints some information to the standard output.
752 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
754 Value alpha = -VALUE_INFINITE;
755 Value beta = VALUE_INFINITE, value;
756 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
758 // Loop through all the moves in the root move list
759 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
766 RootMoveNumber = i + 1;
769 // Remember the node count before the move is searched. The node counts
770 // are used to sort the root moves at the next iteration.
771 nodes = nodes_searched();
773 // Pick the next root move, and print the move and the move number to
774 // the standard output.
775 move = ss[0].currentMove = rml.get_move(i);
776 if (current_search_time() >= 1000)
777 std::cout << "info currmove " << move
778 << " currmovenumber " << i + 1 << std::endl;
780 // Decide search depth for this move
781 ext = extension(pos, move, true, pos.move_is_check(move), false, false);
782 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
784 // Make the move, and search it
785 pos.do_move(move, u, dcCandidates);
789 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
790 // If the value has dropped a lot compared to the last iteration,
791 // set the boolean variable Problem to true. This variable is used
792 // for time managment: When Problem is true, we try to complete the
793 // current iteration before playing a move.
794 Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
796 if (Problem && StopOnPonderhit)
797 StopOnPonderhit = false;
801 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
804 // Fail high! Set the boolean variable FailHigh to true, and
805 // re-search the move with a big window. The variable FailHigh is
806 // used for time managment: We try to avoid aborting the search
807 // prematurely during a fail high research.
809 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
813 pos.undo_move(move, u);
815 // Finished searching the move. If AbortSearch is true, the search
816 // was aborted because the user interrupted the search or because we
817 // ran out of time. In this case, the return value of the search cannot
818 // be trusted, and we break out of the loop without updating the best
823 // Remember the node count for this move. The node counts are used to
824 // sort the root moves at the next iteration.
825 rml.set_move_nodes(i, nodes_searched() - nodes);
827 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
829 if (value <= alpha && i >= MultiPV)
830 rml.set_move_score(i, -VALUE_INFINITE);
836 rml.set_move_score(i, value);
838 rml.set_move_pv(i, ss[0].pv);
842 // We record how often the best move has been changed in each
843 // iteration. This information is used for time managment: When
844 // the best move changes frequently, we allocate some more time.
846 BestMoveChangesByIteration[Iteration]++;
848 // Print search information to the standard output:
849 std::cout << "info depth " << Iteration
850 << " score " << value_to_string(value)
851 << " time " << current_search_time()
852 << " nodes " << nodes_searched()
856 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
857 std::cout << ss[0].pv[j] << " ";
859 std::cout << std::endl;
862 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
867 // Reset the global variable Problem to false if the value isn't too
868 // far below the final value from the last iteration.
869 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
875 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
878 std::cout << "info multipv " << j + 1
879 << " score " << value_to_string(rml.get_move_score(j))
880 << " depth " << ((j <= i)? Iteration : Iteration - 1)
881 << " time " << current_search_time()
882 << " nodes " << nodes_searched()
886 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
887 std::cout << rml.get_move_pv(j, k) << " ";
889 std::cout << std::endl;
891 alpha = rml.get_move_score(Min(i, MultiPV-1));
899 // search_pv() is the main search function for PV nodes.
901 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
902 Depth depth, int ply, int threadID) {
904 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
905 assert(beta > alpha && beta <= VALUE_INFINITE);
906 assert(ply >= 0 && ply < PLY_MAX);
907 assert(threadID >= 0 && threadID < ActiveThreads);
909 // Initialize, and make an early exit in case of an aborted search,
910 // an instant draw, maximum ply reached, etc.
911 if (AbortSearch || thread_should_stop(threadID))
915 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
917 init_node(pos, ss, ply, threadID);
924 if (ply >= PLY_MAX - 1)
925 return evaluate(pos, ei, threadID);
927 // Mate distance pruning
928 Value oldAlpha = alpha;
929 alpha = Max(value_mated_in(ply), alpha);
930 beta = Min(value_mate_in(ply+1), beta);
934 // Transposition table lookup. At PV nodes, we don't use the TT for
935 // pruning, but only for move ordering.
936 const TTEntry* tte = TT.retrieve(pos);
937 Move ttMove = (tte ? tte->move() : MOVE_NONE);
939 // Go with internal iterative deepening if we don't have a TT move
940 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
942 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
943 ttMove = ss[ply].pv[ply];
946 // Initialize a MovePicker object for the current position, and prepare
947 // to search all moves
948 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
950 Move move, movesSearched[256];
952 Value value, bestValue = -VALUE_INFINITE;
953 Bitboard dcCandidates = mp.discovered_check_candidates();
954 bool isCheck = pos.is_check();
955 bool mateThreat = MateThreatExtension[1] > Depth(0)
956 && pos.has_mate_threat(opposite_color(pos.side_to_move()));
958 // Loop through all legal moves until no moves remain or a beta cutoff
961 && (move = mp.get_next_move()) != MOVE_NONE
962 && !thread_should_stop(threadID))
964 assert(move_is_ok(move));
966 bool singleReply = (isCheck && mp.number_of_moves() == 1);
967 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
968 bool moveIsCapture = pos.move_is_capture(move);
969 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
971 movesSearched[moveCount++] = ss[ply].currentMove = move;
974 ss[ply].currentMoveCaptureValue = pos.midgame_value_of_piece_on(move_to(move));
975 else if (move_is_ep(move))
976 ss[ply].currentMoveCaptureValue = PawnValueMidgame;
978 ss[ply].currentMoveCaptureValue = Value(0);
980 // Decide the new search depth
981 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat);
982 Depth newDepth = depth - OnePly + ext;
984 // Make and search the move
986 pos.do_move(move, u, dcCandidates);
988 if (moveCount == 1) // The first move in list is the PV
989 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
992 // Try to reduce non-pv search depth by one ply if move seems not problematic,
993 // if the move fails high will be re-searched at full depth.
994 if ( depth >= 2*OnePly
996 && moveCount >= LMRPVMoves
998 && !move_promotion(move)
999 && !moveIsPassedPawnPush
1000 && !move_is_castle(move)
1001 && move != ss[ply].killers[0]
1002 && move != ss[ply].killers[1])
1004 ss[ply].reduction = OnePly;
1005 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1008 value = alpha + 1; // Just to trigger next condition
1010 if (value > alpha) // Go with full depth pv search
1012 ss[ply].reduction = Depth(0);
1013 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1014 if (value > alpha && value < beta)
1016 // When the search fails high at ply 1 while searching the first
1017 // move at the root, set the flag failHighPly1. This is used for
1018 // time managment: We don't want to stop the search early in
1019 // such cases, because resolving the fail high at ply 1 could
1020 // result in a big drop in score at the root.
1021 if (ply == 1 && RootMoveNumber == 1)
1022 Threads[threadID].failHighPly1 = true;
1024 // A fail high occurred. Re-search at full window (pv search)
1025 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1026 Threads[threadID].failHighPly1 = false;
1030 pos.undo_move(move, u);
1032 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1035 if (value > bestValue)
1042 if (value == value_mate_in(ply + 1))
1043 ss[ply].mateKiller = move;
1045 // If we are at ply 1, and we are searching the first root move at
1046 // ply 0, set the 'Problem' variable if the score has dropped a lot
1047 // (from the computer's point of view) since the previous iteration:
1048 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1053 if ( ActiveThreads > 1
1055 && depth >= MinimumSplitDepth
1057 && idle_thread_exists(threadID)
1059 && !thread_should_stop(threadID)
1060 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1061 &moveCount, &mp, dcCandidates, threadID, true))
1065 // All legal moves have been searched. A special case: If there were
1066 // no legal moves, it must be mate or stalemate:
1068 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1070 // If the search is not aborted, update the transposition table,
1071 // history counters, and killer moves.
1072 if (AbortSearch || thread_should_stop(threadID))
1075 if (bestValue <= oldAlpha)
1076 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1078 else if (bestValue >= beta)
1080 Move m = ss[ply].pv[ply];
1081 if (ok_to_history(pos, m)) // Only non capture moves are considered
1083 update_history(pos, m, depth, movesSearched, moveCount);
1084 if (m != ss[ply].killers[0])
1086 ss[ply].killers[1] = ss[ply].killers[0];
1087 ss[ply].killers[0] = m;
1090 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1093 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1099 // search() is the search function for zero-width nodes.
1101 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1102 int ply, bool allowNullmove, int threadID) {
1104 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1105 assert(ply >= 0 && ply < PLY_MAX);
1106 assert(threadID >= 0 && threadID < ActiveThreads);
1110 // Initialize, and make an early exit in case of an aborted search,
1111 // an instant draw, maximum ply reached, etc.
1112 if (AbortSearch || thread_should_stop(threadID))
1116 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1118 init_node(pos, ss, ply, threadID);
1123 if (ply >= PLY_MAX - 1)
1124 return evaluate(pos, ei, threadID);
1126 // Mate distance pruning
1127 if (value_mated_in(ply) >= beta)
1130 if (value_mate_in(ply + 1) < beta)
1133 // Transposition table lookup
1134 const TTEntry* tte = TT.retrieve(pos);
1135 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1137 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1139 ss[ply].currentMove = ttMove; // can be MOVE_NONE ?
1140 return value_from_tt(tte->value(), ply);
1143 Value approximateEval = quick_evaluate(pos);
1144 bool mateThreat = false;
1145 bool isCheck = pos.is_check();
1150 && ok_to_do_nullmove(pos)
1151 && approximateEval >= beta - NullMoveMargin)
1153 ss[ply].currentMove = MOVE_NULL;
1156 pos.do_null_move(u);
1157 int R = (depth > 7 ? 4 : 3);
1158 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1159 pos.undo_null_move(u);
1161 if (nullValue >= beta)
1163 if (depth < 6 * OnePly)
1166 // Do zugzwang verification search
1167 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1171 // The null move failed low, which means that we may be faced with
1172 // some kind of threat. If the previous move was reduced, check if
1173 // the move that refuted the null move was somehow connected to the
1174 // move which was reduced. If a connection is found, return a fail
1175 // low score (which will cause the reduced move to fail high in the
1176 // parent node, which will trigger a re-search with full depth).
1177 if (nullValue == value_mated_in(ply + 2))
1180 ss[ply].threatMove = ss[ply + 1].currentMove;
1181 if ( depth < ThreatDepth
1182 && ss[ply - 1].reduction
1183 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1187 // Null move search not allowed, try razoring
1188 else if ( (approximateEval < beta - RazorMargin && depth < RazorDepth)
1189 ||(approximateEval < beta - PawnValueMidgame && depth <= OnePly))
1191 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1196 // Go with internal iterative deepening if we don't have a TT move
1197 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1198 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1200 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1201 ttMove = ss[ply].pv[ply];
1204 // Initialize a MovePicker object for the current position, and prepare
1205 // to search all moves:
1206 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1208 Move move, movesSearched[256];
1210 Value value, bestValue = -VALUE_INFINITE;
1211 Bitboard dcCandidates = mp.discovered_check_candidates();
1212 Value futilityValue = VALUE_NONE;
1213 bool useFutilityPruning = UseFutilityPruning
1214 && depth < SelectiveDepth
1217 // Loop through all legal moves until no moves remain or a beta cutoff
1219 while ( bestValue < beta
1220 && (move = mp.get_next_move()) != MOVE_NONE
1221 && !thread_should_stop(threadID))
1223 assert(move_is_ok(move));
1225 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1226 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1227 bool moveIsCapture = pos.move_is_capture(move);
1228 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1230 movesSearched[moveCount++] = ss[ply].currentMove = move;
1232 // Decide the new search depth
1233 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat);
1234 Depth newDepth = depth - OnePly + ext;
1237 if ( useFutilityPruning
1240 && !moveIsPassedPawnPush
1241 && !move_promotion(move))
1243 if ( moveCount >= 2 + int(depth)
1244 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1247 if (depth < 3 * OnePly && approximateEval < beta)
1249 if (futilityValue == VALUE_NONE)
1250 futilityValue = evaluate(pos, ei, threadID)
1251 + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2);
1253 if (futilityValue < beta)
1255 if (futilityValue > bestValue)
1256 bestValue = futilityValue;
1262 // Make and search the move
1264 pos.do_move(move, u, dcCandidates);
1266 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1267 // if the move fails high will be re-searched at full depth.
1268 if ( depth >= 2*OnePly
1270 && moveCount >= LMRNonPVMoves
1272 && !move_promotion(move)
1273 && !moveIsPassedPawnPush
1274 && !move_is_castle(move)
1275 && move != ss[ply].killers[0]
1276 && move != ss[ply].killers[1])
1278 ss[ply].reduction = OnePly;
1279 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1282 value = beta; // Just to trigger next condition
1284 if (value >= beta) // Go with full depth non-pv search
1286 ss[ply].reduction = Depth(0);
1287 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1289 pos.undo_move(move, u);
1291 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1294 if (value > bestValue)
1300 if (value == value_mate_in(ply + 1))
1301 ss[ply].mateKiller = move;
1305 if ( ActiveThreads > 1
1307 && depth >= MinimumSplitDepth
1309 && idle_thread_exists(threadID)
1311 && !thread_should_stop(threadID)
1312 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1313 &mp, dcCandidates, threadID, false))
1317 // All legal moves have been searched. A special case: If there were
1318 // no legal moves, it must be mate or stalemate.
1320 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1322 // If the search is not aborted, update the transposition table,
1323 // history counters, and killer moves.
1324 if (AbortSearch || thread_should_stop(threadID))
1327 if (bestValue < beta)
1328 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1331 Move m = ss[ply].pv[ply];
1332 if (ok_to_history(pos, m)) // Only non capture moves are considered
1334 update_history(pos, m, depth, movesSearched, moveCount);
1335 if (m != ss[ply].killers[0])
1337 ss[ply].killers[1] = ss[ply].killers[0];
1338 ss[ply].killers[0] = m;
1341 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1347 // qsearch() is the quiescence search function, which is called by the main
1348 // search function when the remaining depth is zero (or, to be more precise,
1349 // less than OnePly).
1351 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1352 Depth depth, int ply, int threadID) {
1354 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1355 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1357 assert(ply >= 0 && ply < PLY_MAX);
1358 assert(threadID >= 0 && threadID < ActiveThreads);
1362 // Initialize, and make an early exit in case of an aborted search,
1363 // an instant draw, maximum ply reached, etc.
1364 if (AbortSearch || thread_should_stop(threadID))
1367 init_node(pos, ss, ply, threadID);
1372 // Transposition table lookup
1373 const TTEntry* tte = TT.retrieve(pos);
1374 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1375 return value_from_tt(tte->value(), ply);
1377 // Evaluate the position statically
1378 Value staticValue = evaluate(pos, ei, threadID);
1380 if (ply == PLY_MAX - 1)
1383 // Initialize "stand pat score", and return it immediately if it is
1385 Value bestValue = (pos.is_check() ? -VALUE_INFINITE : staticValue);
1387 if (bestValue >= beta)
1390 if (bestValue > alpha)
1393 // Initialize a MovePicker object for the current position, and prepare
1394 // to search the moves. Because the depth is <= 0 here, only captures,
1395 // queen promotions and checks (only if depth == 0) will be generated.
1396 MovePicker mp = MovePicker(pos, false, MOVE_NONE, EmptySearchStack, depth, &ei);
1399 Bitboard dcCandidates = mp.discovered_check_candidates();
1400 bool isCheck = pos.is_check();
1401 bool pvNode = (beta - alpha != 1);
1402 bool enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1404 // Loop through the moves until no moves remain or a beta cutoff
1406 while ( alpha < beta
1407 && (move = mp.get_next_move()) != MOVE_NONE)
1409 assert(move_is_ok(move));
1411 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1412 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1415 ss[ply].currentMove = move;
1418 if ( UseQSearchFutilityPruning
1421 && !move_promotion(move)
1422 && !moveIsPassedPawnPush
1426 Value futilityValue = staticValue
1427 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1428 pos.endgame_value_of_piece_on(move_to(move)))
1430 + ei.futilityMargin;
1432 if (futilityValue < alpha)
1434 if (futilityValue > bestValue)
1435 bestValue = futilityValue;
1440 // Don't search captures and checks with negative SEE values
1442 && !move_promotion(move)
1444 && (pos.midgame_value_of_piece_on(move_from(move)) >
1445 pos.midgame_value_of_piece_on(move_to(move)))
1446 && pos.see(move) < 0)
1449 // Make and search the move.
1451 pos.do_move(move, u, dcCandidates);
1452 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1453 pos.undo_move(move, u);
1455 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1458 if (value > bestValue)
1469 // All legal moves have been searched. A special case: If we're in check
1470 // and no legal moves were found, it is checkmate:
1471 if (pos.is_check() && moveCount == 0) // Mate!
1472 return value_mated_in(ply);
1474 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1476 // Update transposition table
1477 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1479 // Update killers only for good check moves
1480 Move m = ss[ply].currentMove;
1481 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1483 // Wrong to update history when depth is <= 0
1485 if (m != ss[ply].killers[0])
1487 ss[ply].killers[1] = ss[ply].killers[0];
1488 ss[ply].killers[0] = m;
1495 // sp_search() is used to search from a split point. This function is called
1496 // by each thread working at the split point. It is similar to the normal
1497 // search() function, but simpler. Because we have already probed the hash
1498 // table, done a null move search, and searched the first move before
1499 // splitting, we don't have to repeat all this work in sp_search(). We
1500 // also don't need to store anything to the hash table here: This is taken
1501 // care of after we return from the split point.
1503 void sp_search(SplitPoint *sp, int threadID) {
1505 assert(threadID >= 0 && threadID < ActiveThreads);
1506 assert(ActiveThreads > 1);
1508 Position pos = Position(sp->pos);
1509 SearchStack *ss = sp->sstack[threadID];
1512 bool isCheck = pos.is_check();
1513 bool useFutilityPruning = UseFutilityPruning
1514 && sp->depth < SelectiveDepth
1517 while ( sp->bestValue < sp->beta
1518 && !thread_should_stop(threadID)
1519 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1521 assert(move_is_ok(move));
1523 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1524 bool moveIsCapture = pos.move_is_capture(move);
1525 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1527 lock_grab(&(sp->lock));
1528 int moveCount = ++sp->moves;
1529 lock_release(&(sp->lock));
1531 ss[sp->ply].currentMove = move;
1533 // Decide the new search depth.
1534 Depth ext = extension(pos, move, false, moveIsCheck, false, false);
1535 Depth newDepth = sp->depth - OnePly + ext;
1538 if ( useFutilityPruning
1541 && !moveIsPassedPawnPush
1542 && !move_promotion(move)
1543 && moveCount >= 2 + int(sp->depth)
1544 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1547 // Make and search the move.
1549 pos.do_move(move, u, sp->dcCandidates);
1551 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1552 // if the move fails high will be re-searched at full depth.
1553 if ( ext == Depth(0)
1554 && moveCount >= LMRNonPVMoves
1556 && !moveIsPassedPawnPush
1557 && !move_promotion(move)
1558 && !move_is_castle(move)
1559 && move != ss[sp->ply].killers[0]
1560 && move != ss[sp->ply].killers[1])
1562 ss[sp->ply].reduction = OnePly;
1563 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1566 value = sp->beta; // Just to trigger next condition
1568 if (value >= sp->beta) // Go with full depth non-pv search
1570 ss[sp->ply].reduction = Depth(0);
1571 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1573 pos.undo_move(move, u);
1575 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1577 if (thread_should_stop(threadID))
1581 lock_grab(&(sp->lock));
1582 if (value > sp->bestValue && !thread_should_stop(threadID))
1584 sp->bestValue = value;
1585 if (sp->bestValue >= sp->beta)
1587 sp_update_pv(sp->parentSstack, ss, sp->ply);
1588 for (int i = 0; i < ActiveThreads; i++)
1589 if (i != threadID && (i == sp->master || sp->slaves[i]))
1590 Threads[i].stop = true;
1592 sp->finished = true;
1595 lock_release(&(sp->lock));
1598 lock_grab(&(sp->lock));
1600 // If this is the master thread and we have been asked to stop because of
1601 // a beta cutoff higher up in the tree, stop all slave threads:
1602 if (sp->master == threadID && thread_should_stop(threadID))
1603 for (int i = 0; i < ActiveThreads; i++)
1605 Threads[i].stop = true;
1608 sp->slaves[threadID] = 0;
1610 lock_release(&(sp->lock));
1614 // sp_search_pv() is used to search from a PV split point. This function
1615 // is called by each thread working at the split point. It is similar to
1616 // the normal search_pv() function, but simpler. Because we have already
1617 // probed the hash table and searched the first move before splitting, we
1618 // don't have to repeat all this work in sp_search_pv(). We also don't
1619 // need to store anything to the hash table here: This is taken care of
1620 // after we return from the split point.
1622 void sp_search_pv(SplitPoint *sp, int threadID) {
1624 assert(threadID >= 0 && threadID < ActiveThreads);
1625 assert(ActiveThreads > 1);
1627 Position pos = Position(sp->pos);
1628 SearchStack *ss = sp->sstack[threadID];
1632 while ( sp->alpha < sp->beta
1633 && !thread_should_stop(threadID)
1634 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1636 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1637 bool moveIsCapture = pos.move_is_capture(move);
1638 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1640 assert(move_is_ok(move));
1642 ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1643 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1645 lock_grab(&(sp->lock));
1646 int moveCount = ++sp->moves;
1647 lock_release(&(sp->lock));
1649 ss[sp->ply].currentMove = move;
1651 // Decide the new search depth.
1652 Depth ext = extension(pos, move, true, moveIsCheck, false, false);
1653 Depth newDepth = sp->depth - OnePly + ext;
1655 // Make and search the move.
1657 pos.do_move(move, u, sp->dcCandidates);
1659 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1660 // if the move fails high will be re-searched at full depth.
1661 if ( ext == Depth(0)
1662 && moveCount >= LMRPVMoves
1664 && !moveIsPassedPawnPush
1665 && !move_promotion(move)
1666 && !move_is_castle(move)
1667 && move != ss[sp->ply].killers[0]
1668 && move != ss[sp->ply].killers[1])
1670 ss[sp->ply].reduction = OnePly;
1671 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1674 value = sp->alpha + 1; // Just to trigger next condition
1676 if (value > sp->alpha) // Go with full depth non-pv search
1678 ss[sp->ply].reduction = Depth(0);
1679 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1681 if (value > sp->alpha && value < sp->beta)
1683 // When the search fails high at ply 1 while searching the first
1684 // move at the root, set the flag failHighPly1. This is used for
1685 // time managment: We don't want to stop the search early in
1686 // such cases, because resolving the fail high at ply 1 could
1687 // result in a big drop in score at the root.
1688 if (sp->ply == 1 && RootMoveNumber == 1)
1689 Threads[threadID].failHighPly1 = true;
1691 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1692 Threads[threadID].failHighPly1 = false;
1695 pos.undo_move(move, u);
1697 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1699 if (thread_should_stop(threadID))
1703 lock_grab(&(sp->lock));
1704 if (value > sp->bestValue && !thread_should_stop(threadID))
1706 sp->bestValue = value;
1707 if (value > sp->alpha)
1710 sp_update_pv(sp->parentSstack, ss, sp->ply);
1711 if (value == value_mate_in(sp->ply + 1))
1712 ss[sp->ply].mateKiller = move;
1714 if(value >= sp->beta)
1716 for(int i = 0; i < ActiveThreads; i++)
1717 if(i != threadID && (i == sp->master || sp->slaves[i]))
1718 Threads[i].stop = true;
1720 sp->finished = true;
1723 // If we are at ply 1, and we are searching the first root move at
1724 // ply 0, set the 'Problem' variable if the score has dropped a lot
1725 // (from the computer's point of view) since the previous iteration:
1726 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1729 lock_release(&(sp->lock));
1732 lock_grab(&(sp->lock));
1734 // If this is the master thread and we have been asked to stop because of
1735 // a beta cutoff higher up in the tree, stop all slave threads:
1736 if (sp->master == threadID && thread_should_stop(threadID))
1737 for (int i = 0; i < ActiveThreads; i++)
1739 Threads[i].stop = true;
1742 sp->slaves[threadID] = 0;
1744 lock_release(&(sp->lock));
1748 /// The RootMove class
1752 RootMove::RootMove() {
1753 nodes = cumulativeNodes = 0ULL;
1756 // RootMove::operator<() is the comparison function used when
1757 // sorting the moves. A move m1 is considered to be better
1758 // than a move m2 if it has a higher score, or if the moves
1759 // have equal score but m1 has the higher node count.
1761 bool RootMove::operator<(const RootMove& m) {
1763 if (score != m.score)
1764 return (score < m.score);
1766 return nodes <= m.nodes;
1769 /// The RootMoveList class
1773 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1775 MoveStack mlist[MaxRootMoves];
1776 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1778 // Generate all legal moves
1779 int lm_count = generate_legal_moves(pos, mlist);
1781 // Add each move to the moves[] array
1782 for (int i = 0; i < lm_count; i++)
1784 bool includeMove = includeAllMoves;
1786 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1787 includeMove = (searchMoves[k] == mlist[i].move);
1791 // Find a quick score for the move
1793 SearchStack ss[PLY_MAX_PLUS_2];
1795 moves[count].move = mlist[i].move;
1796 moves[count].nodes = 0ULL;
1797 pos.do_move(moves[count].move, u);
1798 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1800 pos.undo_move(moves[count].move, u);
1801 moves[count].pv[0] = moves[i].move;
1802 moves[count].pv[1] = MOVE_NONE; // FIXME
1810 // Simple accessor methods for the RootMoveList class
1812 inline Move RootMoveList::get_move(int moveNum) const {
1813 return moves[moveNum].move;
1816 inline Value RootMoveList::get_move_score(int moveNum) const {
1817 return moves[moveNum].score;
1820 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1821 moves[moveNum].score = score;
1824 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1825 moves[moveNum].nodes = nodes;
1826 moves[moveNum].cumulativeNodes += nodes;
1829 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1831 for(j = 0; pv[j] != MOVE_NONE; j++)
1832 moves[moveNum].pv[j] = pv[j];
1833 moves[moveNum].pv[j] = MOVE_NONE;
1836 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1837 return moves[moveNum].pv[i];
1840 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1841 return moves[moveNum].cumulativeNodes;
1844 inline int RootMoveList::move_count() const {
1849 // RootMoveList::scan_for_easy_move() is called at the end of the first
1850 // iteration, and is used to detect an "easy move", i.e. a move which appears
1851 // to be much bester than all the rest. If an easy move is found, the move
1852 // is returned, otherwise the function returns MOVE_NONE. It is very
1853 // important that this function is called at the right moment: The code
1854 // assumes that the first iteration has been completed and the moves have
1855 // been sorted. This is done in RootMoveList c'tor.
1857 Move RootMoveList::scan_for_easy_move() const {
1864 // moves are sorted so just consider the best and the second one
1865 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1871 // RootMoveList::sort() sorts the root move list at the beginning of a new
1874 inline void RootMoveList::sort() {
1876 sort_multipv(count - 1); // all items
1880 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1881 // list by their scores and depths. It is used to order the different PVs
1882 // correctly in MultiPV mode.
1884 void RootMoveList::sort_multipv(int n) {
1886 for (int i = 1; i <= n; i++)
1888 RootMove rm = moves[i];
1890 for (j = i; j > 0 && moves[j-1] < rm; j--)
1891 moves[j] = moves[j-1];
1897 // init_search_stack() initializes a search stack at the beginning of a
1898 // new search from the root.
1899 void init_search_stack(SearchStack ss) {
1901 ss.pv[0] = MOVE_NONE;
1902 ss.pv[1] = MOVE_NONE;
1903 ss.currentMove = MOVE_NONE;
1904 ss.threatMove = MOVE_NONE;
1905 ss.reduction = Depth(0);
1906 for (int j = 0; j < KILLER_MAX; j++)
1907 ss.killers[j] = MOVE_NONE;
1910 void init_search_stack(SearchStack ss[]) {
1912 for (int i = 0; i < 3; i++)
1914 ss[i].pv[i] = MOVE_NONE;
1915 ss[i].pv[i+1] = MOVE_NONE;
1916 ss[i].currentMove = MOVE_NONE;
1917 ss[i].threatMove = MOVE_NONE;
1918 ss[i].reduction = Depth(0);
1919 for (int j = 0; j < KILLER_MAX; j++)
1920 ss[i].killers[j] = MOVE_NONE;
1925 // init_node() is called at the beginning of all the search functions
1926 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1927 // stack object corresponding to the current node. Once every
1928 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1929 // for user input and checks whether it is time to stop the search.
1931 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1932 assert(ply >= 0 && ply < PLY_MAX);
1933 assert(threadID >= 0 && threadID < ActiveThreads);
1935 Threads[threadID].nodes++;
1939 if(NodesSincePoll >= NodesBetweenPolls) {
1945 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1946 ss[ply+2].mateKiller = MOVE_NONE;
1947 ss[ply+2].killers[0] = ss[ply+2].killers[1] = MOVE_NONE;
1948 ss[ply].threatMove = MOVE_NONE;
1949 ss[ply].reduction = Depth(0);
1950 ss[ply].currentMoveCaptureValue = Value(0);
1952 if(Threads[threadID].printCurrentLine)
1953 print_current_line(ss, ply, threadID);
1957 // update_pv() is called whenever a search returns a value > alpha. It
1958 // updates the PV in the SearchStack object corresponding to the current
1961 void update_pv(SearchStack ss[], int ply) {
1962 assert(ply >= 0 && ply < PLY_MAX);
1964 ss[ply].pv[ply] = ss[ply].currentMove;
1966 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1967 ss[ply].pv[p] = ss[ply+1].pv[p];
1968 ss[ply].pv[p] = MOVE_NONE;
1972 // sp_update_pv() is a variant of update_pv for use at split points. The
1973 // difference between the two functions is that sp_update_pv also updates
1974 // the PV at the parent node.
1976 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1977 assert(ply >= 0 && ply < PLY_MAX);
1979 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1981 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1982 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1983 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1987 // connected_moves() tests whether two moves are 'connected' in the sense
1988 // that the first move somehow made the second move possible (for instance
1989 // if the moving piece is the same in both moves). The first move is
1990 // assumed to be the move that was made to reach the current position, while
1991 // the second move is assumed to be a move from the current position.
1993 bool connected_moves(const Position &pos, Move m1, Move m2) {
1994 Square f1, t1, f2, t2;
1996 assert(move_is_ok(m1));
1997 assert(move_is_ok(m2));
2002 // Case 1: The moving piece is the same in both moves.
2008 // Case 2: The destination square for m2 was vacated by m1.
2014 // Case 3: Moving through the vacated square:
2015 if(piece_is_slider(pos.piece_on(f2)) &&
2016 bit_is_set(squares_between(f2, t2), f1))
2019 // Case 4: The destination square for m2 is attacked by the moving piece
2021 if(pos.piece_attacks_square(t1, t2))
2024 // Case 5: Discovered check, checking piece is the piece moved in m1:
2025 if(piece_is_slider(pos.piece_on(t1)) &&
2026 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2028 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2030 Bitboard occ = pos.occupied_squares();
2031 Color us = pos.side_to_move();
2032 Square ksq = pos.king_square(us);
2033 clear_bit(&occ, f2);
2034 if(pos.type_of_piece_on(t1) == BISHOP) {
2035 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2038 else if(pos.type_of_piece_on(t1) == ROOK) {
2039 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2043 assert(pos.type_of_piece_on(t1) == QUEEN);
2044 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2053 // extension() decides whether a move should be searched with normal depth,
2054 // or with extended depth. Certain classes of moves (checking moves, in
2055 // particular) are searched with bigger depth than ordinary moves.
2057 Depth extension(const Position &pos, Move m, bool pvNode,
2058 bool check, bool singleReply, bool mateThreat) {
2060 Depth result = Depth(0);
2063 result += CheckExtension[pvNode];
2066 result += SingleReplyExtension[pvNode];
2068 if (pos.move_is_pawn_push_to_7th(m))
2069 result += PawnPushTo7thExtension[pvNode];
2071 if (pos.move_is_passed_pawn_push(m))
2072 result += PassedPawnExtension[pvNode];
2075 result += MateThreatExtension[pvNode];
2077 if ( pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
2078 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2079 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2080 && !move_promotion(m))
2081 result += PawnEndgameExtension[pvNode];
2084 && pos.move_is_capture(m)
2085 && pos.type_of_piece_on(move_to(m)) != PAWN
2089 return Min(result, OnePly);
2093 // ok_to_do_nullmove() looks at the current position and decides whether
2094 // doing a 'null move' should be allowed. In order to avoid zugzwang
2095 // problems, null moves are not allowed when the side to move has very
2096 // little material left. Currently, the test is a bit too simple: Null
2097 // moves are avoided only when the side to move has only pawns left. It's
2098 // probably a good idea to avoid null moves in at least some more
2099 // complicated endgames, e.g. KQ vs KR. FIXME
2101 bool ok_to_do_nullmove(const Position &pos) {
2102 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2108 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2109 // non-tactical moves late in the move list close to the leaves are
2110 // candidates for pruning.
2112 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2113 Square mfrom, mto, tfrom, tto;
2115 assert(move_is_ok(m));
2116 assert(threat == MOVE_NONE || move_is_ok(threat));
2117 assert(!move_promotion(m));
2118 assert(!pos.move_is_check(m));
2119 assert(!pos.move_is_capture(m));
2120 assert(!pos.move_is_passed_pawn_push(m));
2121 assert(d >= OnePly);
2123 mfrom = move_from(m);
2125 tfrom = move_from(threat);
2126 tto = move_to(threat);
2128 // Case 1: Castling moves are never pruned.
2129 if(move_is_castle(m))
2132 // Case 2: Don't prune moves which move the threatened piece
2133 if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2136 // Case 3: If the threatened piece has value less than or equal to the
2137 // value of the threatening piece, don't prune move which defend it.
2138 if(!PruneDefendingMoves && threat != MOVE_NONE
2139 && (piece_value_midgame(pos.piece_on(tfrom))
2140 >= piece_value_midgame(pos.piece_on(tto)))
2141 && pos.move_attacks_square(m, tto))
2144 // Case 4: Don't prune moves with good history.
2145 if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2148 // Case 5: If the moving piece in the threatened move is a slider, don't
2149 // prune safe moves which block its ray.
2150 if(!PruneBlockingMoves && threat != MOVE_NONE
2151 && piece_is_slider(pos.piece_on(tfrom))
2152 && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2159 // ok_to_use_TT() returns true if a transposition table score
2160 // can be used at a given point in search.
2162 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2164 Value v = value_from_tt(tte->value(), ply);
2166 return ( tte->depth() >= depth
2167 || v >= Max(value_mate_in(100), beta)
2168 || v < Min(value_mated_in(100), beta))
2170 && ( (is_lower_bound(tte->type()) && v >= beta)
2171 || (is_upper_bound(tte->type()) && v < beta));
2175 // ok_to_history() returns true if a move m can be stored
2176 // in history. Should be a non capturing move nor a promotion.
2178 bool ok_to_history(const Position& pos, Move m) {
2180 return !pos.move_is_capture(m) && !move_promotion(m);
2184 // update_history() registers a good move that produced a beta-cutoff
2185 // in history and marks as failures all the other moves of that ply.
2187 void update_history(const Position& pos, Move m, Depth depth,
2188 Move movesSearched[], int moveCount) {
2190 H.success(pos.piece_on(move_from(m)), m, depth);
2192 for (int i = 0; i < moveCount - 1; i++)
2194 assert(m != movesSearched[i]);
2195 if (ok_to_history(pos, movesSearched[i]))
2196 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2200 // fail_high_ply_1() checks if some thread is currently resolving a fail
2201 // high at ply 1 at the node below the first root node. This information
2202 // is used for time managment.
2204 bool fail_high_ply_1() {
2205 for(int i = 0; i < ActiveThreads; i++)
2206 if(Threads[i].failHighPly1)
2212 // current_search_time() returns the number of milliseconds which have passed
2213 // since the beginning of the current search.
2215 int current_search_time() {
2216 return get_system_time() - SearchStartTime;
2220 // nps() computes the current nodes/second count.
2223 int t = current_search_time();
2224 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2228 // poll() performs two different functions: It polls for user input, and it
2229 // looks at the time consumed so far and decides if it's time to abort the
2234 static int lastInfoTime;
2235 int t = current_search_time();
2240 // We are line oriented, don't read single chars
2241 std::string command;
2242 if (!std::getline(std::cin, command))
2245 if (command == "quit")
2248 PonderSearch = false;
2251 else if(command == "stop")
2254 PonderSearch = false;
2256 else if(command == "ponderhit")
2259 // Print search information
2263 else if (lastInfoTime > t)
2264 // HACK: Must be a new search where we searched less than
2265 // NodesBetweenPolls nodes during the first second of search.
2268 else if (t - lastInfoTime >= 1000)
2275 if (dbg_show_hit_rate)
2276 dbg_print_hit_rate();
2278 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2279 << " time " << t << " hashfull " << TT.full() << std::endl;
2280 lock_release(&IOLock);
2281 if (ShowCurrentLine)
2282 Threads[0].printCurrentLine = true;
2284 // Should we stop the search?
2288 bool overTime = t > AbsoluteMaxSearchTime
2289 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2290 || ( !FailHigh && !fail_high_ply_1() && !Problem
2291 && t > 6*(MaxSearchTime + ExtraSearchTime));
2293 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2294 || (ExactMaxTime && t >= ExactMaxTime)
2295 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2300 // ponderhit() is called when the program is pondering (i.e. thinking while
2301 // it's the opponent's turn to move) in order to let the engine know that
2302 // it correctly predicted the opponent's move.
2305 int t = current_search_time();
2306 PonderSearch = false;
2307 if(Iteration >= 2 &&
2308 (!InfiniteSearch && (StopOnPonderhit ||
2309 t > AbsoluteMaxSearchTime ||
2310 (RootMoveNumber == 1 &&
2311 t > MaxSearchTime + ExtraSearchTime) ||
2312 (!FailHigh && !fail_high_ply_1() && !Problem &&
2313 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2318 // print_current_line() prints the current line of search for a given
2319 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2321 void print_current_line(SearchStack ss[], int ply, int threadID) {
2322 assert(ply >= 0 && ply < PLY_MAX);
2323 assert(threadID >= 0 && threadID < ActiveThreads);
2325 if(!Threads[threadID].idle) {
2327 std::cout << "info currline " << (threadID + 1);
2328 for(int p = 0; p < ply; p++)
2329 std::cout << " " << ss[p].currentMove;
2330 std::cout << std::endl;
2331 lock_release(&IOLock);
2333 Threads[threadID].printCurrentLine = false;
2334 if(threadID + 1 < ActiveThreads)
2335 Threads[threadID + 1].printCurrentLine = true;
2339 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2340 // while the program is pondering. The point is to work around a wrinkle in
2341 // the UCI protocol: When pondering, the engine is not allowed to give a
2342 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2343 // We simply wait here until one of these commands is sent, and return,
2344 // after which the bestmove and pondermove will be printed (in id_loop()).
2346 void wait_for_stop_or_ponderhit() {
2347 std::string command;
2350 if(!std::getline(std::cin, command))
2353 if(command == "quit") {
2354 OpeningBook.close();
2359 else if(command == "ponderhit" || command == "stop")
2365 // idle_loop() is where the threads are parked when they have no work to do.
2366 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2367 // object for which the current thread is the master.
2369 void idle_loop(int threadID, SplitPoint *waitSp) {
2370 assert(threadID >= 0 && threadID < THREAD_MAX);
2372 Threads[threadID].running = true;
2375 if(AllThreadsShouldExit && threadID != 0)
2378 // If we are not thinking, wait for a condition to be signaled instead
2379 // of wasting CPU time polling for work:
2380 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2381 #if !defined(_MSC_VER)
2382 pthread_mutex_lock(&WaitLock);
2383 if(Idle || threadID >= ActiveThreads)
2384 pthread_cond_wait(&WaitCond, &WaitLock);
2385 pthread_mutex_unlock(&WaitLock);
2387 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2391 // If this thread has been assigned work, launch a search:
2392 if(Threads[threadID].workIsWaiting) {
2393 Threads[threadID].workIsWaiting = false;
2394 if(Threads[threadID].splitPoint->pvNode)
2395 sp_search_pv(Threads[threadID].splitPoint, threadID);
2397 sp_search(Threads[threadID].splitPoint, threadID);
2398 Threads[threadID].idle = true;
2401 // If this thread is the master of a split point and all threads have
2402 // finished their work at this split point, return from the idle loop:
2403 if(waitSp != NULL && waitSp->cpus == 0)
2407 Threads[threadID].running = false;
2411 // init_split_point_stack() is called during program initialization, and
2412 // initializes all split point objects.
2414 void init_split_point_stack() {
2415 for(int i = 0; i < THREAD_MAX; i++)
2416 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2417 SplitPointStack[i][j].parent = NULL;
2418 lock_init(&(SplitPointStack[i][j].lock), NULL);
2423 // destroy_split_point_stack() is called when the program exits, and
2424 // destroys all locks in the precomputed split point objects.
2426 void destroy_split_point_stack() {
2427 for(int i = 0; i < THREAD_MAX; i++)
2428 for(int j = 0; j < MaxActiveSplitPoints; j++)
2429 lock_destroy(&(SplitPointStack[i][j].lock));
2433 // thread_should_stop() checks whether the thread with a given threadID has
2434 // been asked to stop, directly or indirectly. This can happen if a beta
2435 // cutoff has occured in thre thread's currently active split point, or in
2436 // some ancestor of the current split point.
2438 bool thread_should_stop(int threadID) {
2439 assert(threadID >= 0 && threadID < ActiveThreads);
2443 if(Threads[threadID].stop)
2445 if(ActiveThreads <= 2)
2447 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2449 Threads[threadID].stop = true;
2456 // thread_is_available() checks whether the thread with threadID "slave" is
2457 // available to help the thread with threadID "master" at a split point. An
2458 // obvious requirement is that "slave" must be idle. With more than two
2459 // threads, this is not by itself sufficient: If "slave" is the master of
2460 // some active split point, it is only available as a slave to the other
2461 // threads which are busy searching the split point at the top of "slave"'s
2462 // split point stack (the "helpful master concept" in YBWC terminology).
2464 bool thread_is_available(int slave, int master) {
2465 assert(slave >= 0 && slave < ActiveThreads);
2466 assert(master >= 0 && master < ActiveThreads);
2467 assert(ActiveThreads > 1);
2469 if(!Threads[slave].idle || slave == master)
2472 if(Threads[slave].activeSplitPoints == 0)
2473 // No active split points means that the thread is available as a slave
2474 // for any other thread.
2477 if(ActiveThreads == 2)
2480 // Apply the "helpful master" concept if possible.
2481 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2488 // idle_thread_exists() tries to find an idle thread which is available as
2489 // a slave for the thread with threadID "master".
2491 bool idle_thread_exists(int master) {
2492 assert(master >= 0 && master < ActiveThreads);
2493 assert(ActiveThreads > 1);
2495 for(int i = 0; i < ActiveThreads; i++)
2496 if(thread_is_available(i, master))
2502 // split() does the actual work of distributing the work at a node between
2503 // several threads at PV nodes. If it does not succeed in splitting the
2504 // node (because no idle threads are available, or because we have no unused
2505 // split point objects), the function immediately returns false. If
2506 // splitting is possible, a SplitPoint object is initialized with all the
2507 // data that must be copied to the helper threads (the current position and
2508 // search stack, alpha, beta, the search depth, etc.), and we tell our
2509 // helper threads that they have been assigned work. This will cause them
2510 // to instantly leave their idle loops and call sp_search_pv(). When all
2511 // threads have returned from sp_search_pv (or, equivalently, when
2512 // splitPoint->cpus becomes 0), split() returns true.
2514 bool split(const Position &p, SearchStack *sstck, int ply,
2515 Value *alpha, Value *beta, Value *bestValue,
2516 Depth depth, int *moves,
2517 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2519 assert(sstck != NULL);
2520 assert(ply >= 0 && ply < PLY_MAX);
2521 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2522 assert(!pvNode || *alpha < *beta);
2523 assert(*beta <= VALUE_INFINITE);
2524 assert(depth > Depth(0));
2525 assert(master >= 0 && master < ActiveThreads);
2526 assert(ActiveThreads > 1);
2528 SplitPoint *splitPoint;
2533 // If no other thread is available to help us, or if we have too many
2534 // active split points, don't split:
2535 if(!idle_thread_exists(master) ||
2536 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2537 lock_release(&MPLock);
2541 // Pick the next available split point object from the split point stack:
2542 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2543 Threads[master].activeSplitPoints++;
2545 // Initialize the split point object:
2546 splitPoint->parent = Threads[master].splitPoint;
2547 splitPoint->finished = false;
2548 splitPoint->ply = ply;
2549 splitPoint->depth = depth;
2550 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2551 splitPoint->beta = *beta;
2552 splitPoint->pvNode = pvNode;
2553 splitPoint->dcCandidates = dcCandidates;
2554 splitPoint->bestValue = *bestValue;
2555 splitPoint->master = master;
2556 splitPoint->mp = mp;
2557 splitPoint->moves = *moves;
2558 splitPoint->cpus = 1;
2559 splitPoint->pos.copy(p);
2560 splitPoint->parentSstack = sstck;
2561 for(i = 0; i < ActiveThreads; i++)
2562 splitPoint->slaves[i] = 0;
2564 // Copy the current position and the search stack to the master thread:
2565 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2566 Threads[master].splitPoint = splitPoint;
2568 // Make copies of the current position and search stack for each thread:
2569 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2571 if(thread_is_available(i, master)) {
2572 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2573 Threads[i].splitPoint = splitPoint;
2574 splitPoint->slaves[i] = 1;
2578 // Tell the threads that they have work to do. This will make them leave
2580 for(i = 0; i < ActiveThreads; i++)
2581 if(i == master || splitPoint->slaves[i]) {
2582 Threads[i].workIsWaiting = true;
2583 Threads[i].idle = false;
2584 Threads[i].stop = false;
2587 lock_release(&MPLock);
2589 // Everything is set up. The master thread enters the idle loop, from
2590 // which it will instantly launch a search, because its workIsWaiting
2591 // slot is 'true'. We send the split point as a second parameter to the
2592 // idle loop, which means that the main thread will return from the idle
2593 // loop when all threads have finished their work at this split point
2594 // (i.e. when // splitPoint->cpus == 0).
2595 idle_loop(master, splitPoint);
2597 // We have returned from the idle loop, which means that all threads are
2598 // finished. Update alpha, beta and bestvalue, and return:
2600 if(pvNode) *alpha = splitPoint->alpha;
2601 *beta = splitPoint->beta;
2602 *bestValue = splitPoint->bestValue;
2603 Threads[master].stop = false;
2604 Threads[master].idle = false;
2605 Threads[master].activeSplitPoints--;
2606 Threads[master].splitPoint = splitPoint->parent;
2607 lock_release(&MPLock);
2613 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2614 // to start a new search from the root.
2616 void wake_sleeping_threads() {
2617 if(ActiveThreads > 1) {
2618 for(int i = 1; i < ActiveThreads; i++) {
2619 Threads[i].idle = true;
2620 Threads[i].workIsWaiting = false;
2622 #if !defined(_MSC_VER)
2623 pthread_mutex_lock(&WaitLock);
2624 pthread_cond_broadcast(&WaitCond);
2625 pthread_mutex_unlock(&WaitLock);
2627 for(int i = 1; i < THREAD_MAX; i++)
2628 SetEvent(SitIdleEvent[i]);
2634 // init_thread() is the function which is called when a new thread is
2635 // launched. It simply calls the idle_loop() function with the supplied
2636 // threadID. There are two versions of this function; one for POSIX threads
2637 // and one for Windows threads.
2639 #if !defined(_MSC_VER)
2641 void *init_thread(void *threadID) {
2642 idle_loop(*(int *)threadID, NULL);
2648 DWORD WINAPI init_thread(LPVOID threadID) {
2649 idle_loop(*(int *)threadID, NULL);