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;
177 // Iteration counter:
180 // Scores and number of times the best move changed for each iteration:
181 Value ValueByIteration[PLY_MAX_PLUS_2];
182 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
187 // Time managment variables
189 int MaxNodes, MaxDepth;
190 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, TimeAdvantage;
191 Move BestRootMove, PonderMove, EasyMove;
195 bool StopOnPonderhit;
200 bool PonderingEnabled;
203 // Show current line?
204 bool ShowCurrentLine = false;
207 bool UseLogFile = false;
208 std::ofstream LogFile;
210 // MP related variables
211 Depth MinimumSplitDepth = 4*OnePly;
212 int MaxThreadsPerSplitPoint = 4;
213 Thread Threads[THREAD_MAX];
215 bool AllThreadsShouldExit = false;
216 const int MaxActiveSplitPoints = 8;
217 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
220 #if !defined(_MSC_VER)
221 pthread_cond_t WaitCond;
222 pthread_mutex_t WaitLock;
224 HANDLE SitIdleEvent[THREAD_MAX];
230 Value id_loop(const Position &pos, Move searchMoves[]);
231 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
232 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
233 Depth depth, int ply, int threadID);
234 Value search(Position &pos, SearchStack ss[], Value beta,
235 Depth depth, int ply, bool allowNullmove, int threadID);
236 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
237 Depth depth, int ply, int threadID);
238 void sp_search(SplitPoint *sp, int threadID);
239 void sp_search_pv(SplitPoint *sp, int threadID);
240 void init_search_stack(SearchStack ss[]);
241 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
242 void update_pv(SearchStack ss[], int ply);
243 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
244 bool connected_moves(const Position &pos, Move m1, Move m2);
245 Depth extension(const Position &pos, Move m, bool pvNode, bool check,
246 bool singleReply, bool mateThreat);
247 bool ok_to_do_nullmove(const Position &pos);
248 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
249 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
250 bool ok_to_history(const Position &pos, Move m);
251 void update_history(const Position& pos, Move m, Depth depth,
252 Move movesSearched[], int moveCount);
254 bool fail_high_ply_1();
255 int current_search_time();
259 void print_current_line(SearchStack ss[], int ply, int threadID);
260 void wait_for_stop_or_ponderhit();
262 void idle_loop(int threadID, SplitPoint *waitSp);
263 void init_split_point_stack();
264 void destroy_split_point_stack();
265 bool thread_should_stop(int threadID);
266 bool thread_is_available(int slave, int master);
267 bool idle_thread_exists(int master);
268 bool split(const Position &pos, SearchStack *ss, int ply,
269 Value *alpha, Value *beta, Value *bestValue, Depth depth,
270 int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
272 void wake_sleeping_threads();
274 #if !defined(_MSC_VER)
275 void *init_thread(void *threadID);
277 DWORD WINAPI init_thread(LPVOID threadID);
284 //// Global variables
287 // The main transposition table
288 TranspositionTable TT = TranspositionTable(TTDefaultSize);
291 // Number of active threads:
292 int ActiveThreads = 1;
294 // Locks. In principle, there is no need for IOLock to be a global variable,
295 // but it could turn out to be useful for debugging.
298 History H; // Should be made local?
305 /// think() is the external interface to Stockfish's search, and is called when
306 /// the program receives the UCI 'go' command. It initializes various
307 /// search-related global variables, and calls root_search()
309 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
310 int time[], int increment[], int movesToGo, int maxDepth,
311 int maxNodes, int maxTime, Move searchMoves[]) {
313 // Look for a book move:
314 if(!infinite && !ponder && get_option_value_bool("OwnBook")) {
316 if(get_option_value_string("Book File") != OpeningBook.file_name()) {
318 OpeningBook.open("book.bin");
320 bookMove = OpeningBook.get_move(pos);
321 if(bookMove != MOVE_NONE) {
322 std::cout << "bestmove " << bookMove << std::endl;
327 // Initialize global search variables:
329 SearchStartTime = get_system_time();
330 BestRootMove = MOVE_NONE;
331 PonderMove = MOVE_NONE;
332 EasyMove = MOVE_NONE;
333 for(int i = 0; i < THREAD_MAX; i++) {
334 Threads[i].nodes = 0ULL;
335 Threads[i].failHighPly1 = false;
338 InfiniteSearch = infinite;
339 PonderSearch = ponder;
340 StopOnPonderhit = false;
345 ExactMaxTime = maxTime;
347 // Read UCI option values:
348 TT.set_size(get_option_value_int("Hash"));
349 if(button_was_pressed("Clear Hash"))
351 PonderingEnabled = get_option_value_bool("Ponder");
352 MultiPV = get_option_value_int("MultiPV");
354 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
356 Depth(get_option_value_int("Check Extension (non-PV nodes)"));
357 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
358 SingleReplyExtension[0] =
359 Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
360 PawnPushTo7thExtension[1] =
361 Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
362 PawnPushTo7thExtension[0] =
363 Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
364 PassedPawnExtension[1] =
365 Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
366 PassedPawnExtension[0] =
367 Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
368 PawnEndgameExtension[1] =
369 Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
370 PawnEndgameExtension[0] =
371 Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
372 MateThreatExtension[1] =
373 Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
374 MateThreatExtension[0] =
375 Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
377 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
378 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
379 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
380 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
382 Chess960 = get_option_value_bool("UCI_Chess960");
383 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
384 UseLogFile = get_option_value_bool("Use Search Log");
386 LogFile.open(get_option_value_string("Search Log Filename").c_str(),
387 std::ios::out | std::ios::app);
389 UseQSearchFutilityPruning =
390 get_option_value_bool("Futility Pruning (Quiescence Search)");
392 get_option_value_bool("Futility Pruning (Main Search)");
395 value_from_centipawns(get_option_value_int("Futility Margin 0"));
397 value_from_centipawns(get_option_value_int("Futility Margin 1"));
399 value_from_centipawns(get_option_value_int("Futility Margin 2"));
401 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
402 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
404 UseLSNFiltering = get_option_value_bool("LSN filtering");
405 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
406 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
408 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
409 MaxThreadsPerSplitPoint =
410 get_option_value_int("Maximum Number of Threads per Split Point");
412 read_weights(pos.side_to_move());
414 int newActiveThreads = get_option_value_int("Threads");
415 if(newActiveThreads != ActiveThreads) {
416 ActiveThreads = newActiveThreads;
417 init_eval(ActiveThreads);
420 // Wake up sleeping threads:
421 wake_sleeping_threads();
423 for(int i = 1; i < ActiveThreads; i++)
424 assert(thread_is_available(i, 0));
426 // Set thinking time:
427 int myTime = time[side_to_move];
428 int myIncrement = increment[side_to_move];
429 int oppTime = time[1 - side_to_move];
431 TimeAdvantage = myTime - oppTime;
433 if(!movesToGo) { // Sudden death time control
435 MaxSearchTime = myTime / 30 + myIncrement;
436 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)
445 MaxSearchTime = myTime / 2;
446 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
449 MaxSearchTime = myTime / Min(movesToGo, 20);
450 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
453 if(PonderingEnabled) {
454 MaxSearchTime += MaxSearchTime / 4;
455 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
458 // Fixed depth or fixed number of nodes?
461 InfiniteSearch = true; // HACK
465 NodesBetweenPolls = Min(MaxNodes, 30000);
466 InfiniteSearch = true; // HACK
469 NodesBetweenPolls = 30000;
472 // Write information to search log file:
474 LogFile << "Searching: " << pos.to_fen() << '\n';
475 LogFile << "infinite: " << infinite << " ponder: " << ponder
476 << " time: " << myTime << " increment: " << myIncrement
477 << " moves to go: " << movesToGo << '\n';
480 // We're ready to start thinking. Call the iterative deepening loop
484 Value v = id_loop(pos, searchMoves);
485 looseOnTime = ( UseLSNFiltering
492 looseOnTime = false; // reset for next match
493 while (SearchStartTime + myTime + 1000 > get_system_time())
495 id_loop(pos, searchMoves); // to fail gracefully
512 /// init_threads() is called during startup. It launches all helper threads,
513 /// and initializes the split point stack and the global locks and condition
516 void init_threads() {
518 #if !defined(_MSC_VER)
519 pthread_t pthread[1];
522 for(i = 0; i < THREAD_MAX; i++)
523 Threads[i].activeSplitPoints = 0;
525 // Initialize global locks:
526 lock_init(&MPLock, NULL);
527 lock_init(&IOLock, NULL);
529 init_split_point_stack();
531 #if !defined(_MSC_VER)
532 pthread_mutex_init(&WaitLock, NULL);
533 pthread_cond_init(&WaitCond, NULL);
535 for(i = 0; i < THREAD_MAX; i++)
536 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
539 // All threads except the main thread should be initialized to idle state:
540 for(i = 1; i < THREAD_MAX; i++) {
541 Threads[i].stop = false;
542 Threads[i].workIsWaiting = false;
543 Threads[i].idle = true;
544 Threads[i].running = false;
547 // Launch the helper threads:
548 for(i = 1; i < THREAD_MAX; i++) {
549 #if !defined(_MSC_VER)
550 pthread_create(pthread, NULL, init_thread, (void*)(&i));
554 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
558 // Wait until the thread has finished launching:
559 while(!Threads[i].running);
564 /// stop_threads() is called when the program exits. It makes all the
565 /// helper threads exit cleanly.
567 void stop_threads() {
568 ActiveThreads = THREAD_MAX; // HACK
569 Idle = false; // HACK
570 wake_sleeping_threads();
571 AllThreadsShouldExit = true;
572 for(int i = 1; i < THREAD_MAX; i++) {
573 Threads[i].stop = true;
574 while(Threads[i].running);
576 destroy_split_point_stack();
580 /// nodes_searched() returns the total number of nodes searched so far in
581 /// the current search.
583 int64_t nodes_searched() {
584 int64_t result = 0ULL;
585 for(int i = 0; i < ActiveThreads; i++)
586 result += Threads[i].nodes;
593 // id_loop() is the main iterative deepening loop. It calls root_search
594 // repeatedly with increasing depth until the allocated thinking time has
595 // been consumed, the user stops the search, or the maximum search depth is
598 Value id_loop(const Position &pos, Move searchMoves[]) {
600 SearchStack ss[PLY_MAX_PLUS_2];
602 // searchMoves are verified, copied, scored and sorted
603 RootMoveList rml(p, searchMoves);
608 init_search_stack(ss);
610 ValueByIteration[0] = Value(0);
611 ValueByIteration[1] = rml.get_move_score(0);
614 EasyMove = rml.scan_for_easy_move();
616 // Iterative deepening loop
617 while(!AbortSearch && Iteration < PLY_MAX) {
619 // Initialize iteration
622 BestMoveChangesByIteration[Iteration] = 0;
626 std::cout << "info depth " << Iteration << std::endl;
628 // Search to the current depth
629 ValueByIteration[Iteration] = root_search(p, ss, rml);
631 // Erase the easy move if it differs from the new best move
632 if(ss[0].pv[0] != EasyMove)
633 EasyMove = MOVE_NONE;
637 if(!InfiniteSearch) {
639 bool stopSearch = false;
641 // Stop search early if there is only a single legal move:
642 if(Iteration >= 6 && rml.move_count() == 1)
645 // Stop search early when the last two iterations returned a mate
648 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
649 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
652 // Stop search early if one move seems to be much better than the
654 int64_t nodes = nodes_searched();
655 if(Iteration >= 8 && EasyMove == ss[0].pv[0] &&
656 ((rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100 &&
657 current_search_time() > MaxSearchTime / 16) ||
658 (rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100 &&
659 current_search_time() > MaxSearchTime / 32)))
662 // Add some extra time if the best move has changed during the last
664 if(Iteration > 5 && Iteration <= 50)
666 BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2) +
667 BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
669 // If we need some more and we are in time advantage take it.
670 if (ExtraSearchTime > 0 && TimeAdvantage > 2 * MaxSearchTime)
671 ExtraSearchTime += MaxSearchTime / 2;
673 // Stop search if most of MaxSearchTime is consumed at the end of the
674 // iteration. We probably don't have enough time to search the first
675 // move at the next iteration anyway.
676 if(current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
683 StopOnPonderhit = true;
687 // Write PV to transposition table, in case the relevant entries have
688 // been overwritten during the search:
689 TT.insert_pv(p, ss[0].pv);
691 if(MaxDepth && Iteration >= MaxDepth)
697 // If we are pondering, we shouldn't print the best move before we
700 wait_for_stop_or_ponderhit();
702 // Print final search statistics
703 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
704 << " time " << current_search_time()
705 << " hashfull " << TT.full() << std::endl;
707 // Print the best move and the ponder move to the standard output:
708 std::cout << "bestmove " << ss[0].pv[0];
709 if(ss[0].pv[1] != MOVE_NONE)
710 std::cout << " ponder " << ss[0].pv[1];
711 std::cout << std::endl;
715 LogFile << "Nodes: " << nodes_searched() << '\n';
716 LogFile << "Nodes/second: " << nps() << '\n';
717 LogFile << "Best move: " << move_to_san(p, ss[0].pv[0]) << '\n';
718 p.do_move(ss[0].pv[0], u);
719 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1]) << '\n';
720 LogFile << std::endl;
722 return rml.get_move_score(0);
726 // root_search() is the function which searches the root node. It is
727 // similar to search_pv except that it uses a different move ordering
728 // scheme (perhaps we should try to use this at internal PV nodes, too?)
729 // and prints some information to the standard output.
731 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
732 Value alpha = -VALUE_INFINITE, beta = VALUE_INFINITE, value;
733 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
735 // Loop through all the moves in the root move list:
736 for(int i = 0; i < rml.move_count() && !AbortSearch; i++) {
742 RootMoveNumber = i + 1;
745 // Remember the node count before the move is searched. The node counts
746 // are used to sort the root moves at the next iteration.
747 nodes = nodes_searched();
749 // Pick the next root move, and print the move and the move number to
750 // the standard output:
751 move = ss[0].currentMove = rml.get_move(i);
752 if(current_search_time() >= 1000)
753 std::cout << "info currmove " << move
754 << " currmovenumber " << i + 1 << std::endl;
756 // Decide search depth for this move:
757 ext = extension(pos, move, true, pos.move_is_check(move), false, false);
758 newDepth = (Iteration-2)*OnePly + ext + InitialDepth;
760 // Make the move, and search it.
761 pos.do_move(move, u, dcCandidates);
764 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
765 // If the value has dropped a lot compared to the last iteration,
766 // set the boolean variable Problem to true. This variable is used
767 // for time managment: When Problem is true, we try to complete the
768 // current iteration before playing a move.
769 Problem = (Iteration >= 2 &&
770 value <= ValueByIteration[Iteration-1] - ProblemMargin);
771 if(Problem && StopOnPonderhit)
772 StopOnPonderhit = false;
775 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
777 // Fail high! Set the boolean variable FailHigh to true, and
778 // re-search the move with a big window. The variable FailHigh is
779 // used for time managment: We try to avoid aborting the search
780 // prematurely during a fail high research.
782 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
786 pos.undo_move(move, u);
788 // Finished searching the move. If AbortSearch is true, the search
789 // was aborted because the user interrupted the search or because we
790 // ran out of time. In this case, the return value of the search cannot
791 // be trusted, and we break out of the loop without updating the best
796 // Remember the node count for this move. The node counts are used to
797 // sort the root moves at the next iteration.
798 rml.set_move_nodes(i, nodes_searched() - nodes);
800 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
802 if(value <= alpha && i >= MultiPV)
803 rml.set_move_score(i, -VALUE_INFINITE);
808 rml.set_move_score(i, value);
810 rml.set_move_pv(i, ss[0].pv);
813 // We record how often the best move has been changed in each
814 // iteration. This information is used for time managment: When
815 // the best move changes frequently, we allocate some more time.
817 BestMoveChangesByIteration[Iteration]++;
819 // Print search information to the standard output:
820 std::cout << "info depth " << Iteration
821 << " score " << value_to_string(value)
822 << " time " << current_search_time()
823 << " nodes " << nodes_searched()
826 for(int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
827 std::cout << ss[0].pv[j] << " ";
828 std::cout << std::endl;
831 LogFile << pretty_pv(pos, current_search_time(), Iteration,
832 nodes_searched(), value, ss[0].pv)
837 // Reset the global variable Problem to false if the value isn't too
838 // far below the final value from the last iteration.
839 if(value > ValueByIteration[Iteration - 1] - NoProblemMargin)
842 else { // MultiPV > 1
844 for(int j = 0; j < Min(MultiPV, rml.move_count()); j++) {
846 std::cout << "info multipv " << j + 1
847 << " score " << value_to_string(rml.get_move_score(j))
848 << " depth " << ((j <= i)? Iteration : Iteration - 1)
849 << " time " << current_search_time()
850 << " nodes " << nodes_searched()
853 for(k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
854 std::cout << rml.get_move_pv(j, k) << " ";
855 std::cout << std::endl;
857 alpha = rml.get_move_score(Min(i, MultiPV-1));
865 // search_pv() is the main search function for PV nodes.
867 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
868 Depth depth, int ply, int threadID) {
870 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
871 assert(beta > alpha && beta <= VALUE_INFINITE);
872 assert(ply >= 0 && ply < PLY_MAX);
873 assert(threadID >= 0 && threadID < ActiveThreads);
877 // Initialize, and make an early exit in case of an aborted search,
878 // an instant draw, maximum ply reached, etc.
879 Value oldAlpha = alpha;
881 if (AbortSearch || thread_should_stop(threadID))
885 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
887 init_node(pos, ss, ply, threadID);
892 if (ply >= PLY_MAX - 1)
893 return evaluate(pos, ei, threadID);
895 // Mate distance pruning
896 alpha = Max(value_mated_in(ply), alpha);
897 beta = Min(value_mate_in(ply+1), beta);
901 // Transposition table lookup. At PV nodes, we don't use the TT for
902 // pruning, but only for move ordering.
903 const TTEntry* tte = TT.retrieve(pos);
905 Move ttMove = (tte ? tte->move() : MOVE_NONE);
907 // Go with internal iterative deepening if we don't have a TT move
908 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
910 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
911 ttMove = ss[ply].pv[ply];
914 // Initialize a MovePicker object for the current position, and prepare
915 // to search all moves:
916 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply].mateKiller,
917 ss[ply].killer1, ss[ply].killer2, depth);
919 Move move, movesSearched[256];
921 Value value, bestValue = -VALUE_INFINITE;
922 Bitboard dcCandidates = mp.discovered_check_candidates();
923 bool mateThreat = MateThreatExtension[1] > Depth(0)
924 && pos.has_mate_threat(opposite_color(pos.side_to_move()));
926 // Loop through all legal moves until no moves remain or a beta cutoff
929 && (move = mp.get_next_move()) != MOVE_NONE
930 && !thread_should_stop(threadID))
932 assert(move_is_ok(move));
934 bool singleReply = (pos.is_check() && mp.number_of_moves() == 1);
935 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
936 bool moveIsCapture = pos.move_is_capture(move);
937 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
939 movesSearched[moveCount++] = ss[ply].currentMove = move;
941 ss[ply].currentMoveCaptureValue = move_is_ep(move) ?
942 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
944 // Decide the new search depth
945 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat);
946 Depth newDepth = depth - OnePly + ext;
948 // Make and search the move
950 pos.do_move(move, u, dcCandidates);
952 if (moveCount == 1) // The first move in list is the PV
953 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
956 // Try to reduce non-pv search depth by one ply if move seems not problematic,
957 // if the move fails high will be re-searched at full depth.
958 if ( depth >= 2*OnePly
960 && moveCount >= LMRPVMoves
962 && !move_promotion(move)
963 && !moveIsPassedPawnPush
964 && !move_is_castle(move)
965 && move != ss[ply].killer1
966 && move != ss[ply].killer2)
968 ss[ply].reduction = OnePly;
969 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
972 value = alpha + 1; // Just to trigger next condition
974 if (value > alpha) // Go with full depth pv search
976 ss[ply].reduction = Depth(0);
977 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
978 if (value > alpha && value < beta)
980 // When the search fails high at ply 1 while searching the first
981 // move at the root, set the flag failHighPly1. This is used for
982 // time managment: We don't want to stop the search early in
983 // such cases, because resolving the fail high at ply 1 could
984 // result in a big drop in score at the root.
985 if (ply == 1 && RootMoveNumber == 1)
986 Threads[threadID].failHighPly1 = true;
988 // A fail high occurred. Re-search at full window (pv search)
989 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
990 Threads[threadID].failHighPly1 = false;
994 pos.undo_move(move, u);
996 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
999 if (value > bestValue)
1006 if (value == value_mate_in(ply + 1))
1007 ss[ply].mateKiller = move;
1009 // If we are at ply 1, and we are searching the first root move at
1010 // ply 0, set the 'Problem' variable if the score has dropped a lot
1011 // (from the computer's point of view) since the previous iteration:
1012 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1017 if ( ActiveThreads > 1
1019 && depth >= MinimumSplitDepth
1021 && idle_thread_exists(threadID)
1023 && !thread_should_stop(threadID)
1024 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1025 &moveCount, &mp, dcCandidates, threadID, true))
1029 // All legal moves have been searched. A special case: If there were
1030 // no legal moves, it must be mate or stalemate:
1032 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1034 // If the search is not aborted, update the transposition table,
1035 // history counters, and killer moves.
1036 if (AbortSearch || thread_should_stop(threadID))
1039 if (bestValue <= oldAlpha)
1040 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1042 else if (bestValue >= beta)
1044 Move m = ss[ply].pv[ply];
1045 if (ok_to_history(pos, m)) // Only non capture moves are considered
1047 update_history(pos, m, depth, movesSearched, moveCount);
1048 if (m != ss[ply].killer1)
1050 ss[ply].killer2 = ss[ply].killer1;
1051 ss[ply].killer1 = m;
1054 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1057 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1063 // search() is the search function for zero-width nodes.
1065 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1066 int ply, bool allowNullmove, int threadID) {
1068 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1069 assert(ply >= 0 && ply < PLY_MAX);
1070 assert(threadID >= 0 && threadID < ActiveThreads);
1074 // Initialize, and make an early exit in case of an aborted search,
1075 // an instant draw, maximum ply reached, etc.
1076 if (AbortSearch || thread_should_stop(threadID))
1080 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1082 init_node(pos, ss, ply, threadID);
1087 if (ply >= PLY_MAX - 1)
1088 return evaluate(pos, ei, threadID);
1090 // Mate distance pruning
1091 if (value_mated_in(ply) >= beta)
1094 if (value_mate_in(ply + 1) < beta)
1097 // Transposition table lookup
1098 const TTEntry* tte = TT.retrieve(pos);
1100 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1102 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1104 ss[ply].currentMove = ttMove; // can be MOVE_NONE ?
1105 return value_from_tt(tte->value(), ply);
1108 Value approximateEval = quick_evaluate(pos);
1109 bool mateThreat = false;
1114 && ok_to_do_nullmove(pos)
1115 && approximateEval >= beta - NullMoveMargin)
1117 ss[ply].currentMove = MOVE_NULL;
1120 pos.do_null_move(u);
1121 Value nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false, threadID);
1122 pos.undo_null_move(u);
1124 if (nullValue >= beta)
1126 if (depth < 6 * OnePly)
1129 // Do zugzwang verification search
1130 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1134 // The null move failed low, which means that we may be faced with
1135 // some kind of threat. If the previous move was reduced, check if
1136 // the move that refuted the null move was somehow connected to the
1137 // move which was reduced. If a connection is found, return a fail
1138 // low score (which will cause the reduced move to fail high in the
1139 // parent node, which will trigger a re-search with full depth).
1140 if (nullValue == value_mated_in(ply + 2))
1143 ss[ply].threatMove = ss[ply + 1].currentMove;
1144 if ( depth < ThreatDepth
1145 && ss[ply - 1].reduction
1146 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1150 // Null move search not allowed, try razoring
1151 else if ( (approximateEval < beta - RazorMargin && depth < RazorDepth)
1152 ||(approximateEval < beta - PawnValueMidgame && depth <= OnePly))
1154 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1159 // Go with internal iterative deepening if we don't have a TT move
1160 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1161 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1163 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1164 ttMove = ss[ply].pv[ply];
1167 // Initialize a MovePicker object for the current position, and prepare
1168 // to search all moves:
1169 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply].mateKiller,
1170 ss[ply].killer1, ss[ply].killer2, depth);
1172 Move move, movesSearched[256];
1174 Value value, bestValue = -VALUE_INFINITE;
1175 Bitboard dcCandidates = mp.discovered_check_candidates();
1176 Value futilityValue = VALUE_NONE;
1177 bool isCheck = pos.is_check();
1178 bool useFutilityPruning = UseFutilityPruning
1179 && depth < SelectiveDepth
1182 // Loop through all legal moves until no moves remain or a beta cutoff
1184 while ( bestValue < beta
1185 && (move = mp.get_next_move()) != MOVE_NONE
1186 && !thread_should_stop(threadID))
1188 assert(move_is_ok(move));
1190 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1191 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1192 bool moveIsCapture = pos.move_is_capture(move);
1193 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1195 movesSearched[moveCount++] = ss[ply].currentMove = move;
1197 // Decide the new search depth
1198 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat);
1199 Depth newDepth = depth - OnePly + ext;
1202 if ( useFutilityPruning
1205 && !moveIsPassedPawnPush
1206 && !move_promotion(move))
1208 if ( moveCount >= 2 + int(depth)
1209 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1212 if (depth < 3 * OnePly && approximateEval < beta)
1214 if (futilityValue == VALUE_NONE)
1215 futilityValue = evaluate(pos, ei, threadID)
1216 + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2);
1218 if (futilityValue < beta)
1220 if (futilityValue > bestValue)
1221 bestValue = futilityValue;
1227 // Make and search the move
1229 pos.do_move(move, u, dcCandidates);
1231 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1232 // if the move fails high will be re-searched at full depth.
1233 if ( depth >= 2*OnePly
1235 && moveCount >= LMRNonPVMoves
1237 && !move_promotion(move)
1238 && !moveIsPassedPawnPush
1239 && !move_is_castle(move)
1240 && move != ss[ply].killer1
1241 && move != ss[ply].killer2)
1243 ss[ply].reduction = OnePly;
1244 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1247 value = beta; // Just to trigger next condition
1249 if (value >= beta) // Go with full depth non-pv search
1251 ss[ply].reduction = Depth(0);
1252 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1254 pos.undo_move(move, u);
1256 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1259 if (value > bestValue)
1265 if (value == value_mate_in(ply + 1))
1266 ss[ply].mateKiller = move;
1270 if ( ActiveThreads > 1
1272 && depth >= MinimumSplitDepth
1274 && idle_thread_exists(threadID)
1276 && !thread_should_stop(threadID)
1277 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1278 &mp, dcCandidates, threadID, false))
1282 // All legal moves have been searched. A special case: If there were
1283 // no legal moves, it must be mate or stalemate:
1285 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1287 // If the search is not aborted, update the transposition table,
1288 // history counters, and killer moves.
1289 if (AbortSearch || thread_should_stop(threadID))
1292 if (bestValue < beta)
1293 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1296 Move m = ss[ply].pv[ply];
1297 if (ok_to_history(pos, m)) // Only non capture moves are considered
1299 update_history(pos, m, depth, movesSearched, moveCount);
1300 if (m != ss[ply].killer1)
1302 ss[ply].killer2 = ss[ply].killer1;
1303 ss[ply].killer1 = m;
1306 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1312 // qsearch() is the quiescence search function, which is called by the main
1313 // search function when the remaining depth is zero (or, to be more precise,
1314 // less than OnePly).
1316 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1317 Depth depth, int ply, int threadID) {
1319 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1320 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1322 assert(ply >= 0 && ply < PLY_MAX);
1323 assert(threadID >= 0 && threadID < ActiveThreads);
1327 // Initialize, and make an early exit in case of an aborted search,
1328 // an instant draw, maximum ply reached, etc.
1329 if (AbortSearch || thread_should_stop(threadID))
1332 init_node(pos, ss, ply, threadID);
1337 // Transposition table lookup
1338 const TTEntry* tte = TT.retrieve(pos);
1339 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1340 return value_from_tt(tte->value(), ply);
1342 // Evaluate the position statically:
1343 Value staticValue = evaluate(pos, ei, threadID);
1345 if (ply == PLY_MAX - 1)
1348 // Initialize "stand pat score", and return it immediately if it is
1350 Value bestValue = (pos.is_check() ? -VALUE_INFINITE : staticValue);
1352 if (bestValue >= beta)
1355 if (bestValue > alpha)
1358 // Initialize a MovePicker object for the current position, and prepare
1359 // to search the moves. Because the depth is <= 0 here, only captures,
1360 // queen promotions and checks (only if depth == 0) will be generated.
1361 MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1365 Bitboard dcCandidates = mp.discovered_check_candidates();
1366 bool isCheck = pos.is_check();
1368 // Loop through the moves until no moves remain or a beta cutoff
1370 while ( alpha < beta
1371 && (move = mp.get_next_move()) != MOVE_NONE)
1373 assert(move_is_ok(move));
1375 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1376 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1379 ss[ply].currentMove = move;
1382 if ( UseQSearchFutilityPruning
1385 && !move_promotion(move)
1386 && !moveIsPassedPawnPush
1387 && beta - alpha == 1
1388 && pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame)
1390 Value futilityValue = staticValue
1391 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1392 pos.endgame_value_of_piece_on(move_to(move)))
1394 + ei.futilityMargin;
1396 if (futilityValue < alpha)
1398 if (futilityValue > bestValue)
1399 bestValue = futilityValue;
1404 // Don't search captures and checks with negative SEE values.
1406 && !move_promotion(move)
1407 && (pos.midgame_value_of_piece_on(move_from(move)) >
1408 pos.midgame_value_of_piece_on(move_to(move)))
1409 && pos.see(move) < 0)
1412 // Make and search the move.
1414 pos.do_move(move, u, dcCandidates);
1415 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1416 pos.undo_move(move, u);
1418 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1421 if (value > bestValue)
1432 // All legal moves have been searched. A special case: If we're in check
1433 // and no legal moves were found, it is checkmate:
1434 if (pos.is_check() && moveCount == 0) // Mate!
1435 return value_mated_in(ply);
1437 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1439 // Update transposition table
1440 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1446 // sp_search() is used to search from a split point. This function is called
1447 // by each thread working at the split point. It is similar to the normal
1448 // search() function, but simpler. Because we have already probed the hash
1449 // table, done a null move search, and searched the first move before
1450 // splitting, we don't have to repeat all this work in sp_search(). We
1451 // also don't need to store anything to the hash table here: This is taken
1452 // care of after we return from the split point.
1454 void sp_search(SplitPoint *sp, int threadID) {
1456 assert(threadID >= 0 && threadID < ActiveThreads);
1457 assert(ActiveThreads > 1);
1459 Position pos = Position(sp->pos);
1460 SearchStack *ss = sp->sstack[threadID];
1463 bool isCheck = pos.is_check();
1464 bool useFutilityPruning = UseFutilityPruning
1465 && sp->depth < SelectiveDepth
1468 while ( sp->bestValue < sp->beta
1469 && !thread_should_stop(threadID)
1470 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1472 assert(move_is_ok(move));
1474 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1475 bool moveIsCapture = pos.move_is_capture(move);
1476 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1478 lock_grab(&(sp->lock));
1479 int moveCount = ++sp->moves;
1480 lock_release(&(sp->lock));
1482 ss[sp->ply].currentMove = move;
1484 // Decide the new search depth.
1485 Depth ext = extension(pos, move, false, moveIsCheck, false, false);
1486 Depth newDepth = sp->depth - OnePly + ext;
1489 if ( useFutilityPruning
1492 && !moveIsPassedPawnPush
1493 && !move_promotion(move)
1494 && moveCount >= 2 + int(sp->depth)
1495 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1498 // Make and search the move.
1500 pos.do_move(move, u, sp->dcCandidates);
1502 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1503 // if the move fails high will be re-searched at full depth.
1504 if ( ext == Depth(0)
1505 && moveCount >= LMRNonPVMoves
1507 && !moveIsPassedPawnPush
1508 && !move_promotion(move)
1509 && !move_is_castle(move)
1510 && move != ss[sp->ply].killer1
1511 && move != ss[sp->ply].killer2)
1513 ss[sp->ply].reduction = OnePly;
1514 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1517 value = sp->beta; // Just to trigger next condition
1519 if (value >= sp->beta) // Go with full depth non-pv search
1521 ss[sp->ply].reduction = Depth(0);
1522 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1524 pos.undo_move(move, u);
1526 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1528 if (thread_should_stop(threadID))
1532 lock_grab(&(sp->lock));
1533 if (value > sp->bestValue && !thread_should_stop(threadID))
1535 sp->bestValue = value;
1536 if (sp->bestValue >= sp->beta)
1538 sp_update_pv(sp->parentSstack, ss, sp->ply);
1539 for (int i = 0; i < ActiveThreads; i++)
1540 if (i != threadID && (i == sp->master || sp->slaves[i]))
1541 Threads[i].stop = true;
1543 sp->finished = true;
1546 lock_release(&(sp->lock));
1549 lock_grab(&(sp->lock));
1551 // If this is the master thread and we have been asked to stop because of
1552 // a beta cutoff higher up in the tree, stop all slave threads:
1553 if (sp->master == threadID && thread_should_stop(threadID))
1554 for (int i = 0; i < ActiveThreads; i++)
1556 Threads[i].stop = true;
1559 sp->slaves[threadID] = 0;
1561 lock_release(&(sp->lock));
1565 // sp_search_pv() is used to search from a PV split point. This function
1566 // is called by each thread working at the split point. It is similar to
1567 // the normal search_pv() function, but simpler. Because we have already
1568 // probed the hash table and searched the first move before splitting, we
1569 // don't have to repeat all this work in sp_search_pv(). We also don't
1570 // need to store anything to the hash table here: This is taken care of
1571 // after we return from the split point.
1573 void sp_search_pv(SplitPoint *sp, int threadID) {
1575 assert(threadID >= 0 && threadID < ActiveThreads);
1576 assert(ActiveThreads > 1);
1578 Position pos = Position(sp->pos);
1579 SearchStack *ss = sp->sstack[threadID];
1583 while ( sp->alpha < sp->beta
1584 && !thread_should_stop(threadID)
1585 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1587 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1588 bool moveIsCapture = pos.move_is_capture(move);
1589 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1591 assert(move_is_ok(move));
1593 ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1594 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1596 lock_grab(&(sp->lock));
1597 int moveCount = ++sp->moves;
1598 lock_release(&(sp->lock));
1600 ss[sp->ply].currentMove = move;
1602 // Decide the new search depth.
1603 Depth ext = extension(pos, move, true, moveIsCheck, false, false);
1604 Depth newDepth = sp->depth - OnePly + ext;
1606 // Make and search the move.
1608 pos.do_move(move, u, sp->dcCandidates);
1610 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1611 // if the move fails high will be re-searched at full depth.
1612 if ( ext == Depth(0)
1613 && moveCount >= LMRPVMoves
1615 && !moveIsPassedPawnPush
1616 && !move_promotion(move)
1617 && !move_is_castle(move)
1618 && move != ss[sp->ply].killer1
1619 && move != ss[sp->ply].killer2)
1621 ss[sp->ply].reduction = OnePly;
1622 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1625 value = sp->alpha + 1; // Just to trigger next condition
1627 if (value > sp->alpha) // Go with full depth non-pv search
1629 ss[sp->ply].reduction = Depth(0);
1630 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1632 if (value > sp->alpha && value < sp->beta)
1634 // When the search fails high at ply 1 while searching the first
1635 // move at the root, set the flag failHighPly1. This is used for
1636 // time managment: We don't want to stop the search early in
1637 // such cases, because resolving the fail high at ply 1 could
1638 // result in a big drop in score at the root.
1639 if (sp->ply == 1 && RootMoveNumber == 1)
1640 Threads[threadID].failHighPly1 = true;
1642 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1643 Threads[threadID].failHighPly1 = false;
1646 pos.undo_move(move, u);
1648 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1650 if (thread_should_stop(threadID))
1654 lock_grab(&(sp->lock));
1655 if (value > sp->bestValue && !thread_should_stop(threadID))
1657 sp->bestValue = value;
1658 if (value > sp->alpha)
1661 sp_update_pv(sp->parentSstack, ss, sp->ply);
1662 if (value == value_mate_in(sp->ply + 1))
1663 ss[sp->ply].mateKiller = move;
1665 if(value >= sp->beta)
1667 for(int i = 0; i < ActiveThreads; i++)
1668 if(i != threadID && (i == sp->master || sp->slaves[i]))
1669 Threads[i].stop = true;
1671 sp->finished = true;
1674 // If we are at ply 1, and we are searching the first root move at
1675 // ply 0, set the 'Problem' variable if the score has dropped a lot
1676 // (from the computer's point of view) since the previous iteration:
1677 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1680 lock_release(&(sp->lock));
1683 lock_grab(&(sp->lock));
1685 // If this is the master thread and we have been asked to stop because of
1686 // a beta cutoff higher up in the tree, stop all slave threads:
1687 if (sp->master == threadID && thread_should_stop(threadID))
1688 for (int i = 0; i < ActiveThreads; i++)
1690 Threads[i].stop = true;
1693 sp->slaves[threadID] = 0;
1695 lock_release(&(sp->lock));
1699 /// The RootMove class
1703 RootMove::RootMove() {
1704 nodes = cumulativeNodes = 0ULL;
1707 // RootMove::operator<() is the comparison function used when
1708 // sorting the moves. A move m1 is considered to be better
1709 // than a move m2 if it has a higher score, or if the moves
1710 // have equal score but m1 has the higher node count.
1712 bool RootMove::operator<(const RootMove& m) {
1714 if (score != m.score)
1715 return (score < m.score);
1717 return nodes <= m.nodes;
1720 /// The RootMoveList class
1724 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1726 MoveStack mlist[MaxRootMoves];
1727 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1729 // Generate all legal moves
1730 int lm_count = generate_legal_moves(pos, mlist);
1732 // Add each move to the moves[] array
1733 for (int i = 0; i < lm_count; i++)
1735 bool includeMove = includeAllMoves;
1737 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1738 includeMove = (searchMoves[k] == mlist[i].move);
1742 // Find a quick score for the move
1744 SearchStack ss[PLY_MAX_PLUS_2];
1746 moves[count].move = mlist[i].move;
1747 moves[count].nodes = 0ULL;
1748 pos.do_move(moves[count].move, u);
1749 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1751 pos.undo_move(moves[count].move, u);
1752 moves[count].pv[0] = moves[i].move;
1753 moves[count].pv[1] = MOVE_NONE; // FIXME
1761 // Simple accessor methods for the RootMoveList class
1763 inline Move RootMoveList::get_move(int moveNum) const {
1764 return moves[moveNum].move;
1767 inline Value RootMoveList::get_move_score(int moveNum) const {
1768 return moves[moveNum].score;
1771 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1772 moves[moveNum].score = score;
1775 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1776 moves[moveNum].nodes = nodes;
1777 moves[moveNum].cumulativeNodes += nodes;
1780 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1782 for(j = 0; pv[j] != MOVE_NONE; j++)
1783 moves[moveNum].pv[j] = pv[j];
1784 moves[moveNum].pv[j] = MOVE_NONE;
1787 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1788 return moves[moveNum].pv[i];
1791 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1792 return moves[moveNum].cumulativeNodes;
1795 inline int RootMoveList::move_count() const {
1800 // RootMoveList::scan_for_easy_move() is called at the end of the first
1801 // iteration, and is used to detect an "easy move", i.e. a move which appears
1802 // to be much bester than all the rest. If an easy move is found, the move
1803 // is returned, otherwise the function returns MOVE_NONE. It is very
1804 // important that this function is called at the right moment: The code
1805 // assumes that the first iteration has been completed and the moves have
1806 // been sorted. This is done in RootMoveList c'tor.
1808 Move RootMoveList::scan_for_easy_move() const {
1815 // moves are sorted so just consider the best and the second one
1816 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1822 // RootMoveList::sort() sorts the root move list at the beginning of a new
1825 inline void RootMoveList::sort() {
1827 sort_multipv(count - 1); // all items
1831 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1832 // list by their scores and depths. It is used to order the different PVs
1833 // correctly in MultiPV mode.
1835 void RootMoveList::sort_multipv(int n) {
1837 for (int i = 1; i <= n; i++)
1839 RootMove rm = moves[i];
1841 for (j = i; j > 0 && moves[j-1] < rm; j--)
1842 moves[j] = moves[j-1];
1848 // init_search_stack() initializes a search stack at the beginning of a
1849 // new search from the root.
1851 void init_search_stack(SearchStack ss[]) {
1852 for(int i = 0; i < 3; i++) {
1853 ss[i].pv[i] = MOVE_NONE;
1854 ss[i].pv[i+1] = MOVE_NONE;
1855 ss[i].currentMove = MOVE_NONE;
1856 ss[i].mateKiller = MOVE_NONE;
1857 ss[i].killer1 = MOVE_NONE;
1858 ss[i].killer2 = MOVE_NONE;
1859 ss[i].threatMove = MOVE_NONE;
1860 ss[i].reduction = Depth(0);
1865 // init_node() is called at the beginning of all the search functions
1866 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1867 // stack object corresponding to the current node. Once every
1868 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1869 // for user input and checks whether it is time to stop the search.
1871 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1872 assert(ply >= 0 && ply < PLY_MAX);
1873 assert(threadID >= 0 && threadID < ActiveThreads);
1875 Threads[threadID].nodes++;
1879 if(NodesSincePoll >= NodesBetweenPolls) {
1885 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1886 ss[ply+2].mateKiller = MOVE_NONE;
1887 ss[ply+2].killer1 = ss[ply+2].killer2 = MOVE_NONE;
1888 ss[ply].threatMove = MOVE_NONE;
1889 ss[ply].reduction = Depth(0);
1890 ss[ply].currentMoveCaptureValue = Value(0);
1892 if(Threads[threadID].printCurrentLine)
1893 print_current_line(ss, ply, threadID);
1897 // update_pv() is called whenever a search returns a value > alpha. It
1898 // updates the PV in the SearchStack object corresponding to the current
1901 void update_pv(SearchStack ss[], int ply) {
1902 assert(ply >= 0 && ply < PLY_MAX);
1904 ss[ply].pv[ply] = ss[ply].currentMove;
1906 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1907 ss[ply].pv[p] = ss[ply+1].pv[p];
1908 ss[ply].pv[p] = MOVE_NONE;
1912 // sp_update_pv() is a variant of update_pv for use at split points. The
1913 // difference between the two functions is that sp_update_pv also updates
1914 // the PV at the parent node.
1916 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1917 assert(ply >= 0 && ply < PLY_MAX);
1919 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1921 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1922 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1923 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1927 // connected_moves() tests whether two moves are 'connected' in the sense
1928 // that the first move somehow made the second move possible (for instance
1929 // if the moving piece is the same in both moves). The first move is
1930 // assumed to be the move that was made to reach the current position, while
1931 // the second move is assumed to be a move from the current position.
1933 bool connected_moves(const Position &pos, Move m1, Move m2) {
1934 Square f1, t1, f2, t2;
1936 assert(move_is_ok(m1));
1937 assert(move_is_ok(m2));
1942 // Case 1: The moving piece is the same in both moves.
1948 // Case 2: The destination square for m2 was vacated by m1.
1954 // Case 3: Moving through the vacated square:
1955 if(piece_is_slider(pos.piece_on(f2)) &&
1956 bit_is_set(squares_between(f2, t2), f1))
1959 // Case 4: The destination square for m2 is attacked by the moving piece
1961 if(pos.piece_attacks_square(t1, t2))
1964 // Case 5: Discovered check, checking piece is the piece moved in m1:
1965 if(piece_is_slider(pos.piece_on(t1)) &&
1966 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
1968 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
1970 Bitboard occ = pos.occupied_squares();
1971 Color us = pos.side_to_move();
1972 Square ksq = pos.king_square(us);
1973 clear_bit(&occ, f2);
1974 if(pos.type_of_piece_on(t1) == BISHOP) {
1975 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
1978 else if(pos.type_of_piece_on(t1) == ROOK) {
1979 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
1983 assert(pos.type_of_piece_on(t1) == QUEEN);
1984 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
1993 // extension() decides whether a move should be searched with normal depth,
1994 // or with extended depth. Certain classes of moves (checking moves, in
1995 // particular) are searched with bigger depth than ordinary moves.
1997 Depth extension(const Position &pos, Move m, bool pvNode,
1998 bool check, bool singleReply, bool mateThreat) {
2000 Depth result = Depth(0);
2003 result += CheckExtension[pvNode];
2006 result += SingleReplyExtension[pvNode];
2008 if (pos.move_is_pawn_push_to_7th(m))
2009 result += PawnPushTo7thExtension[pvNode];
2011 if (pos.move_is_passed_pawn_push(m))
2012 result += PassedPawnExtension[pvNode];
2015 result += MateThreatExtension[pvNode];
2017 if ( pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
\r
2018 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
\r
2019 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
\r
2020 && !move_promotion(m))
2021 result += PawnEndgameExtension[pvNode];
2024 && pos.move_is_capture(m)
2025 && pos.type_of_piece_on(move_to(m)) != PAWN
2029 return Min(result, OnePly);
2033 // ok_to_do_nullmove() looks at the current position and decides whether
2034 // doing a 'null move' should be allowed. In order to avoid zugzwang
2035 // problems, null moves are not allowed when the side to move has very
2036 // little material left. Currently, the test is a bit too simple: Null
2037 // moves are avoided only when the side to move has only pawns left. It's
2038 // probably a good idea to avoid null moves in at least some more
2039 // complicated endgames, e.g. KQ vs KR. FIXME
2041 bool ok_to_do_nullmove(const Position &pos) {
2042 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2048 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2049 // non-tactical moves late in the move list close to the leaves are
2050 // candidates for pruning.
2052 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2053 Square mfrom, mto, tfrom, tto;
2055 assert(move_is_ok(m));
2056 assert(threat == MOVE_NONE || move_is_ok(threat));
2057 assert(!move_promotion(m));
2058 assert(!pos.move_is_check(m));
2059 assert(!pos.move_is_capture(m));
2060 assert(!pos.move_is_passed_pawn_push(m));
2061 assert(d >= OnePly);
2063 mfrom = move_from(m);
2065 tfrom = move_from(threat);
2066 tto = move_to(threat);
2068 // Case 1: Castling moves are never pruned.
2069 if(move_is_castle(m))
2072 // Case 2: Don't prune moves which move the threatened piece
2073 if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2076 // Case 3: If the threatened piece has value less than or equal to the
2077 // value of the threatening piece, don't prune move which defend it.
2078 if(!PruneDefendingMoves && threat != MOVE_NONE
2079 && (piece_value_midgame(pos.piece_on(tfrom))
2080 >= piece_value_midgame(pos.piece_on(tto)))
2081 && pos.move_attacks_square(m, tto))
2084 // Case 4: Don't prune moves with good history.
2085 if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2088 // Case 5: If the moving piece in the threatened move is a slider, don't
2089 // prune safe moves which block its ray.
2090 if(!PruneBlockingMoves && threat != MOVE_NONE
2091 && piece_is_slider(pos.piece_on(tfrom))
2092 && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2099 // ok_to_use_TT() returns true if a transposition table score
2100 // can be used at a given point in search.
2102 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2104 Value v = value_from_tt(tte->value(), ply);
2106 return ( tte->depth() >= depth
2107 || v >= Max(value_mate_in(100), beta)
2108 || v < Min(value_mated_in(100), beta))
2110 && ( (is_lower_bound(tte->type()) && v >= beta)
2111 || (is_upper_bound(tte->type()) && v < beta));
2115 // ok_to_history() returns true if a move m can be stored
2116 // in history. Should be a non capturing move.
2118 bool ok_to_history(const Position& pos, Move m) {
2120 return pos.square_is_empty(move_to(m))
2121 && !move_promotion(m)
2126 // update_history() registers a good move that produced a beta-cutoff
2127 // in history and marks as failures all the other moves of that ply.
2129 void update_history(const Position& pos, Move m, Depth depth,
2130 Move movesSearched[], int moveCount) {
2132 H.success(pos.piece_on(move_from(m)), m, depth);
2134 for (int i = 0; i < moveCount - 1; i++)
2135 if (ok_to_history(pos, movesSearched[i]) && m != movesSearched[i])
2136 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2139 // fail_high_ply_1() checks if some thread is currently resolving a fail
2140 // high at ply 1 at the node below the first root node. This information
2141 // is used for time managment.
2143 bool fail_high_ply_1() {
2144 for(int i = 0; i < ActiveThreads; i++)
2145 if(Threads[i].failHighPly1)
2151 // current_search_time() returns the number of milliseconds which have passed
2152 // since the beginning of the current search.
2154 int current_search_time() {
2155 return get_system_time() - SearchStartTime;
2159 // nps() computes the current nodes/second count.
2162 int t = current_search_time();
2163 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2167 // poll() performs two different functions: It polls for user input, and it
2168 // looks at the time consumed so far and decides if it's time to abort the
2173 static int lastInfoTime;
2174 int t = current_search_time();
2179 // We are line oriented, don't read single chars
2180 std::string command;
2181 if (!std::getline(std::cin, command))
2184 if (command == "quit")
2187 PonderSearch = false;
2190 else if(command == "stop")
2193 PonderSearch = false;
2195 else if(command == "ponderhit")
2198 // Print search information
2202 else if (lastInfoTime > t)
2203 // HACK: Must be a new search where we searched less than
2204 // NodesBetweenPolls nodes during the first second of search.
2207 else if (t - lastInfoTime >= 1000)
2214 if (dbg_show_hit_rate)
2215 dbg_print_hit_rate();
2217 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2218 << " time " << t << " hashfull " << TT.full() << std::endl;
2219 lock_release(&IOLock);
2220 if (ShowCurrentLine)
2221 Threads[0].printCurrentLine = true;
2223 // Should we stop the search?
2227 bool overTime = t > AbsoluteMaxSearchTime
2228 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2229 || ( !FailHigh && !fail_high_ply_1() && !Problem
2230 && t > 6*(MaxSearchTime + ExtraSearchTime));
2232 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2233 || (ExactMaxTime && t >= ExactMaxTime)
2234 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2239 // ponderhit() is called when the program is pondering (i.e. thinking while
2240 // it's the opponent's turn to move) in order to let the engine know that
2241 // it correctly predicted the opponent's move.
2244 int t = current_search_time();
2245 PonderSearch = false;
2246 if(Iteration >= 2 &&
2247 (!InfiniteSearch && (StopOnPonderhit ||
2248 t > AbsoluteMaxSearchTime ||
2249 (RootMoveNumber == 1 &&
2250 t > MaxSearchTime + ExtraSearchTime) ||
2251 (!FailHigh && !fail_high_ply_1() && !Problem &&
2252 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2257 // print_current_line() prints the current line of search for a given
2258 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2260 void print_current_line(SearchStack ss[], int ply, int threadID) {
2261 assert(ply >= 0 && ply < PLY_MAX);
2262 assert(threadID >= 0 && threadID < ActiveThreads);
2264 if(!Threads[threadID].idle) {
2266 std::cout << "info currline " << (threadID + 1);
2267 for(int p = 0; p < ply; p++)
2268 std::cout << " " << ss[p].currentMove;
2269 std::cout << std::endl;
2270 lock_release(&IOLock);
2272 Threads[threadID].printCurrentLine = false;
2273 if(threadID + 1 < ActiveThreads)
2274 Threads[threadID + 1].printCurrentLine = true;
2278 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2279 // while the program is pondering. The point is to work around a wrinkle in
2280 // the UCI protocol: When pondering, the engine is not allowed to give a
2281 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2282 // We simply wait here until one of these commands is sent, and return,
2283 // after which the bestmove and pondermove will be printed (in id_loop()).
2285 void wait_for_stop_or_ponderhit() {
2286 std::string command;
2289 if(!std::getline(std::cin, command))
2292 if(command == "quit") {
2293 OpeningBook.close();
2298 else if(command == "ponderhit" || command == "stop")
2304 // idle_loop() is where the threads are parked when they have no work to do.
2305 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2306 // object for which the current thread is the master.
2308 void idle_loop(int threadID, SplitPoint *waitSp) {
2309 assert(threadID >= 0 && threadID < THREAD_MAX);
2311 Threads[threadID].running = true;
2314 if(AllThreadsShouldExit && threadID != 0)
2317 // If we are not thinking, wait for a condition to be signaled instead
2318 // of wasting CPU time polling for work:
2319 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2320 #if !defined(_MSC_VER)
2321 pthread_mutex_lock(&WaitLock);
2322 if(Idle || threadID >= ActiveThreads)
2323 pthread_cond_wait(&WaitCond, &WaitLock);
2324 pthread_mutex_unlock(&WaitLock);
2326 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2330 // If this thread has been assigned work, launch a search:
2331 if(Threads[threadID].workIsWaiting) {
2332 Threads[threadID].workIsWaiting = false;
2333 if(Threads[threadID].splitPoint->pvNode)
2334 sp_search_pv(Threads[threadID].splitPoint, threadID);
2336 sp_search(Threads[threadID].splitPoint, threadID);
2337 Threads[threadID].idle = true;
2340 // If this thread is the master of a split point and all threads have
2341 // finished their work at this split point, return from the idle loop:
2342 if(waitSp != NULL && waitSp->cpus == 0)
2346 Threads[threadID].running = false;
2350 // init_split_point_stack() is called during program initialization, and
2351 // initializes all split point objects.
2353 void init_split_point_stack() {
2354 for(int i = 0; i < THREAD_MAX; i++)
2355 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2356 SplitPointStack[i][j].parent = NULL;
2357 lock_init(&(SplitPointStack[i][j].lock), NULL);
2362 // destroy_split_point_stack() is called when the program exits, and
2363 // destroys all locks in the precomputed split point objects.
2365 void destroy_split_point_stack() {
2366 for(int i = 0; i < THREAD_MAX; i++)
2367 for(int j = 0; j < MaxActiveSplitPoints; j++)
2368 lock_destroy(&(SplitPointStack[i][j].lock));
2372 // thread_should_stop() checks whether the thread with a given threadID has
2373 // been asked to stop, directly or indirectly. This can happen if a beta
2374 // cutoff has occured in thre thread's currently active split point, or in
2375 // some ancestor of the current split point.
2377 bool thread_should_stop(int threadID) {
2378 assert(threadID >= 0 && threadID < ActiveThreads);
2382 if(Threads[threadID].stop)
2384 if(ActiveThreads <= 2)
2386 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2388 Threads[threadID].stop = true;
2395 // thread_is_available() checks whether the thread with threadID "slave" is
2396 // available to help the thread with threadID "master" at a split point. An
2397 // obvious requirement is that "slave" must be idle. With more than two
2398 // threads, this is not by itself sufficient: If "slave" is the master of
2399 // some active split point, it is only available as a slave to the other
2400 // threads which are busy searching the split point at the top of "slave"'s
2401 // split point stack (the "helpful master concept" in YBWC terminology).
2403 bool thread_is_available(int slave, int master) {
2404 assert(slave >= 0 && slave < ActiveThreads);
2405 assert(master >= 0 && master < ActiveThreads);
2406 assert(ActiveThreads > 1);
2408 if(!Threads[slave].idle || slave == master)
2411 if(Threads[slave].activeSplitPoints == 0)
2412 // No active split points means that the thread is available as a slave
2413 // for any other thread.
2416 if(ActiveThreads == 2)
2419 // Apply the "helpful master" concept if possible.
2420 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2427 // idle_thread_exists() tries to find an idle thread which is available as
2428 // a slave for the thread with threadID "master".
2430 bool idle_thread_exists(int master) {
2431 assert(master >= 0 && master < ActiveThreads);
2432 assert(ActiveThreads > 1);
2434 for(int i = 0; i < ActiveThreads; i++)
2435 if(thread_is_available(i, master))
2441 // split() does the actual work of distributing the work at a node between
2442 // several threads at PV nodes. If it does not succeed in splitting the
2443 // node (because no idle threads are available, or because we have no unused
2444 // split point objects), the function immediately returns false. If
2445 // splitting is possible, a SplitPoint object is initialized with all the
2446 // data that must be copied to the helper threads (the current position and
2447 // search stack, alpha, beta, the search depth, etc.), and we tell our
2448 // helper threads that they have been assigned work. This will cause them
2449 // to instantly leave their idle loops and call sp_search_pv(). When all
2450 // threads have returned from sp_search_pv (or, equivalently, when
2451 // splitPoint->cpus becomes 0), split() returns true.
2453 bool split(const Position &p, SearchStack *sstck, int ply,
2454 Value *alpha, Value *beta, Value *bestValue,
2455 Depth depth, int *moves,
2456 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2458 assert(sstck != NULL);
2459 assert(ply >= 0 && ply < PLY_MAX);
2460 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2461 assert(!pvNode || *alpha < *beta);
2462 assert(*beta <= VALUE_INFINITE);
2463 assert(depth > Depth(0));
2464 assert(master >= 0 && master < ActiveThreads);
2465 assert(ActiveThreads > 1);
2467 SplitPoint *splitPoint;
2472 // If no other thread is available to help us, or if we have too many
2473 // active split points, don't split:
2474 if(!idle_thread_exists(master) ||
2475 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2476 lock_release(&MPLock);
2480 // Pick the next available split point object from the split point stack:
2481 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2482 Threads[master].activeSplitPoints++;
2484 // Initialize the split point object:
2485 splitPoint->parent = Threads[master].splitPoint;
2486 splitPoint->finished = false;
2487 splitPoint->ply = ply;
2488 splitPoint->depth = depth;
2489 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2490 splitPoint->beta = *beta;
2491 splitPoint->pvNode = pvNode;
2492 splitPoint->dcCandidates = dcCandidates;
2493 splitPoint->bestValue = *bestValue;
2494 splitPoint->master = master;
2495 splitPoint->mp = mp;
2496 splitPoint->moves = *moves;
2497 splitPoint->cpus = 1;
2498 splitPoint->pos.copy(p);
2499 splitPoint->parentSstack = sstck;
2500 for(i = 0; i < ActiveThreads; i++)
2501 splitPoint->slaves[i] = 0;
2503 // Copy the current position and the search stack to the master thread:
2504 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2505 Threads[master].splitPoint = splitPoint;
2507 // Make copies of the current position and search stack for each thread:
2508 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2510 if(thread_is_available(i, master)) {
2511 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2512 Threads[i].splitPoint = splitPoint;
2513 splitPoint->slaves[i] = 1;
2517 // Tell the threads that they have work to do. This will make them leave
2519 for(i = 0; i < ActiveThreads; i++)
2520 if(i == master || splitPoint->slaves[i]) {
2521 Threads[i].workIsWaiting = true;
2522 Threads[i].idle = false;
2523 Threads[i].stop = false;
2526 lock_release(&MPLock);
2528 // Everything is set up. The master thread enters the idle loop, from
2529 // which it will instantly launch a search, because its workIsWaiting
2530 // slot is 'true'. We send the split point as a second parameter to the
2531 // idle loop, which means that the main thread will return from the idle
2532 // loop when all threads have finished their work at this split point
2533 // (i.e. when // splitPoint->cpus == 0).
2534 idle_loop(master, splitPoint);
2536 // We have returned from the idle loop, which means that all threads are
2537 // finished. Update alpha, beta and bestvalue, and return:
2539 if(pvNode) *alpha = splitPoint->alpha;
2540 *beta = splitPoint->beta;
2541 *bestValue = splitPoint->bestValue;
2542 Threads[master].stop = false;
2543 Threads[master].idle = false;
2544 Threads[master].activeSplitPoints--;
2545 Threads[master].splitPoint = splitPoint->parent;
2546 lock_release(&MPLock);
2552 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2553 // to start a new search from the root.
2555 void wake_sleeping_threads() {
2556 if(ActiveThreads > 1) {
2557 for(int i = 1; i < ActiveThreads; i++) {
2558 Threads[i].idle = true;
2559 Threads[i].workIsWaiting = false;
2561 #if !defined(_MSC_VER)
2562 pthread_mutex_lock(&WaitLock);
2563 pthread_cond_broadcast(&WaitCond);
2564 pthread_mutex_unlock(&WaitLock);
2566 for(int i = 1; i < THREAD_MAX; i++)
2567 SetEvent(SitIdleEvent[i]);
2573 // init_thread() is the function which is called when a new thread is
2574 // launched. It simply calls the idle_loop() function with the supplied
2575 // threadID. There are two versions of this function; one for POSIX threads
2576 // and one for Windows threads.
2578 #if !defined(_MSC_VER)
2580 void *init_thread(void *threadID) {
2581 idle_loop(*(int *)threadID, NULL);
2587 DWORD WINAPI init_thread(LPVOID threadID) {
2588 idle_loop(*(int *)threadID, NULL);