forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 9
/
constraint_solver.cc
3336 lines (2916 loc) · 109 KB
/
constraint_solver.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2010-2024 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// This file implements the core objects of the constraint solver:
// Solver, Search, Queue, ... along with the main resolution loop.
#include "ortools/constraint_solver/constraint_solver.h"
#include <algorithm>
#include <csetjmp>
#include <cstdint>
#include <deque>
#include <iosfwd>
#include <limits>
#include <memory>
#include <ostream>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "absl/flags/flag.h"
#include "absl/log/check.h"
#include "absl/time/time.h"
#include "ortools/base/logging.h"
#include "ortools/base/map_util.h"
#include "ortools/base/stl_util.h"
#include "ortools/base/sysinfo.h"
#include "ortools/base/timer.h"
#include "ortools/constraint_solver/constraint_solveri.h"
#include "ortools/util/tuple_set.h"
#include "zconf.h"
#include "zlib.h"
// These flags are used to set the fields in the DefaultSolverParameters proto.
ABSL_FLAG(bool, cp_trace_propagation, false,
"Trace propagation events (constraint and demon executions,"
" variable modifications).");
ABSL_FLAG(bool, cp_trace_search, false, "Trace search events");
ABSL_FLAG(bool, cp_print_added_constraints, false,
"show all constraints added to the solver.");
ABSL_FLAG(bool, cp_print_model, false,
"use PrintModelVisitor on model before solving.");
ABSL_FLAG(bool, cp_model_stats, false,
"use StatisticsModelVisitor on model before solving.");
ABSL_FLAG(bool, cp_disable_solve, false,
"Force failure at the beginning of a search.");
ABSL_FLAG(std::string, cp_profile_file, "",
"Export profiling overview to file.");
ABSL_FLAG(bool, cp_print_local_search_profile, false,
"Print local search profiling data after solving.");
ABSL_FLAG(bool, cp_name_variables, false, "Force all variables to have names.");
ABSL_FLAG(bool, cp_name_cast_variables, false,
"Name variables casted from expressions");
ABSL_FLAG(bool, cp_use_small_table, true,
"Use small compact table constraint when possible.");
ABSL_FLAG(bool, cp_use_cumulative_edge_finder, true,
"Use the O(n log n) cumulative edge finding algorithm described "
"in 'Edge Finding Filtering Algorithm for Discrete Cumulative "
"Resources in O(kn log n)' by Petr Vilim, CP 2009.");
ABSL_FLAG(bool, cp_use_cumulative_time_table, true,
"Use a O(n^2) cumulative time table propagation algorithm.");
ABSL_FLAG(bool, cp_use_cumulative_time_table_sync, false,
"Use a synchronized O(n^2 log n) cumulative time table propagation "
"algorithm.");
ABSL_FLAG(bool, cp_use_sequence_high_demand_tasks, true,
"Use a sequence constraints for cumulative tasks that have a "
"demand greater than half of the capacity of the resource.");
ABSL_FLAG(bool, cp_use_all_possible_disjunctions, true,
"Post temporal disjunctions for all pairs of tasks sharing a "
"cumulative resource and that cannot overlap because the sum of "
"their demand exceeds the capacity.");
ABSL_FLAG(int, cp_max_edge_finder_size, 50,
"Do not post the edge finder in the cumulative constraints if "
"it contains more than this number of tasks");
ABSL_FLAG(bool, cp_diffn_use_cumulative, true,
"Diffn constraint adds redundant cumulative constraint");
ABSL_FLAG(bool, cp_use_element_rmq, true,
"If true, rmq's will be used in element expressions.");
ABSL_FLAG(int, cp_check_solution_period, 1,
"Number of solutions explored between two solution checks during "
"local search.");
ABSL_FLAG(int64_t, cp_random_seed, 12345,
"Random seed used in several (but not all) random number "
"generators used by the CP solver. Use -1 to auto-generate an"
"undeterministic random seed.");
void ConstraintSolverFailsHere() { VLOG(3) << "Fail"; }
#if defined(_MSC_VER) // WINDOWS
#pragma warning(disable : 4351 4355)
#endif
namespace operations_research {
namespace {
// Calls the given method with the provided arguments on all objects in the
// collection.
template <typename T, typename MethodPointer, typename... Args>
void ForAll(const std::vector<T*>& objects, MethodPointer method,
const Args&... args) {
for (T* const object : objects) {
DCHECK(object != nullptr);
(object->*method)(args...);
}
}
// Converts a scoped enum to its underlying type.
template <typename E>
constexpr typename std::underlying_type<E>::type to_underlying(E e) {
return static_cast<typename std::underlying_type<E>::type>(e);
}
} // namespace
// ----- ConstraintSolverParameters -----
ConstraintSolverParameters Solver::DefaultSolverParameters() {
ConstraintSolverParameters params;
params.set_compress_trail(ConstraintSolverParameters::NO_COMPRESSION);
params.set_trail_block_size(8000);
params.set_array_split_size(16);
params.set_store_names(true);
params.set_profile_propagation(!absl::GetFlag(FLAGS_cp_profile_file).empty());
params.set_trace_propagation(absl::GetFlag(FLAGS_cp_trace_propagation));
params.set_trace_search(absl::GetFlag(FLAGS_cp_trace_search));
params.set_name_all_variables(absl::GetFlag(FLAGS_cp_name_variables));
params.set_profile_file(absl::GetFlag(FLAGS_cp_profile_file));
params.set_profile_local_search(
absl::GetFlag(FLAGS_cp_print_local_search_profile));
params.set_print_local_search_profile(
absl::GetFlag(FLAGS_cp_print_local_search_profile));
params.set_print_model(absl::GetFlag(FLAGS_cp_print_model));
params.set_print_model_stats(absl::GetFlag(FLAGS_cp_model_stats));
params.set_disable_solve(absl::GetFlag(FLAGS_cp_disable_solve));
params.set_name_cast_variables(absl::GetFlag(FLAGS_cp_name_cast_variables));
params.set_print_added_constraints(
absl::GetFlag(FLAGS_cp_print_added_constraints));
params.set_use_small_table(absl::GetFlag(FLAGS_cp_use_small_table));
params.set_use_cumulative_edge_finder(
absl::GetFlag(FLAGS_cp_use_cumulative_edge_finder));
params.set_use_cumulative_time_table(
absl::GetFlag(FLAGS_cp_use_cumulative_time_table));
params.set_use_cumulative_time_table_sync(
absl::GetFlag(FLAGS_cp_use_cumulative_time_table_sync));
params.set_use_sequence_high_demand_tasks(
absl::GetFlag(FLAGS_cp_use_sequence_high_demand_tasks));
params.set_use_all_possible_disjunctions(
absl::GetFlag(FLAGS_cp_use_all_possible_disjunctions));
params.set_max_edge_finder_size(absl::GetFlag(FLAGS_cp_max_edge_finder_size));
params.set_diffn_use_cumulative(absl::GetFlag(FLAGS_cp_diffn_use_cumulative));
params.set_use_element_rmq(absl::GetFlag(FLAGS_cp_use_element_rmq));
params.set_check_solution_period(
absl::GetFlag(FLAGS_cp_check_solution_period));
return params;
}
// ----- Forward Declarations and Profiling Support -----
extern void InstallDemonProfiler(DemonProfiler* monitor);
extern DemonProfiler* BuildDemonProfiler(Solver* solver);
extern void DeleteDemonProfiler(DemonProfiler* monitor);
extern void InstallLocalSearchProfiler(LocalSearchProfiler* monitor);
extern LocalSearchProfiler* BuildLocalSearchProfiler(Solver* solver);
extern void DeleteLocalSearchProfiler(LocalSearchProfiler* monitor);
// TODO(user): remove this complex logic.
// We need the double test because parameters are set too late when using
// python in the open source. This is the cheapest work-around.
bool Solver::InstrumentsDemons() const {
return IsProfilingEnabled() || InstrumentsVariables();
}
bool Solver::IsProfilingEnabled() const {
return parameters_.profile_propagation() ||
!parameters_.profile_file().empty();
}
bool Solver::IsLocalSearchProfilingEnabled() const {
return parameters_.profile_local_search() ||
parameters_.print_local_search_profile();
}
bool Solver::InstrumentsVariables() const {
return parameters_.trace_propagation();
}
bool Solver::NameAllVariables() const {
return parameters_.name_all_variables();
}
// ------------------ Demon class ----------------
Solver::DemonPriority Demon::priority() const {
return Solver::NORMAL_PRIORITY;
}
std::string Demon::DebugString() const { return "Demon"; }
void Demon::inhibit(Solver* const s) {
if (stamp_ < std::numeric_limits<uint64_t>::max()) {
s->SaveAndSetValue(&stamp_, std::numeric_limits<uint64_t>::max());
}
}
void Demon::desinhibit(Solver* const s) {
if (stamp_ == std::numeric_limits<uint64_t>::max()) {
s->SaveAndSetValue(&stamp_, s->stamp() - 1);
}
}
// ------------------ Queue class ------------------
extern void CleanVariableOnFail(IntVar* var);
class Queue {
public:
static constexpr int64_t kTestPeriod = 10000;
explicit Queue(Solver* const s)
: solver_(s),
stamp_(1),
freeze_level_(0),
in_process_(false),
clean_action_(nullptr),
clean_variable_(nullptr),
in_add_(false),
instruments_demons_(s->InstrumentsDemons()) {}
~Queue() {}
void Freeze() {
freeze_level_++;
stamp_++;
}
void Unfreeze() {
if (--freeze_level_ == 0) {
Process();
}
}
void ProcessOneDemon(Demon* const demon) {
demon->set_stamp(stamp_ - 1);
if (!instruments_demons_) {
if (++solver_->demon_runs_[demon->priority()] % kTestPeriod == 0) {
solver_->TopPeriodicCheck();
}
demon->Run(solver_);
solver_->CheckFail();
} else {
solver_->GetPropagationMonitor()->BeginDemonRun(demon);
if (++solver_->demon_runs_[demon->priority()] % kTestPeriod == 0) {
solver_->TopPeriodicCheck();
}
demon->Run(solver_);
solver_->CheckFail();
solver_->GetPropagationMonitor()->EndDemonRun(demon);
}
}
void Process() {
if (!in_process_) {
in_process_ = true;
while (!var_queue_.empty() || !delayed_queue_.empty()) {
if (!var_queue_.empty()) {
Demon* const demon = var_queue_.front();
var_queue_.pop_front();
ProcessOneDemon(demon);
} else {
DCHECK(!delayed_queue_.empty());
Demon* const demon = delayed_queue_.front();
delayed_queue_.pop_front();
ProcessOneDemon(demon);
}
}
in_process_ = false;
}
}
void ExecuteAll(const SimpleRevFIFO<Demon*>& demons) {
if (!instruments_demons_) {
for (SimpleRevFIFO<Demon*>::Iterator it(&demons); it.ok(); ++it) {
Demon* const demon = *it;
if (demon->stamp() < stamp_) {
DCHECK_EQ(demon->priority(), Solver::NORMAL_PRIORITY);
if (++solver_->demon_runs_[Solver::NORMAL_PRIORITY] % kTestPeriod ==
0) {
solver_->TopPeriodicCheck();
}
demon->Run(solver_);
solver_->CheckFail();
}
}
} else {
for (SimpleRevFIFO<Demon*>::Iterator it(&demons); it.ok(); ++it) {
Demon* const demon = *it;
if (demon->stamp() < stamp_) {
DCHECK_EQ(demon->priority(), Solver::NORMAL_PRIORITY);
solver_->GetPropagationMonitor()->BeginDemonRun(demon);
if (++solver_->demon_runs_[Solver::NORMAL_PRIORITY] % kTestPeriod ==
0) {
solver_->TopPeriodicCheck();
}
demon->Run(solver_);
solver_->CheckFail();
solver_->GetPropagationMonitor()->EndDemonRun(demon);
}
}
}
}
void EnqueueAll(const SimpleRevFIFO<Demon*>& demons) {
for (SimpleRevFIFO<Demon*>::Iterator it(&demons); it.ok(); ++it) {
EnqueueDelayedDemon(*it);
}
}
void EnqueueVar(Demon* const demon) {
DCHECK(demon->priority() == Solver::VAR_PRIORITY);
if (demon->stamp() < stamp_) {
demon->set_stamp(stamp_);
var_queue_.push_back(demon);
if (freeze_level_ == 0) {
Process();
}
}
}
void EnqueueDelayedDemon(Demon* const demon) {
DCHECK(demon->priority() == Solver::DELAYED_PRIORITY);
if (demon->stamp() < stamp_) {
demon->set_stamp(stamp_);
delayed_queue_.push_back(demon);
}
}
void AfterFailure() {
// Clean queue.
var_queue_.clear();
delayed_queue_.clear();
// Call cleaning actions on variables.
if (clean_action_ != nullptr) {
clean_action_(solver_);
clean_action_ = nullptr;
} else if (clean_variable_ != nullptr) {
CleanVariableOnFail(clean_variable_);
clean_variable_ = nullptr;
}
freeze_level_ = 0;
in_process_ = false;
in_add_ = false;
to_add_.clear();
}
void increase_stamp() { stamp_++; }
uint64_t stamp() const { return stamp_; }
void set_action_on_fail(Solver::Action a) {
DCHECK(clean_variable_ == nullptr);
clean_action_ = std::move(a);
}
void set_variable_to_clean_on_fail(IntVar* var) {
DCHECK(clean_action_ == nullptr);
clean_variable_ = var;
}
void reset_action_on_fail() {
DCHECK(clean_variable_ == nullptr);
clean_action_ = nullptr;
}
void AddConstraint(Constraint* const c) {
to_add_.push_back(c);
ProcessConstraints();
}
void ProcessConstraints() {
if (!in_add_) {
in_add_ = true;
// We cannot store to_add_.size() as constraints can add other
// constraints. For the same reason a range-based for loop cannot be used.
// TODO(user): Make to_add_ a queue to make the behavior more obvious.
for (int counter = 0; counter < to_add_.size(); ++counter) {
Constraint* const constraint = to_add_[counter];
// TODO(user): Add profiling to initial propagation
constraint->PostAndPropagate();
}
in_add_ = false;
to_add_.clear();
}
}
private:
Solver* const solver_;
std::deque<Demon*> var_queue_;
std::deque<Demon*> delayed_queue_;
uint64_t stamp_;
// The number of nested freeze levels. The queue is frozen if and only if
// freeze_level_ > 0.
uint32_t freeze_level_;
bool in_process_;
Solver::Action clean_action_;
IntVar* clean_variable_;
std::vector<Constraint*> to_add_;
bool in_add_;
const bool instruments_demons_;
};
// ------------------ StateMarker / StateInfo struct -----------
struct StateInfo { // This is an internal structure to store
// additional information on the choice point.
public:
StateInfo()
: ptr_info(nullptr),
int_info(0),
depth(0),
left_depth(0),
reversible_action(nullptr) {}
StateInfo(void* pinfo, int iinfo)
: ptr_info(pinfo),
int_info(iinfo),
depth(0),
left_depth(0),
reversible_action(nullptr) {}
StateInfo(void* pinfo, int iinfo, int d, int ld)
: ptr_info(pinfo),
int_info(iinfo),
depth(d),
left_depth(ld),
reversible_action(nullptr) {}
StateInfo(Solver::Action a, bool fast)
: ptr_info(nullptr),
int_info(static_cast<int>(fast)),
depth(0),
left_depth(0),
reversible_action(std::move(a)) {}
void* ptr_info;
int int_info;
int depth;
int left_depth;
Solver::Action reversible_action;
};
struct StateMarker {
public:
StateMarker(Solver::MarkerType t, const StateInfo& info);
friend class Solver;
friend struct Trail;
private:
Solver::MarkerType type_;
int rev_int_index_;
int rev_int64_index_;
int rev_uint64_index_;
int rev_double_index_;
int rev_ptr_index_;
int rev_boolvar_list_index_;
int rev_bools_index_;
int rev_int_memory_index_;
int rev_int64_memory_index_;
int rev_double_memory_index_;
int rev_object_memory_index_;
int rev_object_array_memory_index_;
int rev_memory_index_;
int rev_memory_array_index_;
StateInfo info_;
};
StateMarker::StateMarker(Solver::MarkerType t, const StateInfo& info)
: type_(t),
rev_int_index_(0),
rev_int64_index_(0),
rev_uint64_index_(0),
rev_double_index_(0),
rev_ptr_index_(0),
rev_boolvar_list_index_(0),
rev_bools_index_(0),
rev_int_memory_index_(0),
rev_int64_memory_index_(0),
rev_double_memory_index_(0),
rev_object_memory_index_(0),
rev_object_array_memory_index_(0),
info_(info) {}
// ---------- Trail and Reversibility ----------
namespace {
// ----- addrval struct -----
// This template class is used internally to implement reversibility.
// It stores an address and the value that was at the address.
template <class T>
struct addrval {
public:
addrval() : address_(nullptr) {}
explicit addrval(T* adr) : address_(adr), old_value_(*adr) {}
void restore() const { (*address_) = old_value_; }
private:
T* address_;
T old_value_;
};
// ----- Compressed trail -----
// ---------- Trail Packer ---------
// Abstract class to pack trail blocks.
template <class T>
class TrailPacker {
public:
explicit TrailPacker(int block_size) : block_size_(block_size) {}
// This type is neither copyable nor movable.
TrailPacker(const TrailPacker&) = delete;
TrailPacker& operator=(const TrailPacker&) = delete;
virtual ~TrailPacker() {}
int input_size() const { return block_size_ * sizeof(addrval<T>); }
virtual void Pack(const addrval<T>* block, std::string* packed_block) = 0;
virtual void Unpack(const std::string& packed_block, addrval<T>* block) = 0;
private:
const int block_size_;
};
template <class T>
class NoCompressionTrailPacker : public TrailPacker<T> {
public:
explicit NoCompressionTrailPacker(int block_size)
: TrailPacker<T>(block_size) {}
// This type is neither copyable nor movable.
NoCompressionTrailPacker(const NoCompressionTrailPacker&) = delete;
NoCompressionTrailPacker& operator=(const NoCompressionTrailPacker&) = delete;
~NoCompressionTrailPacker() override {}
void Pack(const addrval<T>* block, std::string* packed_block) override {
DCHECK(block != nullptr);
DCHECK(packed_block != nullptr);
absl::string_view block_str(reinterpret_cast<const char*>(block),
this->input_size());
packed_block->assign(block_str.data(), block_str.size());
}
void Unpack(const std::string& packed_block, addrval<T>* block) override {
DCHECK(block != nullptr);
memcpy(block, packed_block.c_str(), packed_block.size());
}
};
template <class T>
class ZlibTrailPacker : public TrailPacker<T> {
public:
explicit ZlibTrailPacker(int block_size)
: TrailPacker<T>(block_size),
tmp_size_(compressBound(this->input_size())),
tmp_block_(new char[tmp_size_]) {}
// This type is neither copyable nor movable.
ZlibTrailPacker(const ZlibTrailPacker&) = delete;
ZlibTrailPacker& operator=(const ZlibTrailPacker&) = delete;
~ZlibTrailPacker() override {}
void Pack(const addrval<T>* block, std::string* packed_block) override {
DCHECK(block != nullptr);
DCHECK(packed_block != nullptr);
uLongf size = tmp_size_;
const int result =
compress(reinterpret_cast<Bytef*>(tmp_block_.get()), &size,
reinterpret_cast<const Bytef*>(block), this->input_size());
CHECK_EQ(Z_OK, result);
absl::string_view block_str;
block_str = absl::string_view(tmp_block_.get(), size);
packed_block->assign(block_str.data(), block_str.size());
}
void Unpack(const std::string& packed_block, addrval<T>* block) override {
DCHECK(block != nullptr);
uLongf size = this->input_size();
const int result =
uncompress(reinterpret_cast<Bytef*>(block), &size,
reinterpret_cast<const Bytef*>(packed_block.c_str()),
packed_block.size());
CHECK_EQ(Z_OK, result);
}
private:
const uint64_t tmp_size_;
std::unique_ptr<char[]> tmp_block_;
};
template <class T>
class CompressedTrail {
public:
CompressedTrail(
int block_size,
ConstraintSolverParameters::TrailCompression compression_level)
: block_size_(block_size),
blocks_(nullptr),
free_blocks_(nullptr),
data_(new addrval<T>[block_size]),
buffer_(new addrval<T>[block_size]),
buffer_used_(false),
current_(0),
size_(0) {
switch (compression_level) {
case ConstraintSolverParameters::NO_COMPRESSION: {
packer_.reset(new NoCompressionTrailPacker<T>(block_size));
break;
}
case ConstraintSolverParameters::COMPRESS_WITH_ZLIB: {
packer_.reset(new ZlibTrailPacker<T>(block_size));
break;
}
default: {
LOG(ERROR) << "Should not be here";
}
}
// We zero all memory used by addrval arrays.
// Because of padding, all bytes may not be initialized, while compression
// will read them all, even if the uninitialized bytes are never used.
// This makes valgrind happy.
memset(data_.get(), 0, sizeof(*data_.get()) * block_size);
memset(buffer_.get(), 0, sizeof(*buffer_.get()) * block_size);
}
~CompressedTrail() {
FreeBlocks(blocks_);
FreeBlocks(free_blocks_);
}
const addrval<T>& Back() const {
// Back of empty trail.
DCHECK_GT(current_, 0);
return data_[current_ - 1];
}
void PopBack() {
if (size_ > 0) {
--current_;
if (current_ <= 0) {
if (buffer_used_) {
data_.swap(buffer_);
current_ = block_size_;
buffer_used_ = false;
} else if (blocks_ != nullptr) {
packer_->Unpack(blocks_->compressed, data_.get());
FreeTopBlock();
current_ = block_size_;
}
}
--size_;
}
}
void PushBack(const addrval<T>& addr_val) {
if (current_ >= block_size_) {
if (buffer_used_) { // Buffer is used.
NewTopBlock();
packer_->Pack(buffer_.get(), &blocks_->compressed);
// O(1) operation.
data_.swap(buffer_);
} else {
data_.swap(buffer_);
buffer_used_ = true;
}
current_ = 0;
}
data_[current_] = addr_val;
++current_;
++size_;
}
int64_t size() const { return size_; }
private:
struct Block {
std::string compressed;
Block* next;
};
void FreeTopBlock() {
Block* block = blocks_;
blocks_ = block->next;
block->compressed.clear();
block->next = free_blocks_;
free_blocks_ = block;
}
void NewTopBlock() {
Block* block = nullptr;
if (free_blocks_ != nullptr) {
block = free_blocks_;
free_blocks_ = block->next;
} else {
block = new Block;
}
block->next = blocks_;
blocks_ = block;
}
void FreeBlocks(Block* blocks) {
while (nullptr != blocks) {
Block* next = blocks->next;
delete blocks;
blocks = next;
}
}
std::unique_ptr<TrailPacker<T>> packer_;
const int block_size_;
Block* blocks_;
Block* free_blocks_;
std::unique_ptr<addrval<T>[]> data_;
std::unique_ptr<addrval<T>[]> buffer_;
bool buffer_used_;
int current_;
int size_;
};
} // namespace
// ----- Trail -----
// Object are explicitly copied using the copy ctor instead of
// passing and storing a pointer. As objects are small, copying is
// much faster than allocating (around 35% on a complete solve).
extern void RestoreBoolValue(IntVar* var);
struct Trail {
CompressedTrail<int> rev_ints_;
CompressedTrail<int64_t> rev_int64s_;
CompressedTrail<uint64_t> rev_uint64s_;
CompressedTrail<double> rev_doubles_;
CompressedTrail<void*> rev_ptrs_;
std::vector<IntVar*> rev_boolvar_list_;
std::vector<bool*> rev_bools_;
std::vector<bool> rev_bool_value_;
std::vector<int*> rev_int_memory_;
std::vector<int64_t*> rev_int64_memory_;
std::vector<double*> rev_double_memory_;
std::vector<BaseObject*> rev_object_memory_;
std::vector<BaseObject**> rev_object_array_memory_;
std::vector<void*> rev_memory_;
std::vector<void**> rev_memory_array_;
Trail(int block_size,
ConstraintSolverParameters::TrailCompression compression_level)
: rev_ints_(block_size, compression_level),
rev_int64s_(block_size, compression_level),
rev_uint64s_(block_size, compression_level),
rev_doubles_(block_size, compression_level),
rev_ptrs_(block_size, compression_level) {}
void BacktrackTo(StateMarker* m) {
int target = m->rev_int_index_;
for (int curr = rev_ints_.size(); curr > target; --curr) {
const addrval<int>& cell = rev_ints_.Back();
cell.restore();
rev_ints_.PopBack();
}
DCHECK_EQ(rev_ints_.size(), target);
// Incorrect trail size after backtrack.
target = m->rev_int64_index_;
for (int curr = rev_int64s_.size(); curr > target; --curr) {
const addrval<int64_t>& cell = rev_int64s_.Back();
cell.restore();
rev_int64s_.PopBack();
}
DCHECK_EQ(rev_int64s_.size(), target);
// Incorrect trail size after backtrack.
target = m->rev_uint64_index_;
for (int curr = rev_uint64s_.size(); curr > target; --curr) {
const addrval<uint64_t>& cell = rev_uint64s_.Back();
cell.restore();
rev_uint64s_.PopBack();
}
DCHECK_EQ(rev_uint64s_.size(), target);
// Incorrect trail size after backtrack.
target = m->rev_double_index_;
for (int curr = rev_doubles_.size(); curr > target; --curr) {
const addrval<double>& cell = rev_doubles_.Back();
cell.restore();
rev_doubles_.PopBack();
}
DCHECK_EQ(rev_doubles_.size(), target);
// Incorrect trail size after backtrack.
target = m->rev_ptr_index_;
for (int curr = rev_ptrs_.size(); curr > target; --curr) {
const addrval<void*>& cell = rev_ptrs_.Back();
cell.restore();
rev_ptrs_.PopBack();
}
DCHECK_EQ(rev_ptrs_.size(), target);
// Incorrect trail size after backtrack.
target = m->rev_boolvar_list_index_;
for (int curr = rev_boolvar_list_.size() - 1; curr >= target; --curr) {
IntVar* const var = rev_boolvar_list_[curr];
RestoreBoolValue(var);
}
rev_boolvar_list_.resize(target);
DCHECK_EQ(rev_bools_.size(), rev_bool_value_.size());
target = m->rev_bools_index_;
for (int curr = rev_bools_.size() - 1; curr >= target; --curr) {
*(rev_bools_[curr]) = rev_bool_value_[curr];
}
rev_bools_.resize(target);
rev_bool_value_.resize(target);
target = m->rev_int_memory_index_;
for (int curr = rev_int_memory_.size() - 1; curr >= target; --curr) {
delete[] rev_int_memory_[curr];
}
rev_int_memory_.resize(target);
target = m->rev_int64_memory_index_;
for (int curr = rev_int64_memory_.size() - 1; curr >= target; --curr) {
delete[] rev_int64_memory_[curr];
}
rev_int64_memory_.resize(target);
target = m->rev_double_memory_index_;
for (int curr = rev_double_memory_.size() - 1; curr >= target; --curr) {
delete[] rev_double_memory_[curr];
}
rev_double_memory_.resize(target);
target = m->rev_object_memory_index_;
for (int curr = rev_object_memory_.size() - 1; curr >= target; --curr) {
delete rev_object_memory_[curr];
}
rev_object_memory_.resize(target);
target = m->rev_object_array_memory_index_;
for (int curr = rev_object_array_memory_.size() - 1; curr >= target;
--curr) {
delete[] rev_object_array_memory_[curr];
}
rev_object_array_memory_.resize(target);
target = m->rev_memory_index_;
for (int curr = rev_memory_.size() - 1; curr >= target; --curr) {
// Explicitly call unsized delete
::operator delete(reinterpret_cast<char*>(rev_memory_[curr]));
// The previous cast is necessary to deallocate generic memory
// described by a void* when passed to the RevAlloc procedure
// We cannot do a delete[] there
// This is useful for cells of RevFIFO and should not be used outside
// of the product
}
rev_memory_.resize(target);
target = m->rev_memory_array_index_;
for (int curr = rev_memory_array_.size() - 1; curr >= target; --curr) {
delete[] rev_memory_array_[curr];
// delete [] version of the previous unsafe case.
}
rev_memory_array_.resize(target);
}
};
void Solver::InternalSaveValue(int* valptr) {
trail_->rev_ints_.PushBack(addrval<int>(valptr));
}
void Solver::InternalSaveValue(int64_t* valptr) {
trail_->rev_int64s_.PushBack(addrval<int64_t>(valptr));
}
void Solver::InternalSaveValue(uint64_t* valptr) {
trail_->rev_uint64s_.PushBack(addrval<uint64_t>(valptr));
}
void Solver::InternalSaveValue(double* valptr) {
trail_->rev_doubles_.PushBack(addrval<double>(valptr));
}
void Solver::InternalSaveValue(void** valptr) {
trail_->rev_ptrs_.PushBack(addrval<void*>(valptr));
}
// TODO(user) : this code is unsafe if you save the same alternating
// bool multiple times.
// The correct code should use a bitset and a single list.
void Solver::InternalSaveValue(bool* valptr) {
trail_->rev_bools_.push_back(valptr);
trail_->rev_bool_value_.push_back(*valptr);
}
BaseObject* Solver::SafeRevAlloc(BaseObject* ptr) {
check_alloc_state();
trail_->rev_object_memory_.push_back(ptr);
return ptr;
}
int* Solver::SafeRevAllocArray(int* ptr) {
check_alloc_state();
trail_->rev_int_memory_.push_back(ptr);
return ptr;
}
int64_t* Solver::SafeRevAllocArray(int64_t* ptr) {
check_alloc_state();
trail_->rev_int64_memory_.push_back(ptr);
return ptr;
}
double* Solver::SafeRevAllocArray(double* ptr) {
check_alloc_state();
trail_->rev_double_memory_.push_back(ptr);
return ptr;
}
uint64_t* Solver::SafeRevAllocArray(uint64_t* ptr) {
check_alloc_state();
trail_->rev_int64_memory_.push_back(reinterpret_cast<int64_t*>(ptr));
return ptr;
}
BaseObject** Solver::SafeRevAllocArray(BaseObject** ptr) {
check_alloc_state();
trail_->rev_object_array_memory_.push_back(ptr);
return ptr;
}
IntVar** Solver::SafeRevAllocArray(IntVar** ptr) {
BaseObject** in = SafeRevAllocArray(reinterpret_cast<BaseObject**>(ptr));
return reinterpret_cast<IntVar**>(in);
}
IntExpr** Solver::SafeRevAllocArray(IntExpr** ptr) {
BaseObject** in = SafeRevAllocArray(reinterpret_cast<BaseObject**>(ptr));
return reinterpret_cast<IntExpr**>(in);
}
Constraint** Solver::SafeRevAllocArray(Constraint** ptr) {
BaseObject** in = SafeRevAllocArray(reinterpret_cast<BaseObject**>(ptr));
return reinterpret_cast<Constraint**>(in);
}
void* Solver::UnsafeRevAllocAux(void* ptr) {
check_alloc_state();
trail_->rev_memory_.push_back(ptr);
return ptr;
}
void** Solver::UnsafeRevAllocArrayAux(void** ptr) {
check_alloc_state();
trail_->rev_memory_array_.push_back(ptr);
return ptr;
}
void InternalSaveBooleanVarValue(Solver* const solver, IntVar* const var) {
solver->trail_->rev_boolvar_list_.push_back(var);
}
// ------------------ Search class -----------------
class Search {
public:
explicit Search(Solver* const s)
: solver_(s),
marker_stack_(),
monitor_event_listeners_(to_underlying(Solver::MonitorEvent::kLast)),
fail_buffer_(),
solution_counter_(0),
unchecked_solution_counter_(0),
decision_builder_(nullptr),
created_by_solve_(false),
search_depth_(0),
left_search_depth_(0),
should_restart_(false),
should_finish_(false),
sentinel_pushed_(0),
jmpbuf_filled_(false),
backtrack_at_the_end_of_the_search_(true) {}
// Constructor for a dummy search. The only difference between a dummy search
// and a regular one is that the search depth and left search depth is
// initialized to -1 instead of zero.
Search(Solver* const s, int /* dummy_argument */)
: solver_(s),
marker_stack_(),
monitor_event_listeners_(to_underlying(Solver::MonitorEvent::kLast)),
fail_buffer_(),
solution_counter_(0),
unchecked_solution_counter_(0),
decision_builder_(nullptr),