2 Glaurung, a UCI chess playing engine.
3 Copyright (C) 2004-2008 Tord Romstad
5 Glaurung is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 Glaurung is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 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 Move get_move(int moveNum) const;
74 Value get_move_score(int moveNum) const;
75 void set_move_score(int moveNum, Value score);
76 void set_move_nodes(int moveNum, int64_t nodes);
77 void set_move_pv(int moveNum, const Move pv[]);
78 Move get_move_pv(int moveNum, int i) const;
79 int64_t get_move_cumulative_nodes(int moveNum) const;
80 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 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
157 Depth CheckExtension[2] = {OnePly, OnePly};
158 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
159 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
160 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
161 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
162 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
164 // Search depth at iteration 1:
165 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
169 int NodesBetweenPolls = 30000;
171 // Iteration counter:
174 // Scores and number of times the best move changed for each iteration:
175 Value ValueByIteration[PLY_MAX_PLUS_2];
176 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
181 // Time managment variables
183 int MaxNodes, MaxDepth;
184 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
185 Move BestRootMove, PonderMove, EasyMove;
189 bool StopOnPonderhit;
194 bool PonderingEnabled;
197 // Show current line?
198 bool ShowCurrentLine = false;
201 bool UseLogFile = false;
202 std::ofstream LogFile;
204 // MP related variables
205 Depth MinimumSplitDepth = 4*OnePly;
206 int MaxThreadsPerSplitPoint = 4;
207 Thread Threads[THREAD_MAX];
209 bool AllThreadsShouldExit = false;
210 const int MaxActiveSplitPoints = 8;
211 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
214 #if !defined(_MSC_VER)
215 pthread_cond_t WaitCond;
216 pthread_mutex_t WaitLock;
218 HANDLE SitIdleEvent[THREAD_MAX];
224 void id_loop(const Position &pos, Move searchMoves[]);
225 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
226 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
227 Depth depth, int ply, int threadID);
228 Value search(Position &pos, SearchStack ss[], Value beta,
229 Depth depth, int ply, bool allowNullmove, int threadID);
230 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
231 Depth depth, int ply, int threadID);
232 void sp_search(SplitPoint *sp, int threadID);
233 void sp_search_pv(SplitPoint *sp, int threadID);
234 void init_search_stack(SearchStack ss[]);
235 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
236 void update_pv(SearchStack ss[], int ply);
237 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
238 bool connected_moves(const Position &pos, Move m1, Move m2);
239 Depth extension(const Position &pos, Move m, bool pvNode, bool check,
240 bool singleReply, bool mateThreat);
241 bool ok_to_do_nullmove(const Position &pos);
242 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
243 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
244 bool ok_to_history(const Position &pos, Move m);
245 void update_history(const Position& pos, Move m, Depth depth,
246 Move movesSearched[], int moveCount);
248 bool fail_high_ply_1();
249 int current_search_time();
253 void print_current_line(SearchStack ss[], int ply, int threadID);
254 void wait_for_stop_or_ponderhit();
256 void idle_loop(int threadID, SplitPoint *waitSp);
257 void init_split_point_stack();
258 void destroy_split_point_stack();
259 bool thread_should_stop(int threadID);
260 bool thread_is_available(int slave, int master);
261 bool idle_thread_exists(int master);
262 bool split(const Position &pos, SearchStack *ss, int ply,
263 Value *alpha, Value *beta, Value *bestValue, Depth depth,
264 int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
266 void wake_sleeping_threads();
268 #if !defined(_MSC_VER)
269 void *init_thread(void *threadID);
271 DWORD WINAPI init_thread(LPVOID threadID);
278 //// Global variables
281 // The main transposition table
282 TranspositionTable TT = TranspositionTable(TTDefaultSize);
285 // Number of active threads:
286 int ActiveThreads = 1;
288 // Locks. In principle, there is no need for IOLock to be a global variable,
289 // but it could turn out to be useful for debugging.
292 History H; // Should be made local?
299 /// think() is the external interface to Glaurung's search, and is called when
300 /// the program receives the UCI 'go' command. It initializes various
301 /// search-related global variables, and calls root_search()
303 void think(const Position &pos, bool infinite, bool ponder, int time,
304 int increment, int movesToGo, int maxDepth, int maxNodes,
305 int maxTime, Move searchMoves[]) {
307 // Look for a book move:
308 if(!infinite && !ponder && get_option_value_bool("OwnBook")) {
310 if(get_option_value_string("Book File") != OpeningBook.file_name()) {
312 OpeningBook.open("book.bin");
314 bookMove = OpeningBook.get_move(pos);
315 if(bookMove != MOVE_NONE) {
316 std::cout << "bestmove " << bookMove << std::endl;
321 // Initialize global search variables:
323 SearchStartTime = get_system_time();
324 BestRootMove = MOVE_NONE;
325 PonderMove = MOVE_NONE;
326 EasyMove = MOVE_NONE;
327 for(int i = 0; i < THREAD_MAX; i++) {
328 Threads[i].nodes = 0ULL;
329 Threads[i].failHighPly1 = false;
332 InfiniteSearch = infinite;
333 PonderSearch = ponder;
334 StopOnPonderhit = false;
339 ExactMaxTime = maxTime;
341 // Read UCI option values:
342 TT.set_size(get_option_value_int("Hash"));
343 if(button_was_pressed("Clear Hash"))
345 PonderingEnabled = get_option_value_int("Ponder");
346 MultiPV = get_option_value_int("MultiPV");
348 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
350 Depth(get_option_value_int("Check Extension (non-PV nodes)"));
351 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
352 SingleReplyExtension[0] =
353 Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
354 PawnPushTo7thExtension[1] =
355 Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
356 PawnPushTo7thExtension[0] =
357 Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
358 PassedPawnExtension[1] =
359 Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
360 PassedPawnExtension[0] =
361 Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
362 PawnEndgameExtension[1] =
363 Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
364 PawnEndgameExtension[0] =
365 Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
366 MateThreatExtension[1] =
367 Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
368 MateThreatExtension[0] =
369 Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
371 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
372 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
373 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
374 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
376 Chess960 = get_option_value_bool("UCI_Chess960");
377 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
378 UseLogFile = get_option_value_bool("Use Search Log");
380 LogFile.open(get_option_value_string("Search Log Filename").c_str(),
381 std::ios::out | std::ios::app);
383 UseQSearchFutilityPruning =
384 get_option_value_bool("Futility Pruning (Quiescence Search)");
386 get_option_value_bool("Futility Pruning (Main Search)");
389 value_from_centipawns(get_option_value_int("Futility Margin 0"));
391 value_from_centipawns(get_option_value_int("Futility Margin 1"));
393 value_from_centipawns(get_option_value_int("Futility Margin 2"));
395 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
396 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
398 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
399 MaxThreadsPerSplitPoint =
400 get_option_value_int("Maximum Number of Threads per Split Point");
402 read_weights(pos.side_to_move());
404 int newActiveThreads = get_option_value_int("Threads");
405 if(newActiveThreads != ActiveThreads) {
406 ActiveThreads = newActiveThreads;
407 init_eval(ActiveThreads);
410 // Write information to search log file:
412 LogFile << "Searching: " << pos.to_fen() << '\n';
413 LogFile << "infinite: " << infinite << " ponder: " << ponder
414 << " time: " << time << " increment: " << increment
415 << " moves to go: " << movesToGo << '\n';
418 // Wake up sleeping threads:
419 wake_sleeping_threads();
421 for(int i = 1; i < ActiveThreads; i++)
422 assert(thread_is_available(i, 0));
424 // Set thinking time:
425 if(!movesToGo) { // Sudden death time control
427 MaxSearchTime = time / 30 + increment;
428 AbsoluteMaxSearchTime = Max(time / 4, increment - 100);
430 else { // Blitz game without increment
431 MaxSearchTime = time / 40;
432 AbsoluteMaxSearchTime = time / 8;
435 else { // (x moves) / (y minutes)
437 MaxSearchTime = time / 2;
438 AbsoluteMaxSearchTime = Min(time / 2, time - 500);
441 MaxSearchTime = time / Min(movesToGo, 20);
442 AbsoluteMaxSearchTime = Min((4 * time) / movesToGo, time / 3);
445 if(PonderingEnabled) {
446 MaxSearchTime += MaxSearchTime / 4;
447 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
450 // Fixed depth or fixed number of nodes?
453 InfiniteSearch = true; // HACK
457 NodesBetweenPolls = Min(MaxNodes, 30000);
458 InfiniteSearch = true; // HACK
461 NodesBetweenPolls = 30000;
463 // We're ready to start thinking. Call the iterative deepening loop
465 id_loop(pos, searchMoves);
481 /// init_threads() is called during startup. It launches all helper threads,
482 /// and initializes the split point stack and the global locks and condition
485 void init_threads() {
487 #if !defined(_MSC_VER)
488 pthread_t pthread[1];
491 for(i = 0; i < THREAD_MAX; i++)
492 Threads[i].activeSplitPoints = 0;
494 // Initialize global locks:
495 lock_init(&MPLock, NULL);
496 lock_init(&IOLock, NULL);
498 init_split_point_stack();
500 #if !defined(_MSC_VER)
501 pthread_mutex_init(&WaitLock, NULL);
502 pthread_cond_init(&WaitCond, NULL);
504 for(i = 0; i < THREAD_MAX; i++)
505 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
508 // All threads except the main thread should be initialized to idle state:
509 for(i = 1; i < THREAD_MAX; i++) {
510 Threads[i].stop = false;
511 Threads[i].workIsWaiting = false;
512 Threads[i].idle = true;
513 Threads[i].running = false;
516 // Launch the helper threads:
517 for(i = 1; i < THREAD_MAX; i++) {
518 #if !defined(_MSC_VER)
519 pthread_create(pthread, NULL, init_thread, (void*)(&i));
523 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
527 // Wait until the thread has finished launching:
528 while(!Threads[i].running);
533 /// stop_threads() is called when the program exits. It makes all the
534 /// helper threads exit cleanly.
536 void stop_threads() {
537 ActiveThreads = THREAD_MAX; // HACK
538 Idle = false; // HACK
539 wake_sleeping_threads();
540 AllThreadsShouldExit = true;
541 for(int i = 1; i < THREAD_MAX; i++) {
542 Threads[i].stop = true;
543 while(Threads[i].running);
545 destroy_split_point_stack();
549 /// nodes_searched() returns the total number of nodes searched so far in
550 /// the current search.
552 int64_t nodes_searched() {
553 int64_t result = 0ULL;
554 for(int i = 0; i < ActiveThreads; i++)
555 result += Threads[i].nodes;
562 // id_loop() is the main iterative deepening loop. It calls root_search
563 // repeatedly with increasing depth until the allocated thinking time has
564 // been consumed, the user stops the search, or the maximum search depth is
567 void id_loop(const Position &pos, Move searchMoves[]) {
569 SearchStack ss[PLY_MAX_PLUS_2];
571 // searchMoves are verified, copied, scored and sorted
572 RootMoveList rml(p, searchMoves);
577 init_search_stack(ss);
579 ValueByIteration[0] = Value(0);
580 ValueByIteration[1] = rml.get_move_score(0);
583 EasyMove = rml.scan_for_easy_move();
585 // Iterative deepening loop
586 while(!AbortSearch && Iteration < PLY_MAX) {
588 // Initialize iteration
591 BestMoveChangesByIteration[Iteration] = 0;
595 std::cout << "info depth " << Iteration << std::endl;
597 // Search to the current depth
598 ValueByIteration[Iteration] = root_search(p, ss, rml);
600 // Erase the easy move if it differs from the new best move
601 if(ss[0].pv[0] != EasyMove)
602 EasyMove = MOVE_NONE;
606 if(!InfiniteSearch) {
608 bool stopSearch = false;
610 // Stop search early if there is only a single legal move:
611 if(Iteration >= 6 && rml.move_count() == 1)
614 // Stop search early when the last two iterations returned a mate
617 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
618 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
621 // Stop search early if one move seems to be much better than the
623 int64_t nodes = nodes_searched();
624 if(Iteration >= 8 && EasyMove == ss[0].pv[0] &&
625 ((rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100 &&
626 current_search_time() > MaxSearchTime / 16) ||
627 (rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100 &&
628 current_search_time() > MaxSearchTime / 32)))
631 // Add some extra time if the best move has changed during the last
633 if(Iteration > 5 && Iteration <= 50)
635 BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2) +
636 BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
638 // Stop search if most of MaxSearchTime is consumed at the end of the
639 // iteration. We probably don't have enough time to search the first
640 // move at the next iteration anyway.
641 if(current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
648 StopOnPonderhit = true;
652 // Write PV to transposition table, in case the relevant entries have
653 // been overwritten during the search:
654 TT.insert_pv(p, ss[0].pv);
656 if(MaxDepth && Iteration >= MaxDepth)
662 // If we are pondering, we shouldn't print the best move before we
665 wait_for_stop_or_ponderhit();
667 // Print final search statistics
668 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
669 << " time " << current_search_time()
670 << " hashfull " << TT.full() << std::endl;
672 // Print the best move and the ponder move to the standard output:
673 std::cout << "bestmove " << ss[0].pv[0];
674 if(ss[0].pv[1] != MOVE_NONE)
675 std::cout << " ponder " << ss[0].pv[1];
676 std::cout << std::endl;
680 LogFile << "Nodes: " << nodes_searched() << '\n';
681 LogFile << "Nodes/second: " << nps() << '\n';
682 LogFile << "Best move: " << move_to_san(p, ss[0].pv[0]) << '\n';
683 p.do_move(ss[0].pv[0], u);
684 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1]) << '\n';
685 LogFile << std::endl;
690 // root_search() is the function which searches the root node. It is
691 // similar to search_pv except that it uses a different move ordering
692 // scheme (perhaps we should try to use this at internal PV nodes, too?)
693 // and prints some information to the standard output.
695 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
696 Value alpha = -VALUE_INFINITE, beta = VALUE_INFINITE, value;
697 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
699 // Loop through all the moves in the root move list:
700 for(int i = 0; i < rml.move_count() && !AbortSearch; i++) {
706 RootMoveNumber = i + 1;
709 // Remember the node count before the move is searched. The node counts
710 // are used to sort the root moves at the next iteration.
711 nodes = nodes_searched();
713 // Pick the next root move, and print the move and the move number to
714 // the standard output:
715 move = ss[0].currentMove = rml.get_move(i);
716 if(current_search_time() >= 1000)
717 std::cout << "info currmove " << move
718 << " currmovenumber " << i + 1 << std::endl;
720 // Decide search depth for this move:
721 ext = extension(pos, move, true, pos.move_is_check(move), false, false);
722 newDepth = (Iteration-2)*OnePly + ext + InitialDepth;
724 // Make the move, and search it.
725 pos.do_move(move, u, dcCandidates);
728 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
729 // If the value has dropped a lot compared to the last iteration,
730 // set the boolean variable Problem to true. This variable is used
731 // for time managment: When Problem is true, we try to complete the
732 // current iteration before playing a move.
733 Problem = (Iteration >= 2 &&
734 value <= ValueByIteration[Iteration-1] - ProblemMargin);
735 if(Problem && StopOnPonderhit)
736 StopOnPonderhit = false;
739 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
741 // Fail high! Set the boolean variable FailHigh to true, and
742 // re-search the move with a big window. The variable FailHigh is
743 // used for time managment: We try to avoid aborting the search
744 // prematurely during a fail high research.
746 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
750 pos.undo_move(move, u);
752 // Finished searching the move. If AbortSearch is true, the search
753 // was aborted because the user interrupted the search or because we
754 // ran out of time. In this case, the return value of the search cannot
755 // be trusted, and we break out of the loop without updating the best
760 // Remember the node count for this move. The node counts are used to
761 // sort the root moves at the next iteration.
762 rml.set_move_nodes(i, nodes_searched() - nodes);
764 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
766 if(value <= alpha && i >= MultiPV)
767 rml.set_move_score(i, -VALUE_INFINITE);
772 rml.set_move_score(i, value);
774 rml.set_move_pv(i, ss[0].pv);
777 // We record how often the best move has been changed in each
778 // iteration. This information is used for time managment: When
779 // the best move changes frequently, we allocate some more time.
781 BestMoveChangesByIteration[Iteration]++;
783 // Print search information to the standard output:
784 std::cout << "info depth " << Iteration
785 << " score " << value_to_string(value)
786 << " time " << current_search_time()
787 << " nodes " << nodes_searched()
790 for(int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
791 std::cout << ss[0].pv[j] << " ";
792 std::cout << std::endl;
795 LogFile << pretty_pv(pos, current_search_time(), Iteration,
796 nodes_searched(), value, ss[0].pv)
801 // Reset the global variable Problem to false if the value isn't too
802 // far below the final value from the last iteration.
803 if(value > ValueByIteration[Iteration - 1] - NoProblemMargin)
806 else { // MultiPV > 1
808 for(int j = 0; j < Min(MultiPV, rml.move_count()); j++) {
810 std::cout << "info multipv " << j + 1
811 << " score " << value_to_string(rml.get_move_score(j))
812 << " depth " << ((j <= i)? Iteration : Iteration - 1)
813 << " time " << current_search_time()
814 << " nodes " << nodes_searched()
817 for(k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
818 std::cout << rml.get_move_pv(j, k) << " ";
819 std::cout << std::endl;
821 alpha = rml.get_move_score(Min(i, MultiPV-1));
829 // search_pv() is the main search function for PV nodes.
831 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
832 Depth depth, int ply, int threadID) {
834 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
835 assert(beta > alpha && beta <= VALUE_INFINITE);
836 assert(ply >= 0 && ply < PLY_MAX);
837 assert(threadID >= 0 && threadID < ActiveThreads);
841 // Initialize, and make an early exit in case of an aborted search,
842 // an instant draw, maximum ply reached, etc.
843 Value oldAlpha = alpha;
845 if (AbortSearch || thread_should_stop(threadID))
849 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
851 init_node(pos, ss, ply, threadID);
856 if (ply >= PLY_MAX - 1)
857 return evaluate(pos, ei, threadID);
859 // Mate distance pruning
860 alpha = Max(value_mated_in(ply), alpha);
861 beta = Min(value_mate_in(ply+1), beta);
865 // Transposition table lookup. At PV nodes, we don't use the TT for
866 // pruning, but only for move ordering.
867 const TTEntry* tte = TT.retrieve(pos);
869 Move ttMove = (tte ? tte->move() : MOVE_NONE);
871 // Go with internal iterative deepening if we don't have a TT move
872 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
874 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
875 ttMove = ss[ply].pv[ply];
878 // Initialize a MovePicker object for the current position, and prepare
879 // to search all moves:
880 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply].mateKiller,
881 ss[ply].killer1, ss[ply].killer2, depth);
883 Move move, movesSearched[256];
885 Value value, bestValue = -VALUE_INFINITE;
886 Bitboard dcCandidates = mp.discovered_check_candidates();
887 bool mateThreat = MateThreatExtension[1] > Depth(0)
888 && pos.has_mate_threat(opposite_color(pos.side_to_move()));
890 // Loop through all legal moves until no moves remain or a beta cutoff
893 && (move = mp.get_next_move()) != MOVE_NONE
894 && !thread_should_stop(threadID))
896 assert(move_is_ok(move));
898 bool singleReply = (pos.is_check() && mp.number_of_moves() == 1);
899 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
900 bool moveIsCapture = pos.move_is_capture(move);
901 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
903 movesSearched[moveCount++] = ss[ply].currentMove = move;
905 ss[ply].currentMoveCaptureValue = move_is_ep(move) ?
906 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
908 // Decide the new search depth
909 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat);
910 Depth newDepth = depth - OnePly + ext;
912 // Make and search the move
914 pos.do_move(move, u, dcCandidates);
916 if (moveCount == 1) // The first move in list is the PV
917 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
920 // Try to reduce non-pv search depth by one ply if move seems not problematic,
921 // if the move fails high will be re-searched at full depth.
922 if ( depth >= 2*OnePly
924 && moveCount >= LMRPVMoves
926 && !move_promotion(move)
927 && !moveIsPassedPawnPush
928 && !move_is_castle(move)
929 && move != ss[ply].killer1
930 && move != ss[ply].killer2)
932 ss[ply].reduction = OnePly;
933 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
936 value = alpha + 1; // Just to trigger next condition
938 if (value > alpha) // Go with full depth non-pv search
940 ss[ply].reduction = Depth(0);
941 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
942 if (value > alpha && value < beta)
944 // When the search fails high at ply 1 while searching the first
945 // move at the root, set the flag failHighPly1. This is used for
946 // time managment: We don't want to stop the search early in
947 // such cases, because resolving the fail high at ply 1 could
948 // result in a big drop in score at the root.
949 if (ply == 1 && RootMoveNumber == 1)
950 Threads[threadID].failHighPly1 = true;
952 // A fail high occurred. Re-search at full window (pv search)
953 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
954 Threads[threadID].failHighPly1 = false;
958 pos.undo_move(move, u);
960 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
963 if (value > bestValue)
970 if (value == value_mate_in(ply + 1))
971 ss[ply].mateKiller = move;
973 // If we are at ply 1, and we are searching the first root move at
974 // ply 0, set the 'Problem' variable if the score has dropped a lot
975 // (from the computer's point of view) since the previous iteration:
976 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
981 if ( ActiveThreads > 1
983 && depth >= MinimumSplitDepth
985 && idle_thread_exists(threadID)
987 && !thread_should_stop(threadID)
988 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
989 &moveCount, &mp, dcCandidates, threadID, true))
993 // All legal moves have been searched. A special case: If there were
994 // no legal moves, it must be mate or stalemate:
996 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
998 // If the search is not aborted, update the transposition table,
999 // history counters, and killer moves.
1000 if (AbortSearch || thread_should_stop(threadID))
1003 if (bestValue <= oldAlpha)
1004 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1006 else if (bestValue >= beta)
1008 Move m = ss[ply].pv[ply];
1009 if (ok_to_history(pos, m)) // Only non capture moves are considered
1011 update_history(pos, m, depth, movesSearched, moveCount);
1012 if (m != ss[ply].killer1)
1014 ss[ply].killer2 = ss[ply].killer1;
1015 ss[ply].killer1 = m;
1018 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1021 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1027 // search() is the search function for zero-width nodes.
1029 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1030 int ply, bool allowNullmove, int threadID) {
1032 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1033 assert(ply >= 0 && ply < PLY_MAX);
1034 assert(threadID >= 0 && threadID < ActiveThreads);
1038 // Initialize, and make an early exit in case of an aborted search,
1039 // an instant draw, maximum ply reached, etc.
1040 if (AbortSearch || thread_should_stop(threadID))
1044 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1046 init_node(pos, ss, ply, threadID);
1051 if (ply >= PLY_MAX - 1)
1052 return evaluate(pos, ei, threadID);
1054 // Mate distance pruning
1055 if (value_mated_in(ply) >= beta)
1058 if (value_mate_in(ply + 1) < beta)
1061 // Transposition table lookup
1062 const TTEntry* tte = TT.retrieve(pos);
1064 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1066 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1068 ss[ply].currentMove = ttMove; // can be MOVE_NONE ?
1069 return value_from_tt(tte->value(), ply);
1072 Value approximateEval = quick_evaluate(pos);
1073 bool mateThreat = false;
1078 && ok_to_do_nullmove(pos)
1079 && approximateEval >= beta - NullMoveMargin)
1081 ss[ply].currentMove = MOVE_NULL;
1084 pos.do_null_move(u);
1085 Value nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false, threadID);
1086 pos.undo_null_move(u);
1088 if (nullValue >= beta)
1090 if (depth < 6 * OnePly)
1093 // Do zugzwang verification search
1094 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1098 // The null move failed low, which means that we may be faced with
1099 // some kind of threat. If the previous move was reduced, check if
1100 // the move that refuted the null move was somehow connected to the
1101 // move which was reduced. If a connection is found, return a fail
1102 // low score (which will cause the reduced move to fail high in the
1103 // parent node, which will trigger a re-search with full depth).
1104 if (nullValue == value_mated_in(ply + 2))
1107 ss[ply].threatMove = ss[ply + 1].currentMove;
1108 if ( depth < ThreatDepth
1109 && ss[ply - 1].reduction
1110 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1114 // Null move search not allowed, try razoring
1115 else if ( depth < RazorDepth
1116 && approximateEval < beta - RazorMargin
1117 && evaluate(pos, ei, threadID) < beta - RazorMargin)
1119 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1124 // Go with internal iterative deepening if we don't have a TT move
1125 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1126 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1128 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1129 ttMove = ss[ply].pv[ply];
1132 // Initialize a MovePicker object for the current position, and prepare
1133 // to search all moves:
1134 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply].mateKiller,
1135 ss[ply].killer1, ss[ply].killer2, depth);
1137 Move move, movesSearched[256];
1139 Value value, bestValue = -VALUE_INFINITE;
1140 Bitboard dcCandidates = mp.discovered_check_candidates();
1141 Value futilityValue = VALUE_NONE;
1142 bool isCheck = pos.is_check();
1143 bool useFutilityPruning = UseFutilityPruning
1144 && depth < SelectiveDepth
1147 // Loop through all legal moves until no moves remain or a beta cutoff
1149 while ( bestValue < beta
1150 && (move = mp.get_next_move()) != MOVE_NONE
1151 && !thread_should_stop(threadID))
1153 assert(move_is_ok(move));
1155 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1156 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1157 bool moveIsCapture = pos.move_is_capture(move);
1158 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1160 movesSearched[moveCount++] = ss[ply].currentMove = move;
1162 // Decide the new search depth
1163 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat);
1164 Depth newDepth = depth - OnePly + ext;
1167 if ( useFutilityPruning
1170 && !moveIsPassedPawnPush
1171 && !move_promotion(move))
1173 if ( moveCount >= 2 + int(depth)
1174 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1177 if (depth < 3 * OnePly && approximateEval < beta)
1179 if (futilityValue == VALUE_NONE)
1180 futilityValue = evaluate(pos, ei, threadID)
1181 + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2);
1183 if (futilityValue < beta)
1185 if (futilityValue > bestValue)
1186 bestValue = futilityValue;
1192 // Make and search the move
1194 pos.do_move(move, u, dcCandidates);
1196 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1197 // if the move fails high will be re-searched at full depth.
1198 if ( depth >= 2*OnePly
1200 && moveCount >= LMRNonPVMoves
1202 && !move_promotion(move)
1203 && !moveIsPassedPawnPush
1204 && !move_is_castle(move)
1205 && move != ss[ply].killer1
1206 && move != ss[ply].killer2)
1208 ss[ply].reduction = OnePly;
1209 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1212 value = beta; // Just to trigger next condition
1214 if (value >= beta) // Go with full depth non-pv search
1216 ss[ply].reduction = Depth(0);
1217 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1219 pos.undo_move(move, u);
1221 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1224 if (value > bestValue)
1230 if (value == value_mate_in(ply + 1))
1231 ss[ply].mateKiller = move;
1235 if ( ActiveThreads > 1
1237 && depth >= MinimumSplitDepth
1239 && idle_thread_exists(threadID)
1241 && !thread_should_stop(threadID)
1242 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1243 &mp, dcCandidates, threadID, false))
1247 // All legal moves have been searched. A special case: If there were
1248 // no legal moves, it must be mate or stalemate:
1250 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1252 // If the search is not aborted, update the transposition table,
1253 // history counters, and killer moves.
1254 if (AbortSearch || thread_should_stop(threadID))
1257 if (bestValue < beta)
1258 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1261 Move m = ss[ply].pv[ply];
1262 if (ok_to_history(pos, m)) // Only non capture moves are considered
1264 update_history(pos, m, depth, movesSearched, moveCount);
1265 if (m != ss[ply].killer1)
1267 ss[ply].killer2 = ss[ply].killer1;
1268 ss[ply].killer1 = m;
1271 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1277 // qsearch() is the quiescence search function, which is called by the main
1278 // search function when the remaining depth is zero (or, to be more precise,
1279 // less than OnePly).
1281 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1282 Depth depth, int ply, int threadID) {
1284 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1285 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1287 assert(ply >= 0 && ply < PLY_MAX);
1288 assert(threadID >= 0 && threadID < ActiveThreads);
1292 // Initialize, and make an early exit in case of an aborted search,
1293 // an instant draw, maximum ply reached, etc.
1294 if (AbortSearch || thread_should_stop(threadID))
1297 init_node(pos, ss, ply, threadID);
1302 // Transposition table lookup
1303 const TTEntry* tte = TT.retrieve(pos);
1304 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1305 return value_from_tt(tte->value(), ply);
1307 // Evaluate the position statically:
1308 Value staticValue = evaluate(pos, ei, threadID);
1310 if (ply == PLY_MAX - 1)
1313 // Initialize "stand pat score", and return it immediately if it is
1315 Value bestValue = (pos.is_check() ? -VALUE_INFINITE : staticValue);
1317 if (bestValue >= beta)
1320 if (bestValue > alpha)
1323 // Initialize a MovePicker object for the current position, and prepare
1324 // to search the moves. Because the depth is <= 0 here, only captures,
1325 // queen promotions and checks (only if depth == 0) will be generated.
1326 MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1330 Bitboard dcCandidates = mp.discovered_check_candidates();
1331 bool isCheck = pos.is_check();
1333 // Loop through the moves until no moves remain or a beta cutoff
1335 while ( alpha < beta
1336 && (move = mp.get_next_move()) != MOVE_NONE)
1338 assert(move_is_ok(move));
1340 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1341 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1344 ss[ply].currentMove = move;
1347 if ( UseQSearchFutilityPruning
1350 && !move_promotion(move)
1351 && !moveIsPassedPawnPush
1352 && beta - alpha == 1
1353 && pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame)
1355 Value futilityValue = staticValue
1356 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1357 pos.endgame_value_of_piece_on(move_to(move)))
1359 + ei.futilityMargin;
1361 if (futilityValue < alpha)
1363 if (futilityValue > bestValue)
1364 bestValue = futilityValue;
1369 // Don't search captures and checks with negative SEE values.
1371 && !move_promotion(move)
1372 && (pos.midgame_value_of_piece_on(move_from(move)) >
1373 pos.midgame_value_of_piece_on(move_to(move)))
1374 && pos.see(move) < 0)
1377 // Make and search the move.
1379 pos.do_move(move, u, dcCandidates);
1380 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1381 pos.undo_move(move, u);
1383 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1386 if (value > bestValue)
1397 // All legal moves have been searched. A special case: If we're in check
1398 // and no legal moves were found, it is checkmate:
1399 if (pos.is_check() && moveCount == 0) // Mate!
1400 return value_mated_in(ply);
1402 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1404 // Update transposition table
1405 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1411 // sp_search() is used to search from a split point. This function is called
1412 // by each thread working at the split point. It is similar to the normal
1413 // search() function, but simpler. Because we have already probed the hash
1414 // table, done a null move search, and searched the first move before
1415 // splitting, we don't have to repeat all this work in sp_search(). We
1416 // also don't need to store anything to the hash table here: This is taken
1417 // care of after we return from the split point.
1419 void sp_search(SplitPoint *sp, int threadID) {
1420 assert(threadID >= 0 && threadID < ActiveThreads);
1421 assert(ActiveThreads > 1);
1423 Position pos = Position(sp->pos);
1424 SearchStack *ss = sp->sstack[threadID];
1427 int moveCount = sp->moves;
1428 bool isCheck = pos.is_check();
1429 bool useFutilityPruning =
1430 UseFutilityPruning && sp->depth < SelectiveDepth && !isCheck;
1432 while(sp->bestValue < sp->beta && !thread_should_stop(threadID)
1433 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) {
1435 Depth ext, newDepth;
1436 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1437 bool moveIsCapture = pos.move_is_capture(move);
1438 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1440 assert(move_is_ok(move));
1442 lock_grab(&(sp->lock));
1444 moveCount = sp->moves;
1445 lock_release(&(sp->lock));
1447 ss[sp->ply].currentMove = move;
1449 // Decide the new search depth.
1450 ext = extension(pos, move, false, moveIsCheck, false, false);
1451 newDepth = sp->depth - OnePly + ext;
1454 if(useFutilityPruning && ext == Depth(0) && !moveIsCapture
1455 && !moveIsPassedPawnPush && !move_promotion(move)
1456 && moveCount >= 2 + int(sp->depth)
1457 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1460 // Make and search the move.
1461 pos.do_move(move, u, sp->dcCandidates);
1462 if(ext == Depth(0) && moveCount >= LMRNonPVMoves
1463 && !moveIsCapture && !move_promotion(move) && !moveIsPassedPawnPush
1464 && !move_is_castle(move)
1465 && move != ss[sp->ply].killer1 && move != ss[sp->ply].killer2) {
1466 ss[sp->ply].reduction = OnePly;
1467 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1,
1472 if(value >= sp->beta) {
1473 ss[sp->ply].reduction = Depth(0);
1474 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true,
1477 pos.undo_move(move, u);
1479 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1481 if(thread_should_stop(threadID))
1485 lock_grab(&(sp->lock));
1486 if(value > sp->bestValue && !thread_should_stop(threadID)) {
1487 sp->bestValue = value;
1488 if(sp->bestValue >= sp->beta) {
1489 sp_update_pv(sp->parentSstack, ss, sp->ply);
1490 for(int i = 0; i < ActiveThreads; i++)
1491 if(i != threadID && (i == sp->master || sp->slaves[i]))
1492 Threads[i].stop = true;
1493 sp->finished = true;
1496 lock_release(&(sp->lock));
1499 lock_grab(&(sp->lock));
1501 // If this is the master thread and we have been asked to stop because of
1502 // a beta cutoff higher up in the tree, stop all slave threads:
1503 if(sp->master == threadID && thread_should_stop(threadID))
1504 for(int i = 0; i < ActiveThreads; i++)
1506 Threads[i].stop = true;
1509 sp->slaves[threadID] = 0;
1511 lock_release(&(sp->lock));
1515 // sp_search_pv() is used to search from a PV split point. This function
1516 // is called by each thread working at the split point. It is similar to
1517 // the normal search_pv() function, but simpler. Because we have already
1518 // probed the hash table and searched the first move before splitting, we
1519 // don't have to repeat all this work in sp_search_pv(). We also don't
1520 // need to store anything to the hash table here: This is taken care of
1521 // after we return from the split point.
1523 void sp_search_pv(SplitPoint *sp, int threadID) {
1524 assert(threadID >= 0 && threadID < ActiveThreads);
1525 assert(ActiveThreads > 1);
1527 Position pos = Position(sp->pos);
1528 SearchStack *ss = sp->sstack[threadID];
1531 int moveCount = sp->moves;
1533 while(sp->alpha < sp->beta && !thread_should_stop(threadID)
1534 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) {
1536 Depth ext, newDepth;
1537 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1538 bool moveIsCapture = pos.move_is_capture(move);
1539 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1541 assert(move_is_ok(move));
1543 ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1544 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1546 lock_grab(&(sp->lock));
1548 moveCount = sp->moves;
1549 lock_release(&(sp->lock));
1551 ss[sp->ply].currentMove = move;
1553 // Decide the new search depth.
1554 ext = extension(pos, move, true, moveIsCheck, false, false);
1555 newDepth = sp->depth - OnePly + ext;
1557 // Make and search the move.
1558 pos.do_move(move, u, sp->dcCandidates);
1559 if(ext == Depth(0) && moveCount >= LMRPVMoves && !moveIsCapture
1560 && !move_promotion(move) && !moveIsPassedPawnPush
1561 && !move_is_castle(move)
1562 && move != ss[sp->ply].killer1 && move != ss[sp->ply].killer2) {
1563 ss[sp->ply].reduction = OnePly;
1564 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1,
1568 value = sp->alpha + 1;
1569 if(value > sp->alpha) {
1570 ss[sp->ply].reduction = Depth(0);
1571 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true,
1573 if(value > sp->alpha && value < sp->beta) {
1574 if(sp->ply == 1 && RootMoveNumber == 1)
1575 // When the search fails high at ply 1 while searching the first
1576 // move at the root, set the flag failHighPly1. This is used for
1577 // time managment: We don't want to stop the search early in
1578 // such cases, because resolving the fail high at ply 1 could
1579 // result in a big drop in score at the root.
1580 Threads[threadID].failHighPly1 = true;
1581 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth,
1582 sp->ply+1, threadID);
1583 Threads[threadID].failHighPly1 = false;
1586 pos.undo_move(move, u);
1588 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1590 if(thread_should_stop(threadID))
1594 lock_grab(&(sp->lock));
1595 if(value > sp->bestValue && !thread_should_stop(threadID)) {
1596 sp->bestValue = value;
1597 if(value > sp->alpha) {
1599 sp_update_pv(sp->parentSstack, ss, sp->ply);
1600 if(value == value_mate_in(sp->ply + 1))
1601 ss[sp->ply].mateKiller = move;
1602 if(value >= sp->beta) {
1603 for(int i = 0; i < ActiveThreads; i++)
1604 if(i != threadID && (i == sp->master || sp->slaves[i]))
1605 Threads[i].stop = true;
1606 sp->finished = true;
1609 // If we are at ply 1, and we are searching the first root move at
1610 // ply 0, set the 'Problem' variable if the score has dropped a lot
1611 // (from the computer's point of view) since the previous iteration:
1612 if(Iteration >= 2 &&
1613 -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1616 lock_release(&(sp->lock));
1619 lock_grab(&(sp->lock));
1621 // If this is the master thread and we have been asked to stop because of
1622 // a beta cutoff higher up in the tree, stop all slave threads:
1623 if(sp->master == threadID && thread_should_stop(threadID))
1624 for(int i = 0; i < ActiveThreads; i++)
1626 Threads[i].stop = true;
1629 sp->slaves[threadID] = 0;
1631 lock_release(&(sp->lock));
1635 /// The RootMove class
1639 RootMove::RootMove() {
1640 nodes = cumulativeNodes = 0ULL;
1643 // RootMove::operator<() is the comparison function used when
1644 // sorting the moves. A move m1 is considered to be better
1645 // than a move m2 if it has a higher score, or if the moves
1646 // have equal score but m1 has the higher node count.
1648 bool RootMove::operator<(const RootMove& m) {
1650 if (score != m.score)
1651 return (score < m.score);
1653 return nodes <= m.nodes;
1656 /// The RootMoveList class
1660 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1662 MoveStack mlist[MaxRootMoves];
1663 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1665 // Generate all legal moves
1666 int lm_count = generate_legal_moves(pos, mlist);
1668 // Add each move to the moves[] array
1669 for (int i = 0; i < lm_count; i++)
1671 bool includeMove = includeAllMoves;
1673 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1674 includeMove = (searchMoves[k] == mlist[i].move);
1678 // Find a quick score for the move
1680 SearchStack ss[PLY_MAX_PLUS_2];
1682 moves[count].move = mlist[i].move;
1683 moves[count].nodes = 0ULL;
1684 pos.do_move(moves[count].move, u);
1685 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1687 pos.undo_move(moves[count].move, u);
1688 moves[count].pv[0] = moves[i].move;
1689 moves[count].pv[1] = MOVE_NONE; // FIXME
1697 // Simple accessor methods for the RootMoveList class
1699 inline Move RootMoveList::get_move(int moveNum) const {
1700 return moves[moveNum].move;
1703 inline Value RootMoveList::get_move_score(int moveNum) const {
1704 return moves[moveNum].score;
1707 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1708 moves[moveNum].score = score;
1711 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1712 moves[moveNum].nodes = nodes;
1713 moves[moveNum].cumulativeNodes += nodes;
1716 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1718 for(j = 0; pv[j] != MOVE_NONE; j++)
1719 moves[moveNum].pv[j] = pv[j];
1720 moves[moveNum].pv[j] = MOVE_NONE;
1723 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1724 return moves[moveNum].pv[i];
1727 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1728 return moves[moveNum].cumulativeNodes;
1731 inline int RootMoveList::move_count() const {
1736 // RootMoveList::scan_for_easy_move() is called at the end of the first
1737 // iteration, and is used to detect an "easy move", i.e. a move which appears
1738 // to be much bester than all the rest. If an easy move is found, the move
1739 // is returned, otherwise the function returns MOVE_NONE. It is very
1740 // important that this function is called at the right moment: The code
1741 // assumes that the first iteration has been completed and the moves have
1742 // been sorted. This is done in RootMoveList c'tor.
1744 Move RootMoveList::scan_for_easy_move() const {
1751 // moves are sorted so just consider the best and the second one
1752 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1758 // RootMoveList::sort() sorts the root move list at the beginning of a new
1761 inline void RootMoveList::sort() {
1763 sort_multipv(count - 1); // all items
1767 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1768 // list by their scores and depths. It is used to order the different PVs
1769 // correctly in MultiPV mode.
1771 void RootMoveList::sort_multipv(int n) {
1773 for (int i = 1; i <= n; i++)
1775 RootMove rm = moves[i];
1777 for (j = i; j > 0 && moves[j-1] < rm; j--)
1778 moves[j] = moves[j-1];
1784 // init_search_stack() initializes a search stack at the beginning of a
1785 // new search from the root.
1787 void init_search_stack(SearchStack ss[]) {
1788 for(int i = 0; i < 3; i++) {
1789 ss[i].pv[i] = MOVE_NONE;
1790 ss[i].pv[i+1] = MOVE_NONE;
1791 ss[i].currentMove = MOVE_NONE;
1792 ss[i].mateKiller = MOVE_NONE;
1793 ss[i].killer1 = MOVE_NONE;
1794 ss[i].killer2 = MOVE_NONE;
1795 ss[i].threatMove = MOVE_NONE;
1796 ss[i].reduction = Depth(0);
1801 // init_node() is called at the beginning of all the search functions
1802 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1803 // stack object corresponding to the current node. Once every
1804 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1805 // for user input and checks whether it is time to stop the search.
1807 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1808 assert(ply >= 0 && ply < PLY_MAX);
1809 assert(threadID >= 0 && threadID < ActiveThreads);
1811 Threads[threadID].nodes++;
1815 if(NodesSincePoll >= NodesBetweenPolls) {
1821 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1822 ss[ply+2].mateKiller = MOVE_NONE;
1823 ss[ply+2].killer1 = ss[ply+2].killer2 = MOVE_NONE;
1824 ss[ply].threatMove = MOVE_NONE;
1825 ss[ply].reduction = Depth(0);
1826 ss[ply].currentMoveCaptureValue = Value(0);
1828 if(Threads[threadID].printCurrentLine)
1829 print_current_line(ss, ply, threadID);
1833 // update_pv() is called whenever a search returns a value > alpha. It
1834 // updates the PV in the SearchStack object corresponding to the current
1837 void update_pv(SearchStack ss[], int ply) {
1838 assert(ply >= 0 && ply < PLY_MAX);
1840 ss[ply].pv[ply] = ss[ply].currentMove;
1842 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1843 ss[ply].pv[p] = ss[ply+1].pv[p];
1844 ss[ply].pv[p] = MOVE_NONE;
1848 // sp_update_pv() is a variant of update_pv for use at split points. The
1849 // difference between the two functions is that sp_update_pv also updates
1850 // the PV at the parent node.
1852 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1853 assert(ply >= 0 && ply < PLY_MAX);
1855 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1857 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1858 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1859 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1863 // connected_moves() tests whether two moves are 'connected' in the sense
1864 // that the first move somehow made the second move possible (for instance
1865 // if the moving piece is the same in both moves). The first move is
1866 // assumed to be the move that was made to reach the current position, while
1867 // the second move is assumed to be a move from the current position.
1869 bool connected_moves(const Position &pos, Move m1, Move m2) {
1870 Square f1, t1, f2, t2;
1872 assert(move_is_ok(m1));
1873 assert(move_is_ok(m2));
1878 // Case 1: The moving piece is the same in both moves.
1884 // Case 2: The destination square for m2 was vacated by m1.
1890 // Case 3: Moving through the vacated square:
1891 if(piece_is_slider(pos.piece_on(f2)) &&
1892 bit_is_set(squares_between(f2, t2), f1))
1895 // Case 4: The destination square for m2 is attacked by the moving piece
1897 if(pos.piece_attacks_square(t1, t2))
1900 // Case 5: Discovered check, checking piece is the piece moved in m1:
1901 if(piece_is_slider(pos.piece_on(t1)) &&
1902 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
1904 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
1906 Bitboard occ = pos.occupied_squares();
1907 Color us = pos.side_to_move();
1908 Square ksq = pos.king_square(us);
1909 clear_bit(&occ, f2);
1910 if(pos.type_of_piece_on(t1) == BISHOP) {
1911 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
1914 else if(pos.type_of_piece_on(t1) == ROOK) {
1915 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
1919 assert(pos.type_of_piece_on(t1) == QUEEN);
1920 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
1929 // extension() decides whether a move should be searched with normal depth,
1930 // or with extended depth. Certain classes of moves (checking moves, in
1931 // particular) are searched with bigger depth than ordinary moves.
1933 Depth extension(const Position &pos, Move m, bool pvNode,
1934 bool check, bool singleReply, bool mateThreat) {
1935 Depth result = Depth(0);
1938 result += CheckExtension[pvNode];
1940 result += SingleReplyExtension[pvNode];
1941 if(pos.move_is_pawn_push_to_7th(m))
1942 result += PawnPushTo7thExtension[pvNode];
1943 if(pos.move_is_passed_pawn_push(m))
1944 result += PassedPawnExtension[pvNode];
1946 result += MateThreatExtension[pvNode];
1947 if(pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
1948 && (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
1949 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
1950 && !move_promotion(m))
1951 result += PawnEndgameExtension[pvNode];
1952 if(pvNode && pos.move_is_capture(m)
1953 && pos.type_of_piece_on(move_to(m)) != PAWN && pos.see(m) >= 0)
1956 return Min(result, OnePly);
1960 // ok_to_do_nullmove() looks at the current position and decides whether
1961 // doing a 'null move' should be allowed. In order to avoid zugzwang
1962 // problems, null moves are not allowed when the side to move has very
1963 // little material left. Currently, the test is a bit too simple: Null
1964 // moves are avoided only when the side to move has only pawns left. It's
1965 // probably a good idea to avoid null moves in at least some more
1966 // complicated endgames, e.g. KQ vs KR. FIXME
1968 bool ok_to_do_nullmove(const Position &pos) {
1969 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
1975 // ok_to_prune() tests whether it is safe to forward prune a move. Only
1976 // non-tactical moves late in the move list close to the leaves are
1977 // candidates for pruning.
1979 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
1980 Square mfrom, mto, tfrom, tto;
1982 assert(move_is_ok(m));
1983 assert(threat == MOVE_NONE || move_is_ok(threat));
1984 assert(!move_promotion(m));
1985 assert(!pos.move_is_check(m));
1986 assert(!pos.move_is_capture(m));
1987 assert(!pos.move_is_passed_pawn_push(m));
1988 assert(d >= OnePly);
1990 mfrom = move_from(m);
1992 tfrom = move_from(threat);
1993 tto = move_to(threat);
1995 // Case 1: Castling moves are never pruned.
1996 if(move_is_castle(m))
1999 // Case 2: Don't prune moves which move the threatened piece
2000 if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2003 // Case 3: If the threatened piece has value less than or equal to the
2004 // value of the threatening piece, don't prune move which defend it.
2005 if(!PruneDefendingMoves && threat != MOVE_NONE
2006 && (piece_value_midgame(pos.piece_on(tfrom))
2007 >= piece_value_midgame(pos.piece_on(tto)))
2008 && pos.move_attacks_square(m, tto))
2011 // Case 4: Don't prune moves with good history.
2012 if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2015 // Case 5: If the moving piece in the threatened move is a slider, don't
2016 // prune safe moves which block its ray.
2017 if(!PruneBlockingMoves && threat != MOVE_NONE
2018 && piece_is_slider(pos.piece_on(tfrom))
2019 && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2026 // ok_to_use_TT() returns true if a transposition table score
2027 // can be used at a given point in search.
2029 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2031 Value v = value_from_tt(tte->value(), ply);
2033 return ( tte->depth() >= depth
2034 || v >= Max(value_mate_in(100), beta)
2035 || v < Min(value_mated_in(100), beta))
2037 && ( (is_lower_bound(tte->type()) && v >= beta)
2038 || (is_upper_bound(tte->type()) && v < beta));
2042 // ok_to_history() returns true if a move m can be stored
2043 // in history. Should be a non capturing move.
2045 bool ok_to_history(const Position& pos, Move m) {
2047 return pos.square_is_empty(move_to(m))
2048 && !move_promotion(m)
2053 // update_history() registers a good move that produced a beta-cutoff
2054 // in history and marks as failures all the other moves of that ply.
2056 void update_history(const Position& pos, Move m, Depth depth,
2057 Move movesSearched[], int moveCount) {
2059 H.success(pos.piece_on(move_from(m)), m, depth);
2061 for (int i = 0; i < moveCount - 1; i++)
2062 if (ok_to_history(pos, movesSearched[i]) && m != movesSearched[i])
2063 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2066 // fail_high_ply_1() checks if some thread is currently resolving a fail
2067 // high at ply 1 at the node below the first root node. This information
2068 // is used for time managment.
2070 bool fail_high_ply_1() {
2071 for(int i = 0; i < ActiveThreads; i++)
2072 if(Threads[i].failHighPly1)
2078 // current_search_time() returns the number of milliseconds which have passed
2079 // since the beginning of the current search.
2081 int current_search_time() {
2082 return get_system_time() - SearchStartTime;
2086 // nps() computes the current nodes/second count.
2089 int t = current_search_time();
2090 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2094 // poll() performs two different functions: It polls for user input, and it
2095 // looks at the time consumed so far and decides if it's time to abort the
2100 static int lastInfoTime;
2102 t = current_search_time();
2108 if(fgets(input, 255, stdin) == NULL)
2109 strcpy(input, "quit\n");
2110 if(strncmp(input, "quit", 4) == 0) {
2112 PonderSearch = false;
2115 else if(strncmp(input, "stop", 4) == 0) {
2117 PonderSearch = false;
2119 else if(strncmp(input, "ponderhit", 9) == 0)
2123 // Print search information
2126 else if(lastInfoTime > t)
2127 // HACK: Must be a new search where we searched less than
2128 // NodesBetweenPolls nodes during the first second of search.
2130 else if(t - lastInfoTime >= 1000) {
2133 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2134 << " time " << t << " hashfull " << TT.full() << std::endl;
2135 lock_release(&IOLock);
2137 Threads[0].printCurrentLine = true;
2140 // Should we stop the search?
2141 if(!PonderSearch && Iteration >= 2 &&
2142 (!InfiniteSearch && (t > AbsoluteMaxSearchTime ||
2143 (RootMoveNumber == 1 &&
2144 t > MaxSearchTime + ExtraSearchTime) ||
2145 (!FailHigh && !fail_high_ply_1() && !Problem &&
2146 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2149 if(!PonderSearch && ExactMaxTime && t >= ExactMaxTime)
2152 if(!PonderSearch && Iteration >= 3 && MaxNodes
2153 && nodes_searched() >= MaxNodes)
2158 // ponderhit() is called when the program is pondering (i.e. thinking while
2159 // it's the opponent's turn to move) in order to let the engine know that
2160 // it correctly predicted the opponent's move.
2163 int t = current_search_time();
2164 PonderSearch = false;
2165 if(Iteration >= 2 &&
2166 (!InfiniteSearch && (StopOnPonderhit ||
2167 t > AbsoluteMaxSearchTime ||
2168 (RootMoveNumber == 1 &&
2169 t > MaxSearchTime + ExtraSearchTime) ||
2170 (!FailHigh && !fail_high_ply_1() && !Problem &&
2171 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2176 // print_current_line() prints the current line of search for a given
2177 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2179 void print_current_line(SearchStack ss[], int ply, int threadID) {
2180 assert(ply >= 0 && ply < PLY_MAX);
2181 assert(threadID >= 0 && threadID < ActiveThreads);
2183 if(!Threads[threadID].idle) {
2185 std::cout << "info currline " << (threadID + 1);
2186 for(int p = 0; p < ply; p++)
2187 std::cout << " " << ss[p].currentMove;
2188 std::cout << std::endl;
2189 lock_release(&IOLock);
2191 Threads[threadID].printCurrentLine = false;
2192 if(threadID + 1 < ActiveThreads)
2193 Threads[threadID + 1].printCurrentLine = true;
2197 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2198 // while the program is pondering. The point is to work around a wrinkle in
2199 // the UCI protocol: When pondering, the engine is not allowed to give a
2200 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2201 // We simply wait here until one of these commands is sent, and return,
2202 // after which the bestmove and pondermove will be printed (in id_loop()).
2204 void wait_for_stop_or_ponderhit() {
2205 std::string command;
2208 if(!std::getline(std::cin, command))
2211 if(command == "quit") {
2212 OpeningBook.close();
2217 else if(command == "ponderhit" || command == "stop")
2223 // idle_loop() is where the threads are parked when they have no work to do.
2224 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2225 // object for which the current thread is the master.
2227 void idle_loop(int threadID, SplitPoint *waitSp) {
2228 assert(threadID >= 0 && threadID < THREAD_MAX);
2230 Threads[threadID].running = true;
2233 if(AllThreadsShouldExit && threadID != 0)
2236 // If we are not thinking, wait for a condition to be signaled instead
2237 // of wasting CPU time polling for work:
2238 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2239 #if !defined(_MSC_VER)
2240 pthread_mutex_lock(&WaitLock);
2241 if(Idle || threadID >= ActiveThreads)
2242 pthread_cond_wait(&WaitCond, &WaitLock);
2243 pthread_mutex_unlock(&WaitLock);
2245 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2249 // If this thread has been assigned work, launch a search:
2250 if(Threads[threadID].workIsWaiting) {
2251 Threads[threadID].workIsWaiting = false;
2252 if(Threads[threadID].splitPoint->pvNode)
2253 sp_search_pv(Threads[threadID].splitPoint, threadID);
2255 sp_search(Threads[threadID].splitPoint, threadID);
2256 Threads[threadID].idle = true;
2259 // If this thread is the master of a split point and all threads have
2260 // finished their work at this split point, return from the idle loop:
2261 if(waitSp != NULL && waitSp->cpus == 0)
2265 Threads[threadID].running = false;
2269 // init_split_point_stack() is called during program initialization, and
2270 // initializes all split point objects.
2272 void init_split_point_stack() {
2273 for(int i = 0; i < THREAD_MAX; i++)
2274 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2275 SplitPointStack[i][j].parent = NULL;
2276 lock_init(&(SplitPointStack[i][j].lock), NULL);
2281 // destroy_split_point_stack() is called when the program exits, and
2282 // destroys all locks in the precomputed split point objects.
2284 void destroy_split_point_stack() {
2285 for(int i = 0; i < THREAD_MAX; i++)
2286 for(int j = 0; j < MaxActiveSplitPoints; j++)
2287 lock_destroy(&(SplitPointStack[i][j].lock));
2291 // thread_should_stop() checks whether the thread with a given threadID has
2292 // been asked to stop, directly or indirectly. This can happen if a beta
2293 // cutoff has occured in thre thread's currently active split point, or in
2294 // some ancestor of the current split point.
2296 bool thread_should_stop(int threadID) {
2297 assert(threadID >= 0 && threadID < ActiveThreads);
2301 if(Threads[threadID].stop)
2303 if(ActiveThreads <= 2)
2305 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2307 Threads[threadID].stop = true;
2314 // thread_is_available() checks whether the thread with threadID "slave" is
2315 // available to help the thread with threadID "master" at a split point. An
2316 // obvious requirement is that "slave" must be idle. With more than two
2317 // threads, this is not by itself sufficient: If "slave" is the master of
2318 // some active split point, it is only available as a slave to the other
2319 // threads which are busy searching the split point at the top of "slave"'s
2320 // split point stack (the "helpful master concept" in YBWC terminology).
2322 bool thread_is_available(int slave, int master) {
2323 assert(slave >= 0 && slave < ActiveThreads);
2324 assert(master >= 0 && master < ActiveThreads);
2325 assert(ActiveThreads > 1);
2327 if(!Threads[slave].idle || slave == master)
2330 if(Threads[slave].activeSplitPoints == 0)
2331 // No active split points means that the thread is available as a slave
2332 // for any other thread.
2335 if(ActiveThreads == 2)
2338 // Apply the "helpful master" concept if possible.
2339 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2346 // idle_thread_exists() tries to find an idle thread which is available as
2347 // a slave for the thread with threadID "master".
2349 bool idle_thread_exists(int master) {
2350 assert(master >= 0 && master < ActiveThreads);
2351 assert(ActiveThreads > 1);
2353 for(int i = 0; i < ActiveThreads; i++)
2354 if(thread_is_available(i, master))
2360 // split() does the actual work of distributing the work at a node between
2361 // several threads at PV nodes. If it does not succeed in splitting the
2362 // node (because no idle threads are available, or because we have no unused
2363 // split point objects), the function immediately returns false. If
2364 // splitting is possible, a SplitPoint object is initialized with all the
2365 // data that must be copied to the helper threads (the current position and
2366 // search stack, alpha, beta, the search depth, etc.), and we tell our
2367 // helper threads that they have been assigned work. This will cause them
2368 // to instantly leave their idle loops and call sp_search_pv(). When all
2369 // threads have returned from sp_search_pv (or, equivalently, when
2370 // splitPoint->cpus becomes 0), split() returns true.
2372 bool split(const Position &p, SearchStack *sstck, int ply,
2373 Value *alpha, Value *beta, Value *bestValue,
2374 Depth depth, int *moves,
2375 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2377 assert(sstck != NULL);
2378 assert(ply >= 0 && ply < PLY_MAX);
2379 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2380 assert(!pvNode || *alpha < *beta);
2381 assert(*beta <= VALUE_INFINITE);
2382 assert(depth > Depth(0));
2383 assert(master >= 0 && master < ActiveThreads);
2384 assert(ActiveThreads > 1);
2386 SplitPoint *splitPoint;
2391 // If no other thread is available to help us, or if we have too many
2392 // active split points, don't split:
2393 if(!idle_thread_exists(master) ||
2394 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2395 lock_release(&MPLock);
2399 // Pick the next available split point object from the split point stack:
2400 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2401 Threads[master].activeSplitPoints++;
2403 // Initialize the split point object:
2404 splitPoint->parent = Threads[master].splitPoint;
2405 splitPoint->finished = false;
2406 splitPoint->ply = ply;
2407 splitPoint->depth = depth;
2408 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2409 splitPoint->beta = *beta;
2410 splitPoint->pvNode = pvNode;
2411 splitPoint->dcCandidates = dcCandidates;
2412 splitPoint->bestValue = *bestValue;
2413 splitPoint->master = master;
2414 splitPoint->mp = mp;
2415 splitPoint->moves = *moves;
2416 splitPoint->cpus = 1;
2417 splitPoint->pos.copy(p);
2418 splitPoint->parentSstack = sstck;
2419 for(i = 0; i < ActiveThreads; i++)
2420 splitPoint->slaves[i] = 0;
2422 // Copy the current position and the search stack to the master thread:
2423 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2424 Threads[master].splitPoint = splitPoint;
2426 // Make copies of the current position and search stack for each thread:
2427 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2429 if(thread_is_available(i, master)) {
2430 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2431 Threads[i].splitPoint = splitPoint;
2432 splitPoint->slaves[i] = 1;
2436 // Tell the threads that they have work to do. This will make them leave
2438 for(i = 0; i < ActiveThreads; i++)
2439 if(i == master || splitPoint->slaves[i]) {
2440 Threads[i].workIsWaiting = true;
2441 Threads[i].idle = false;
2442 Threads[i].stop = false;
2445 lock_release(&MPLock);
2447 // Everything is set up. The master thread enters the idle loop, from
2448 // which it will instantly launch a search, because its workIsWaiting
2449 // slot is 'true'. We send the split point as a second parameter to the
2450 // idle loop, which means that the main thread will return from the idle
2451 // loop when all threads have finished their work at this split point
2452 // (i.e. when // splitPoint->cpus == 0).
2453 idle_loop(master, splitPoint);
2455 // We have returned from the idle loop, which means that all threads are
2456 // finished. Update alpha, beta and bestvalue, and return:
2458 if(pvNode) *alpha = splitPoint->alpha;
2459 *beta = splitPoint->beta;
2460 *bestValue = splitPoint->bestValue;
2461 Threads[master].stop = false;
2462 Threads[master].idle = false;
2463 Threads[master].activeSplitPoints--;
2464 Threads[master].splitPoint = splitPoint->parent;
2465 lock_release(&MPLock);
2471 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2472 // to start a new search from the root.
2474 void wake_sleeping_threads() {
2475 if(ActiveThreads > 1) {
2476 for(int i = 1; i < ActiveThreads; i++) {
2477 Threads[i].idle = true;
2478 Threads[i].workIsWaiting = false;
2480 #if !defined(_MSC_VER)
2481 pthread_mutex_lock(&WaitLock);
2482 pthread_cond_broadcast(&WaitCond);
2483 pthread_mutex_unlock(&WaitLock);
2485 for(int i = 1; i < THREAD_MAX; i++)
2486 SetEvent(SitIdleEvent[i]);
2492 // init_thread() is the function which is called when a new thread is
2493 // launched. It simply calls the idle_loop() function with the supplied
2494 // threadID. There are two versions of this function; one for POSIX threads
2495 // and one for Windows threads.
2497 #if !defined(_MSC_VER)
2499 void *init_thread(void *threadID) {
2500 idle_loop(*(int *)threadID, NULL);
2506 DWORD WINAPI init_thread(LPVOID threadID) {
2507 idle_loop(*(int *)threadID, NULL);