Fix typo
[c11tester.git] / funcnode.cc
1 #include "action.h"
2 #include "history.h"
3 #include "funcnode.h"
4 #include "funcinst.h"
5 #include "predicate.h"
6 #include "concretepredicate.h"
7
8 #include "model.h"
9 #include <cmath>
10
11 FuncNode::FuncNode(ModelHistory * history) :
12         history(history),
13         exit_count(0),
14         marker(1),
15         func_inst_map(),
16         inst_list(),
17         entry_insts(),
18         inst_pred_map(128),
19         inst_id_map(128),
20         loc_act_map(128),
21         predicate_tree_position(),
22         predicate_leaves(),
23         leaves_tmp_storage(),
24         weight_debug_vec(),
25         failed_predicates(),
26         edge_table(32),
27         out_edges()
28 {
29         predicate_tree_entry = new Predicate(NULL, true);
30         predicate_tree_entry->add_predicate_expr(NOPREDICATE, NULL, true);
31
32         predicate_tree_exit = new Predicate(NULL, false, true);
33         predicate_tree_exit->set_depth(MAX_DEPTH);
34
35         /* Snapshot data structures below */
36         action_list_buffer = new SnapList<action_list_t *>();
37         read_locations = new loc_set_t();
38         write_locations = new loc_set_t();
39         val_loc_map = new HashTable<uint64_t, loc_set_t *, uint64_t, 0, snapshot_malloc, snapshot_calloc, snapshot_free, int64_hash>();
40         loc_may_equal_map = new HashTable<void *, loc_set_t *, uintptr_t, 0>();
41
42         //values_may_read_from = new value_set_t();
43 }
44
45 /* Reallocate snapshotted memories when new executions start */
46 void FuncNode::set_new_exec_flag()
47 {
48         action_list_buffer = new SnapList<action_list_t *>();
49         read_locations = new loc_set_t();
50         write_locations = new loc_set_t();
51         val_loc_map = new HashTable<uint64_t, loc_set_t *, uint64_t, 0, snapshot_malloc, snapshot_calloc, snapshot_free, int64_hash>();
52         loc_may_equal_map = new HashTable<void *, loc_set_t *, uintptr_t, 0>();
53
54         //values_may_read_from = new value_set_t();
55 }
56
57 /* Check whether FuncInst with the same type, position, and location
58  * as act has been added to func_inst_map or not. If not, add it.
59  */
60 void FuncNode::add_inst(ModelAction *act)
61 {
62         ASSERT(act);
63         const char * position = act->get_position();
64
65         /* THREAD* actions, ATOMIC_LOCK, ATOMIC_TRYLOCK, and ATOMIC_UNLOCK
66          * actions are not tagged with their source line numbers
67          */
68         if (position == NULL)
69                 return;
70
71         FuncInst * func_inst = func_inst_map.get(position);
72
73         /* This position has not been inserted into hashtable before */
74         if (func_inst == NULL) {
75                 func_inst = create_new_inst(act);
76                 func_inst_map.put(position, func_inst);
77                 return;
78         }
79
80         /* Volatile variables that use ++ or -- syntax may result in read and write actions with the same position */
81         if (func_inst->get_type() != act->get_type()) {
82                 FuncInst * collision_inst = func_inst->search_in_collision(act);
83
84                 if (collision_inst == NULL) {
85                         collision_inst = create_new_inst(act);
86                         func_inst->add_to_collision(collision_inst);
87                         return;
88                 } else {
89                         func_inst = collision_inst;
90                 }
91         }
92
93         ASSERT(func_inst->get_type() == act->get_type());
94         int curr_execution_number = model->get_execution_number();
95
96         /* Reset locations when new executions start */
97         if (func_inst->get_execution_number() != curr_execution_number) {
98                 func_inst->set_location(act->get_location());
99                 func_inst->set_execution_number(curr_execution_number);
100         }
101
102         /* Mark the memory location of such inst as not unique */
103         if (func_inst->get_location() != act->get_location())
104                 func_inst->not_single_location();
105 }
106
107 FuncInst * FuncNode::create_new_inst(ModelAction * act)
108 {
109         FuncInst * func_inst = new FuncInst(act, this);
110         int exec_num = model->get_execution_number();
111         func_inst->set_execution_number(exec_num);
112
113         inst_list.push_back(func_inst);
114
115         return func_inst;
116 }
117
118
119 /* Get the FuncInst with the same type, position, and location
120  * as act
121  *
122  * @return FuncInst with the same type, position, and location as act */
123 FuncInst * FuncNode::get_inst(ModelAction *act)
124 {
125         ASSERT(act);
126         const char * position = act->get_position();
127
128         /* THREAD* actions, ATOMIC_LOCK, ATOMIC_TRYLOCK, and ATOMIC_UNLOCK
129          * actions are not tagged with their source line numbers
130          */
131         if (position == NULL)
132                 return NULL;
133
134         FuncInst * inst = func_inst_map.get(position);
135         if (inst == NULL)
136                 return NULL;
137
138         action_type inst_type = inst->get_type();
139         action_type act_type = act->get_type();
140
141         if (inst_type == act_type) {
142                 return inst;
143         }
144         /* RMWRCAS actions are converted to RMW or READ actions */
145         else if (inst_type == ATOMIC_RMWRCAS &&
146                                          (act_type == ATOMIC_RMW || act_type == ATOMIC_READ)) {
147                 return inst;
148         }
149         /* Return the FuncInst in the collision list */
150         else {
151                 return inst->search_in_collision(act);
152         }
153 }
154
155
156 void FuncNode::add_entry_inst(FuncInst * inst)
157 {
158         if (inst == NULL)
159                 return;
160
161         mllnode<FuncInst *> * it;
162         for (it = entry_insts.begin();it != NULL;it = it->getNext()) {
163                 if (inst == it->getVal())
164                         return;
165         }
166
167         entry_insts.push_back(inst);
168 }
169
170 /**
171  * @brief Convert ModelAdtion list to FuncInst list
172  * @param act_list A list of ModelActions
173  */
174 void FuncNode::update_tree(action_list_t * act_list)
175 {
176         if (act_list == NULL || act_list->size() == 0)
177                 return;
178
179         HashTable<void *, value_set_t *, uintptr_t, 0> * write_history = history->getWriteHistory();
180         HashSet<ModelAction *, uintptr_t, 2> write_actions;
181
182         /* build inst_list from act_list for later processing */
183         func_inst_list_t inst_list;
184         action_list_t rw_act_list;
185
186         for (sllnode<ModelAction *> * it = act_list->begin();it != NULL;it = it->getNext()) {
187                 ModelAction * act = it->getVal();
188
189                 // Use the original action type and decrement ref count
190                 // so that actions may be deleted by Execution::collectActions
191                 if (act->get_original_type() != ATOMIC_NOP && act->get_swap_flag() == false)
192                         act->use_original_type();
193
194                 act->decr_func_ref_count();
195
196                 if (act->is_read()) {
197                         // For every read or rmw actions in this list, the reads_from was marked, and not deleted.
198                         // So it is safe to call get_reads_from
199                         ModelAction * rf = act->get_reads_from();
200                         if (rf->get_original_type() != ATOMIC_NOP && rf->get_swap_flag() == false)
201                                 rf->use_original_type();
202
203                         rf->decr_func_ref_count();
204                 }
205
206                 FuncInst * func_inst = get_inst(act);
207                 void * loc = act->get_location();
208
209                 if (func_inst == NULL)
210                         continue;
211
212                 inst_list.push_back(func_inst);
213                 bool act_added = false;
214
215                 if (act->is_write()) {
216                         rw_act_list.push_back(act);
217                         act_added = true;
218                         if (!write_locations->contains(loc)) {
219                                 write_locations->add(loc);
220                                 history->update_loc_wr_func_nodes_map(loc, this);
221                         }
222                 }
223
224                 if (act->is_read()) {
225                         if (!act_added)
226                                 rw_act_list.push_back(act);
227
228                         /* If func_inst may only read_from a single location, then:
229                          *
230                          * The first time an action reads from some location,
231                          * import all the values that have been written to this
232                          * location from ModelHistory and notify ModelHistory
233                          * that this FuncNode may read from this location.
234                          */
235                         if (!read_locations->contains(loc) && func_inst->is_single_location()) {
236                                 read_locations->add(loc);
237                                 value_set_t * write_values = write_history->get(loc);
238                                 add_to_val_loc_map(write_values, loc);
239                                 history->update_loc_rd_func_nodes_map(loc, this);
240                         }
241                 }
242         }
243
244         update_inst_tree(&inst_list);
245         update_predicate_tree(&rw_act_list);
246
247         // Revert back action types and free
248         for (sllnode<ModelAction *> * it = act_list->begin(); it != NULL;) {
249                 ModelAction * act = it->getVal();
250                 // Do iteration early in case we delete read actions
251                 it = it->getNext();
252
253                 // Collect write actions and reads_froms
254                 if (act->is_read()) {
255                         if (act->is_rmw()) {
256                                 write_actions.add(act);
257                         }
258
259                         ModelAction * rf = act->get_reads_from();
260                         write_actions.add(rf);
261                 } else if (act->is_write()) {
262                         write_actions.add(act);
263                 }
264
265                 // Revert back action types
266                 if (act->is_read()) {
267                         ModelAction * rf = act->get_reads_from();
268                         if (rf->get_swap_flag() == true)
269                                 rf->use_original_type();
270                 }
271
272                 if (act->get_swap_flag() == true)
273                         act->use_original_type();
274
275                 //  Free read actions
276                 if (act->is_read()) {
277                         if (act->is_rmw()) {
278                                 // Do nothing. Its reads_from can not be READY_FREE
279                         } else {
280                                 ModelAction *rf = act->get_reads_from();
281                                 if (rf->is_free()) {
282                                         model_print("delete read %d; %p\n", act->get_seq_number(), act);
283                                         delete act;
284                                 }
285                         }
286                 }
287         }
288
289         // Free write actions if possible
290         HSIterator<ModelAction *, uintptr_t, 2> * it = write_actions.iterator();
291         while (it->hasNext()) {
292                 ModelAction * act = it->next();
293
294                 if (act->is_free() && act->get_func_ref_count() == 0)
295                         delete act;
296         }
297         delete it;
298
299 //      print_predicate_tree();
300 }
301
302 /**
303  * @brief Link FuncInsts in inst_list  - add one FuncInst to another's predecessors and successors
304  * @param inst_list A list of FuncInsts
305  */
306 void FuncNode::update_inst_tree(func_inst_list_t * inst_list)
307 {
308         if (inst_list == NULL)
309                 return;
310         else if (inst_list->size() == 0)
311                 return;
312
313         /* start linking */
314         sllnode<FuncInst *>* it = inst_list->begin();
315         sllnode<FuncInst *>* prev;
316
317         /* add the first instruction to the list of entry insts */
318         FuncInst * entry_inst = it->getVal();
319         add_entry_inst(entry_inst);
320
321         it = it->getNext();
322         while (it != NULL) {
323                 prev = it->getPrev();
324
325                 FuncInst * prev_inst = prev->getVal();
326                 FuncInst * curr_inst = it->getVal();
327
328                 prev_inst->add_succ(curr_inst);
329                 curr_inst->add_pred(prev_inst);
330
331                 it = it->getNext();
332         }
333 }
334
335 void FuncNode::update_predicate_tree(action_list_t * act_list)
336 {
337         if (act_list == NULL || act_list->size() == 0)
338                 return;
339
340         incr_marker();
341         uint32_t inst_counter = 0;
342
343         // Clear hashtables
344         loc_act_map.reset();
345         inst_pred_map.reset();
346         inst_id_map.reset();
347
348         // Clear the set of leaves encountered in this path
349         leaves_tmp_storage.clear();
350
351         sllnode<ModelAction *> *it = act_list->begin();
352         Predicate * curr_pred = predicate_tree_entry;
353         while (it != NULL) {
354                 ModelAction * next_act = it->getVal();
355                 FuncInst * next_inst = get_inst(next_act);
356                 next_inst->set_associated_act(next_act, marker);
357
358                 Predicate * unset_predicate = NULL;
359                 bool branch_found = follow_branch(&curr_pred, next_inst, next_act, &unset_predicate);
360
361                 // A branch with unset predicate expression is detected
362                 if (!branch_found && unset_predicate != NULL) {
363                         bool amended = amend_predicate_expr(curr_pred, next_inst, next_act);
364                         if (amended)
365                                 continue;
366                         else {
367                                 curr_pred = unset_predicate;
368                                 branch_found = true;
369                         }
370                 }
371
372                 // Detect loops
373                 if (!branch_found && inst_id_map.contains(next_inst)) {
374                         FuncInst * curr_inst = curr_pred->get_func_inst();
375                         uint32_t curr_id = inst_id_map.get(curr_inst);
376                         uint32_t next_id = inst_id_map.get(next_inst);
377
378                         if (curr_id >= next_id) {
379                                 Predicate * old_pred = inst_pred_map.get(next_inst);
380                                 Predicate * back_pred = old_pred->get_parent();
381
382                                 // For updating weights
383                                 leaves_tmp_storage.push_back(curr_pred);
384
385                                 // Add to the set of backedges
386                                 curr_pred->add_backedge(back_pred);
387                                 curr_pred = back_pred;
388                                 continue;
389                         }
390                 }
391
392                 // Generate new branches
393                 if (!branch_found) {
394                         SnapVector<struct half_pred_expr *> half_pred_expressions;
395                         infer_predicates(next_inst, next_act, &half_pred_expressions);
396                         generate_predicates(curr_pred, next_inst, &half_pred_expressions);
397                         continue;
398                 }
399
400                 if (next_act->is_write())
401                         curr_pred->set_write(true);
402
403                 if (next_act->is_read()) {
404                         /* Only need to store the locations of read actions */
405                         loc_act_map.put(next_act->get_location(), next_act);
406                 }
407
408                 inst_pred_map.put(next_inst, curr_pred);
409                 if (!inst_id_map.contains(next_inst))
410                         inst_id_map.put(next_inst, inst_counter++);
411
412                 it = it->getNext();
413                 curr_pred->incr_expl_count();
414         }
415
416         if (curr_pred->get_exit() == NULL) {
417                 // Exit predicate is unset yet
418                 curr_pred->set_exit(predicate_tree_exit);
419         }
420
421         leaves_tmp_storage.push_back(curr_pred);
422         update_predicate_tree_weight();
423 }
424
425 /* Given curr_pred and next_inst, find the branch following curr_pred that
426  * contains next_inst and the correct predicate.
427  * @return true if branch found, false otherwise.
428  */
429 bool FuncNode::follow_branch(Predicate ** curr_pred, FuncInst * next_inst,
430                                                                                                                  ModelAction * next_act, Predicate ** unset_predicate)
431 {
432         /* Check if a branch with func_inst and corresponding predicate exists */
433         bool branch_found = false;
434         ModelVector<Predicate *> * branches = (*curr_pred)->get_children();
435         for (uint i = 0;i < branches->size();i++) {
436                 Predicate * branch = (*branches)[i];
437                 if (branch->get_func_inst() != next_inst)
438                         continue;
439
440                 /* Check against predicate expressions */
441                 bool predicate_correct = true;
442                 PredExprSet * pred_expressions = branch->get_pred_expressions();
443
444                 /* Only read and rmw actions my have unset predicate expressions */
445                 if (pred_expressions->getSize() == 0) {
446                         predicate_correct = false;
447                         if (*unset_predicate == NULL)
448                                 *unset_predicate = branch;
449                         else
450                                 ASSERT(false);
451
452                         continue;
453                 }
454
455                 PredExprSetIter * pred_expr_it = pred_expressions->iterator();
456                 while (pred_expr_it->hasNext()) {
457                         pred_expr * pred_expression = pred_expr_it->next();
458                         uint64_t last_read, next_read;
459                         bool equality;
460
461                         switch(pred_expression->token) {
462                         case NOPREDICATE:
463                                 predicate_correct = true;
464                                 break;
465                         case EQUALITY:
466                                 FuncInst * to_be_compared;
467                                 ModelAction * last_act;
468
469                                 to_be_compared = pred_expression->func_inst;
470                                 last_act = to_be_compared->get_associated_act(marker);
471
472                                 last_read = last_act->get_reads_from_value();
473                                 next_read = next_act->get_reads_from_value();
474                                 equality = (last_read == next_read);
475                                 if (equality != pred_expression->value)
476                                         predicate_correct = false;
477
478                                 break;
479                         case NULLITY:
480                                 next_read = next_act->get_reads_from_value();
481                                 // TODO: implement likely to be null
482                                 equality = ( (void*) (next_read & 0xffffffff) == NULL);
483                                 if (equality != pred_expression->value)
484                                         predicate_correct = false;
485                                 break;
486                         default:
487                                 predicate_correct = false;
488                                 model_print("unkown predicate token\n");
489                                 break;
490                         }
491                 }
492
493                 delete pred_expr_it;
494
495                 if (predicate_correct) {
496                         *curr_pred = branch;
497                         branch_found = true;
498                         break;
499                 }
500         }
501
502         return branch_found;
503 }
504
505 /* Infer predicate expressions, which are generated in FuncNode::generate_predicates */
506 void FuncNode::infer_predicates(FuncInst * next_inst, ModelAction * next_act,
507                                                                                                                                 SnapVector<struct half_pred_expr *> * half_pred_expressions)
508 {
509         void * loc = next_act->get_location();
510
511         if (next_inst->is_read()) {
512                 /* read + rmw */
513                 if ( loc_act_map.contains(loc) ) {
514                         ModelAction * last_act = loc_act_map.get(loc);
515                         FuncInst * last_inst = get_inst(last_act);
516                         struct half_pred_expr * expression = new half_pred_expr(EQUALITY, last_inst);
517                         half_pred_expressions->push_back(expression);
518                 } else if ( next_inst->is_single_location() ) {
519                         loc_set_t * loc_may_equal = loc_may_equal_map->get(loc);
520
521                         if (loc_may_equal != NULL) {
522                                 loc_set_iter * loc_it = loc_may_equal->iterator();
523                                 while (loc_it->hasNext()) {
524                                         void * neighbor = loc_it->next();
525                                         if (loc_act_map.contains(neighbor)) {
526                                                 ModelAction * last_act = loc_act_map.get(neighbor);
527                                                 FuncInst * last_inst = get_inst(last_act);
528
529                                                 struct half_pred_expr * expression = new half_pred_expr(EQUALITY, last_inst);
530                                                 half_pred_expressions->push_back(expression);
531                                         }
532                                 }
533
534                                 delete loc_it;
535                         }
536                 } else {
537                         // next_inst is not single location
538                         uint64_t read_val = next_act->get_reads_from_value();
539
540                         // only infer NULLITY predicate when it is actually NULL.
541                         if ( (void*)read_val == NULL) {
542                                 struct half_pred_expr * expression = new half_pred_expr(NULLITY, NULL);
543                                 half_pred_expressions->push_back(expression);
544                         }
545                 }
546         } else {
547                 /* Pure writes */
548                 // TODO: do anything here?
549         }
550 }
551
552 /* Able to generate complex predicates when there are multiple predciate expressions */
553 void FuncNode::generate_predicates(Predicate * curr_pred, FuncInst * next_inst,
554                                                                                                                                          SnapVector<struct half_pred_expr *> * half_pred_expressions)
555 {
556         if (half_pred_expressions->size() == 0) {
557                 Predicate * new_pred = new Predicate(next_inst);
558                 curr_pred->add_child(new_pred);
559                 new_pred->set_parent(curr_pred);
560
561                 /* Maintain predicate leaves */
562                 predicate_leaves.add(new_pred);
563                 predicate_leaves.remove(curr_pred);
564
565                 /* entry predicates and predicates containing pure write actions
566                  * have no predicate expressions */
567                 if ( curr_pred->is_entry_predicate() )
568                         new_pred->add_predicate_expr(NOPREDICATE, NULL, true);
569                 else if (next_inst->is_write()) {
570                         /* next_inst->is_write() <==> pure writes */
571                         new_pred->add_predicate_expr(NOPREDICATE, NULL, true);
572                 }
573
574                 return;
575         }
576
577         SnapVector<Predicate *> predicates;
578
579         struct half_pred_expr * half_expr = (*half_pred_expressions)[0];
580         predicates.push_back(new Predicate(next_inst));
581         predicates.push_back(new Predicate(next_inst));
582
583         predicates[0]->add_predicate_expr(half_expr->token, half_expr->func_inst, true);
584         predicates[1]->add_predicate_expr(half_expr->token, half_expr->func_inst, false);
585
586         for (uint i = 1;i < half_pred_expressions->size();i++) {
587                 half_expr = (*half_pred_expressions)[i];
588
589                 uint old_size = predicates.size();
590                 for (uint j = 0;j < old_size;j++) {
591                         Predicate * pred = predicates[j];
592                         Predicate * new_pred = new Predicate(next_inst);
593                         new_pred->copy_predicate_expr(pred);
594
595                         pred->add_predicate_expr(half_expr->token, half_expr->func_inst, true);
596                         new_pred->add_predicate_expr(half_expr->token, half_expr->func_inst, false);
597
598                         predicates.push_back(new_pred);
599                 }
600         }
601
602         for (uint i = 0;i < predicates.size();i++) {
603                 Predicate * pred= predicates[i];
604                 curr_pred->add_child(pred);
605                 pred->set_parent(curr_pred);
606
607                 /* Add new predicate leaves */
608                 predicate_leaves.add(pred);
609         }
610
611         /* Remove predicate node that has children */
612         predicate_leaves.remove(curr_pred);
613
614         /* Free memories allocated by infer_predicate */
615         for (uint i = 0;i < half_pred_expressions->size();i++) {
616                 struct half_pred_expr * tmp = (*half_pred_expressions)[i];
617                 snapshot_free(tmp);
618         }
619 }
620
621 /* Amend predicates that contain no predicate expressions. Currenlty only amend with NULLITY predicates */
622 bool FuncNode::amend_predicate_expr(Predicate * curr_pred, FuncInst * next_inst, ModelAction * next_act)
623 {
624         ModelVector<Predicate *> * children = curr_pred->get_children();
625
626         Predicate * unset_pred = NULL;
627         for (uint i = 0;i < children->size();i++) {
628                 Predicate * child = (*children)[i];
629                 if (child->get_func_inst() == next_inst) {
630                         unset_pred = child;
631                         break;
632                 }
633         }
634
635         uint64_t read_val = next_act->get_reads_from_value();
636
637         // only generate NULLITY predicate when it is actually NULL.
638         if ( !next_inst->is_single_location() && (void*)read_val == NULL ) {
639                 Predicate * new_pred = new Predicate(next_inst);
640
641                 curr_pred->add_child(new_pred);
642                 new_pred->set_parent(curr_pred);
643
644                 unset_pred->add_predicate_expr(NULLITY, NULL, false);
645                 new_pred->add_predicate_expr(NULLITY, NULL, true);
646
647                 return true;
648         }
649
650         return false;
651 }
652
653 void FuncNode::add_to_val_loc_map(uint64_t val, void * loc)
654 {
655         loc_set_t * locations = val_loc_map->get(val);
656
657         if (locations == NULL) {
658                 locations = new loc_set_t();
659                 val_loc_map->put(val, locations);
660         }
661
662         update_loc_may_equal_map(loc, locations);
663         locations->add(loc);
664         // values_may_read_from->add(val);
665 }
666
667 void FuncNode::add_to_val_loc_map(value_set_t * values, void * loc)
668 {
669         if (values == NULL)
670                 return;
671
672         value_set_iter * it = values->iterator();
673         while (it->hasNext()) {
674                 uint64_t val = it->next();
675                 add_to_val_loc_map(val, loc);
676         }
677
678         delete it;
679 }
680
681 void FuncNode::update_loc_may_equal_map(void * new_loc, loc_set_t * old_locations)
682 {
683         if ( old_locations->contains(new_loc) )
684                 return;
685
686         loc_set_t * neighbors = loc_may_equal_map->get(new_loc);
687
688         if (neighbors == NULL) {
689                 neighbors = new loc_set_t();
690                 loc_may_equal_map->put(new_loc, neighbors);
691         }
692
693         loc_set_iter * loc_it = old_locations->iterator();
694         while (loc_it->hasNext()) {
695                 // new_loc: { old_locations, ... }
696                 void * member = loc_it->next();
697                 neighbors->add(member);
698
699                 // for each i in old_locations, i : { new_loc, ... }
700                 loc_set_t * _neighbors = loc_may_equal_map->get(member);
701                 if (_neighbors == NULL) {
702                         _neighbors = new loc_set_t();
703                         loc_may_equal_map->put(member, _neighbors);
704                 }
705                 _neighbors->add(new_loc);
706         }
707
708         delete loc_it;
709 }
710
711 /* Every time a thread enters a function, set its position to the predicate tree entry */
712 void FuncNode::init_predicate_tree_position(thread_id_t tid)
713 {
714         int thread_id = id_to_int(tid);
715         if (predicate_tree_position.size() <= (uint) thread_id)
716                 predicate_tree_position.resize(thread_id + 1);
717
718         predicate_tree_position[thread_id] = predicate_tree_entry;
719 }
720
721 void FuncNode::set_predicate_tree_position(thread_id_t tid, Predicate * pred)
722 {
723         int thread_id = id_to_int(tid);
724         predicate_tree_position[thread_id] = pred;
725 }
726
727 /* @return The position of a thread in a predicate tree */
728 Predicate * FuncNode::get_predicate_tree_position(thread_id_t tid)
729 {
730         int thread_id = id_to_int(tid);
731         return predicate_tree_position[thread_id];
732 }
733
734 /* Make sure elements of thrd_inst_act_map are initialized properly when threads enter functions */
735 void FuncNode::init_inst_act_map(thread_id_t tid)
736 {
737         int thread_id = id_to_int(tid);
738         SnapVector<inst_act_map_t *> * thrd_inst_act_map = history->getThrdInstActMap(func_id);
739         uint old_size = thrd_inst_act_map->size();
740
741         if (thrd_inst_act_map->size() <= (uint) thread_id) {
742                 uint new_size = thread_id + 1;
743                 thrd_inst_act_map->resize(new_size);
744
745                 for (uint i = old_size;i < new_size;i++)
746                         (*thrd_inst_act_map)[i] = new inst_act_map_t(128);
747         }
748 }
749
750 /* Reset elements of thrd_inst_act_map when threads exit functions */
751 void FuncNode::reset_inst_act_map(thread_id_t tid)
752 {
753         int thread_id = id_to_int(tid);
754         SnapVector<inst_act_map_t *> * thrd_inst_act_map = history->getThrdInstActMap(func_id);
755
756         inst_act_map_t * map = (*thrd_inst_act_map)[thread_id];
757         map->reset();
758 }
759
760 void FuncNode::update_inst_act_map(thread_id_t tid, ModelAction * read_act)
761 {
762         int thread_id = id_to_int(tid);
763         SnapVector<inst_act_map_t *> * thrd_inst_act_map = history->getThrdInstActMap(func_id);
764
765         inst_act_map_t * map = (*thrd_inst_act_map)[thread_id];
766         FuncInst * read_inst = get_inst(read_act);
767         map->put(read_inst, read_act);
768 }
769
770 inst_act_map_t * FuncNode::get_inst_act_map(thread_id_t tid)
771 {
772         int thread_id = id_to_int(tid);
773         SnapVector<inst_act_map_t *> * thrd_inst_act_map = history->getThrdInstActMap(func_id);
774
775         return (*thrd_inst_act_map)[thread_id];
776 }
777
778 /* Add FuncNodes that this node may follow */
779 void FuncNode::add_out_edge(FuncNode * other)
780 {
781         if ( !edge_table.contains(other) ) {
782                 edge_table.put(other, OUT_EDGE);
783                 out_edges.push_back(other);
784                 return;
785         }
786
787         edge_type_t edge = edge_table.get(other);
788         if (edge == IN_EDGE) {
789                 edge_table.put(other, BI_EDGE);
790                 out_edges.push_back(other);
791         }
792 }
793
794 /* Compute the distance between this FuncNode and the target node.
795  * Return -1 if the target node is unreachable or the actual distance
796  * is greater than max_step.
797  */
798 int FuncNode::compute_distance(FuncNode * target, int max_step)
799 {
800         if (target == NULL)
801                 return -1;
802         else if (target == this)
803                 return 0;
804
805         SnapList<FuncNode *> queue;
806         HashTable<FuncNode *, int, uintptr_t, 0> distances(128);
807
808         queue.push_back(this);
809         distances.put(this, 0);
810
811         while (!queue.empty()) {
812                 FuncNode * curr = queue.front();
813                 queue.pop_front();
814                 int dist = distances.get(curr);
815
816                 if (max_step <= dist)
817                         return -1;
818
819                 ModelList<FuncNode *> * outEdges = curr->get_out_edges();
820                 mllnode<FuncNode *> * it;
821                 for (it = outEdges->begin();it != NULL;it = it->getNext()) {
822                         FuncNode * out_node = it->getVal();
823
824                         /* This node has not been visited before */
825                         if ( !distances.contains(out_node) ) {
826                                 if (out_node == target)
827                                         return dist + 1;
828
829                                 queue.push_back(out_node);
830                                 distances.put(out_node, dist + 1);
831                         }
832                 }
833         }
834
835         /* Target node is unreachable */
836         return -1;
837 }
838
839 void FuncNode::add_failed_predicate(Predicate * pred)
840 {
841         failed_predicates.add(pred);
842 }
843
844 /* Implement quick sort to sort leaves before assigning base scores */
845 template<typename _Tp>
846 static int partition(ModelVector<_Tp *> * arr, int low, int high)
847 {
848         unsigned int pivot = (*arr)[high] -> get_depth();
849         int i = low - 1;
850
851         for (int j = low;j <= high - 1;j ++) {
852                 if ( (*arr)[j] -> get_depth() < pivot ) {
853                         i ++;
854                         _Tp * tmp = (*arr)[i];
855                         (*arr)[i] = (*arr)[j];
856                         (*arr)[j] = tmp;
857                 }
858         }
859
860         _Tp * tmp = (*arr)[i + 1];
861         (*arr)[i + 1] = (*arr)[high];
862         (*arr)[high] = tmp;
863
864         return i + 1;
865 }
866
867 /* Implement quick sort to sort leaves before assigning base scores */
868 template<typename _Tp>
869 static void quickSort(ModelVector<_Tp *> * arr, int low, int high)
870 {
871         if (low < high) {
872                 int pi = partition(arr, low, high);
873
874                 quickSort(arr, low, pi - 1);
875                 quickSort(arr, pi + 1, high);
876         }
877 }
878
879 void FuncNode::assign_initial_weight()
880 {
881         PredSetIter * it = predicate_leaves.iterator();
882         leaves_tmp_storage.clear();
883
884         while (it->hasNext()) {
885                 Predicate * pred = it->next();
886                 double weight = 100.0 / sqrt(pred->get_expl_count() + pred->get_fail_count() + 1);
887                 pred->set_weight(weight);
888                 leaves_tmp_storage.push_back(pred);
889         }
890         delete it;
891
892         quickSort(&leaves_tmp_storage, 0, leaves_tmp_storage.size() - 1);
893
894         // assign scores for internal nodes;
895         while ( !leaves_tmp_storage.empty() ) {
896                 Predicate * leaf = leaves_tmp_storage.back();
897                 leaves_tmp_storage.pop_back();
898
899                 Predicate * curr = leaf->get_parent();
900                 while (curr != NULL) {
901                         if (curr->get_weight() != 0) {
902                                 // Has been exlpored
903                                 break;
904                         }
905
906                         ModelVector<Predicate *> * children = curr->get_children();
907                         double weight_sum = 0;
908                         bool has_unassigned_node = false;
909
910                         for (uint i = 0;i < children->size();i++) {
911                                 Predicate * child = (*children)[i];
912
913                                 // If a child has unassigned weight
914                                 double weight = child->get_weight();
915                                 if (weight == 0) {
916                                         has_unassigned_node = true;
917                                         break;
918                                 } else
919                                         weight_sum += weight;
920                         }
921
922                         if (!has_unassigned_node) {
923                                 double average_weight = (double) weight_sum / (double) children->size();
924                                 double weight = average_weight * pow(0.9, curr->get_depth());
925                                 curr->set_weight(weight);
926                         } else
927                                 break;
928
929                         curr = curr->get_parent();
930                 }
931         }
932 }
933
934 void FuncNode::update_predicate_tree_weight()
935 {
936         if (marker == 2) {
937                 // Predicate tree is initially built
938                 assign_initial_weight();
939                 return;
940         }
941
942         weight_debug_vec.clear();
943
944         PredSetIter * it = failed_predicates.iterator();
945         while (it->hasNext()) {
946                 Predicate * pred = it->next();
947                 leaves_tmp_storage.push_back(pred);
948         }
949         delete it;
950         failed_predicates.reset();
951
952         quickSort(&leaves_tmp_storage, 0, leaves_tmp_storage.size() - 1);
953         for (uint i = 0;i < leaves_tmp_storage.size();i++) {
954                 Predicate * pred = leaves_tmp_storage[i];
955                 double weight = 100.0 / sqrt(pred->get_expl_count() + pred->get_fail_count() + 1);
956                 pred->set_weight(weight);
957         }
958
959         // Update weights in internal nodes
960         while ( !leaves_tmp_storage.empty() ) {
961                 Predicate * leaf = leaves_tmp_storage.back();
962                 leaves_tmp_storage.pop_back();
963
964                 Predicate * curr = leaf->get_parent();
965                 while (curr != NULL) {
966                         ModelVector<Predicate *> * children = curr->get_children();
967                         double weight_sum = 0;
968                         bool has_unassigned_node = false;
969
970                         for (uint i = 0;i < children->size();i++) {
971                                 Predicate * child = (*children)[i];
972
973                                 double weight = child->get_weight();
974                                 if (weight != 0)
975                                         weight_sum += weight;
976                                 else if ( predicate_leaves.contains(child) ) {
977                                         // If this child is a leaf
978                                         double weight = 100.0 / sqrt(child->get_expl_count() + 1);
979                                         child->set_weight(weight);
980                                         weight_sum += weight;
981                                 } else {
982                                         has_unassigned_node = true;
983                                         weight_debug_vec.push_back(child);      // For debugging purpose
984                                         break;
985                                 }
986                         }
987
988                         if (!has_unassigned_node) {
989                                 double average_weight = (double) weight_sum / (double) children->size();
990                                 double weight = average_weight * pow(0.9, curr->get_depth());
991                                 curr->set_weight(weight);
992                         } else
993                                 break;
994
995                         curr = curr->get_parent();
996                 }
997         }
998
999         for (uint i = 0;i < weight_debug_vec.size();i++) {
1000                 Predicate * tmp = weight_debug_vec[i];
1001                 ASSERT( tmp->get_weight() != 0 );
1002         }
1003 }
1004
1005 void FuncNode::print_predicate_tree()
1006 {
1007         model_print("digraph function_%s {\n", func_name);
1008         predicate_tree_entry->print_pred_subtree();
1009         predicate_tree_exit->print_predicate();
1010         model_print("}\n");     // end of graph
1011 }