Toward transferring the removal of some actions from ModelExecution to FuncNode or...
[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
181         /* build inst_list from act_list for later processing */
182         func_inst_list_t inst_list;
183         action_list_t rw_act_list;
184
185         for (sllnode<ModelAction *> * it = act_list->begin();it != NULL;it = it->getNext()) {
186                 ModelAction * act = it->getVal();
187                 act->setFuncActRef(NULL);       // Remove func_act_ref so that this action can be removed
188                 FuncInst * func_inst = get_inst(act);
189                 void * loc = act->get_location();
190
191                 if (func_inst == NULL)
192                         continue;
193
194                 inst_list.push_back(func_inst);
195                 bool act_added = false;
196
197                 if (act->is_write()) {
198                         rw_act_list.push_back(act);
199                         act_added = true;
200                         if (!write_locations->contains(loc)) {
201                                 write_locations->add(loc);
202                                 history->update_loc_wr_func_nodes_map(loc, this);
203                         }
204                 }
205
206                 if (act->is_read()) {
207                         if (!act_added)
208                                 rw_act_list.push_back(act);
209
210                         /* If func_inst may only read_from a single location, then:
211                          *
212                          * The first time an action reads from some location,
213                          * import all the values that have been written to this
214                          * location from ModelHistory and notify ModelHistory
215                          * that this FuncNode may read from this location.
216                          */
217                         if (!read_locations->contains(loc) && func_inst->is_single_location()) {
218                                 read_locations->add(loc);
219                                 value_set_t * write_values = write_history->get(loc);
220                                 add_to_val_loc_map(write_values, loc);
221                                 history->update_loc_rd_func_nodes_map(loc, this);
222                         }
223                 }
224         }
225
226 //      model_print("function %s\n", func_name);
227 //      print_val_loc_map();
228
229         update_inst_tree(&inst_list);
230         update_predicate_tree(&rw_act_list);
231
232 //      print_predicate_tree();
233 }
234
235 /**
236  * @brief Link FuncInsts in inst_list  - add one FuncInst to another's predecessors and successors
237  * @param inst_list A list of FuncInsts
238  */
239 void FuncNode::update_inst_tree(func_inst_list_t * inst_list)
240 {
241         if (inst_list == NULL)
242                 return;
243         else if (inst_list->size() == 0)
244                 return;
245
246         /* start linking */
247         sllnode<FuncInst *>* it = inst_list->begin();
248         sllnode<FuncInst *>* prev;
249
250         /* add the first instruction to the list of entry insts */
251         FuncInst * entry_inst = it->getVal();
252         add_entry_inst(entry_inst);
253
254         it = it->getNext();
255         while (it != NULL) {
256                 prev = it->getPrev();
257
258                 FuncInst * prev_inst = prev->getVal();
259                 FuncInst * curr_inst = it->getVal();
260
261                 prev_inst->add_succ(curr_inst);
262                 curr_inst->add_pred(prev_inst);
263
264                 it = it->getNext();
265         }
266 }
267
268 void FuncNode::update_predicate_tree(action_list_t * act_list)
269 {
270         if (act_list == NULL || act_list->size() == 0)
271                 return;
272
273         incr_marker();
274         uint32_t inst_counter = 0;
275
276         // Clear hashtables
277         loc_act_map.reset();
278         inst_pred_map.reset();
279         inst_id_map.reset();
280
281         // Clear the set of leaves encountered in this path
282         leaves_tmp_storage.clear();
283
284         sllnode<ModelAction *> *it = act_list->begin();
285         Predicate * curr_pred = predicate_tree_entry;
286         while (it != NULL) {
287                 ModelAction * next_act = it->getVal();
288                 FuncInst * next_inst = get_inst(next_act);
289                 next_inst->set_associated_act(next_act, marker);
290
291                 Predicate * unset_predicate = NULL;
292                 bool branch_found = follow_branch(&curr_pred, next_inst, next_act, &unset_predicate);
293
294                 // A branch with unset predicate expression is detected
295                 if (!branch_found && unset_predicate != NULL) {
296                         bool amended = amend_predicate_expr(curr_pred, next_inst, next_act);
297                         if (amended)
298                                 continue;
299                         else {
300                                 curr_pred = unset_predicate;
301                                 branch_found = true;
302                         }
303                 }
304
305                 // Detect loops
306                 if (!branch_found && inst_id_map.contains(next_inst)) {
307                         FuncInst * curr_inst = curr_pred->get_func_inst();
308                         uint32_t curr_id = inst_id_map.get(curr_inst);
309                         uint32_t next_id = inst_id_map.get(next_inst);
310
311                         if (curr_id >= next_id) {
312                                 Predicate * old_pred = inst_pred_map.get(next_inst);
313                                 Predicate * back_pred = old_pred->get_parent();
314
315                                 // For updating weights
316                                 leaves_tmp_storage.push_back(curr_pred);
317
318                                 // Add to the set of backedges
319                                 curr_pred->add_backedge(back_pred);
320                                 curr_pred = back_pred;
321                                 continue;
322                         }
323                 }
324
325                 // Generate new branches
326                 if (!branch_found) {
327                         SnapVector<struct half_pred_expr *> half_pred_expressions;
328                         infer_predicates(next_inst, next_act, &half_pred_expressions);
329                         generate_predicates(curr_pred, next_inst, &half_pred_expressions);
330                         continue;
331                 }
332
333                 if (next_act->is_write())
334                         curr_pred->set_write(true);
335
336                 if (next_act->is_read()) {
337                         /* Only need to store the locations of read actions */
338                         loc_act_map.put(next_act->get_location(), next_act);
339                 }
340
341                 inst_pred_map.put(next_inst, curr_pred);
342                 if (!inst_id_map.contains(next_inst))
343                         inst_id_map.put(next_inst, inst_counter++);
344
345                 it = it->getNext();
346                 curr_pred->incr_expl_count();
347         }
348
349         if (curr_pred->get_exit() == NULL) {
350                 // Exit predicate is unset yet
351                 curr_pred->set_exit(predicate_tree_exit);
352         }
353
354         leaves_tmp_storage.push_back(curr_pred);
355         update_predicate_tree_weight();
356 }
357
358 /* Given curr_pred and next_inst, find the branch following curr_pred that
359  * contains next_inst and the correct predicate.
360  * @return true if branch found, false otherwise.
361  */
362 bool FuncNode::follow_branch(Predicate ** curr_pred, FuncInst * next_inst,
363                                                                                                                  ModelAction * next_act, Predicate ** unset_predicate)
364 {
365         /* Check if a branch with func_inst and corresponding predicate exists */
366         bool branch_found = false;
367         ModelVector<Predicate *> * branches = (*curr_pred)->get_children();
368         for (uint i = 0;i < branches->size();i++) {
369                 Predicate * branch = (*branches)[i];
370                 if (branch->get_func_inst() != next_inst)
371                         continue;
372
373                 /* Check against predicate expressions */
374                 bool predicate_correct = true;
375                 PredExprSet * pred_expressions = branch->get_pred_expressions();
376
377                 /* Only read and rmw actions my have unset predicate expressions */
378                 if (pred_expressions->getSize() == 0) {
379                         predicate_correct = false;
380                         if (*unset_predicate == NULL)
381                                 *unset_predicate = branch;
382                         else
383                                 ASSERT(false);
384
385                         continue;
386                 }
387
388                 PredExprSetIter * pred_expr_it = pred_expressions->iterator();
389                 while (pred_expr_it->hasNext()) {
390                         pred_expr * pred_expression = pred_expr_it->next();
391                         uint64_t last_read, next_read;
392                         bool equality;
393
394                         switch(pred_expression->token) {
395                         case NOPREDICATE:
396                                 predicate_correct = true;
397                                 break;
398                         case EQUALITY:
399                                 FuncInst * to_be_compared;
400                                 ModelAction * last_act;
401
402                                 to_be_compared = pred_expression->func_inst;
403                                 last_act = to_be_compared->get_associated_act(marker);
404
405                                 last_read = last_act->get_reads_from_value();
406                                 next_read = next_act->get_reads_from_value();
407                                 equality = (last_read == next_read);
408                                 if (equality != pred_expression->value)
409                                         predicate_correct = false;
410
411                                 break;
412                         case NULLITY:
413                                 next_read = next_act->get_reads_from_value();
414                                 // TODO: implement likely to be null
415                                 equality = ( (void*) (next_read & 0xffffffff) == NULL);
416                                 if (equality != pred_expression->value)
417                                         predicate_correct = false;
418                                 break;
419                         default:
420                                 predicate_correct = false;
421                                 model_print("unkown predicate token\n");
422                                 break;
423                         }
424                 }
425
426                 delete pred_expr_it;
427
428                 if (predicate_correct) {
429                         *curr_pred = branch;
430                         branch_found = true;
431                         break;
432                 }
433         }
434
435         return branch_found;
436 }
437
438 /* Infer predicate expressions, which are generated in FuncNode::generate_predicates */
439 void FuncNode::infer_predicates(FuncInst * next_inst, ModelAction * next_act,
440                                                                                                                                 SnapVector<struct half_pred_expr *> * half_pred_expressions)
441 {
442         void * loc = next_act->get_location();
443
444         if (next_inst->is_read()) {
445                 /* read + rmw */
446                 if ( loc_act_map.contains(loc) ) {
447                         ModelAction * last_act = loc_act_map.get(loc);
448                         FuncInst * last_inst = get_inst(last_act);
449                         struct half_pred_expr * expression = new half_pred_expr(EQUALITY, last_inst);
450                         half_pred_expressions->push_back(expression);
451                 } else if ( next_inst->is_single_location() ) {
452                         loc_set_t * loc_may_equal = loc_may_equal_map->get(loc);
453
454                         if (loc_may_equal != NULL) {
455                                 loc_set_iter * loc_it = loc_may_equal->iterator();
456                                 while (loc_it->hasNext()) {
457                                         void * neighbor = loc_it->next();
458                                         if (loc_act_map.contains(neighbor)) {
459                                                 ModelAction * last_act = loc_act_map.get(neighbor);
460                                                 FuncInst * last_inst = get_inst(last_act);
461
462                                                 struct half_pred_expr * expression = new half_pred_expr(EQUALITY, last_inst);
463                                                 half_pred_expressions->push_back(expression);
464                                         }
465                                 }
466
467                                 delete loc_it;
468                         }
469                 } else {
470                         // next_inst is not single location
471                         uint64_t read_val = next_act->get_reads_from_value();
472
473                         // only infer NULLITY predicate when it is actually NULL.
474                         if ( (void*)read_val == NULL) {
475                                 struct half_pred_expr * expression = new half_pred_expr(NULLITY, NULL);
476                                 half_pred_expressions->push_back(expression);
477                         }
478                 }
479         } else {
480                 /* Pure writes */
481                 // TODO: do anything here?
482         }
483 }
484
485 /* Able to generate complex predicates when there are multiple predciate expressions */
486 void FuncNode::generate_predicates(Predicate * curr_pred, FuncInst * next_inst,
487                                                                                                                                          SnapVector<struct half_pred_expr *> * half_pred_expressions)
488 {
489         if (half_pred_expressions->size() == 0) {
490                 Predicate * new_pred = new Predicate(next_inst);
491                 curr_pred->add_child(new_pred);
492                 new_pred->set_parent(curr_pred);
493
494                 /* Maintain predicate leaves */
495                 predicate_leaves.add(new_pred);
496                 predicate_leaves.remove(curr_pred);
497
498                 /* entry predicates and predicates containing pure write actions
499                  * have no predicate expressions */
500                 if ( curr_pred->is_entry_predicate() )
501                         new_pred->add_predicate_expr(NOPREDICATE, NULL, true);
502                 else if (next_inst->is_write()) {
503                         /* next_inst->is_write() <==> pure writes */
504                         new_pred->add_predicate_expr(NOPREDICATE, NULL, true);
505                 }
506
507                 return;
508         }
509
510         SnapVector<Predicate *> predicates;
511
512         struct half_pred_expr * half_expr = (*half_pred_expressions)[0];
513         predicates.push_back(new Predicate(next_inst));
514         predicates.push_back(new Predicate(next_inst));
515
516         predicates[0]->add_predicate_expr(half_expr->token, half_expr->func_inst, true);
517         predicates[1]->add_predicate_expr(half_expr->token, half_expr->func_inst, false);
518
519         for (uint i = 1;i < half_pred_expressions->size();i++) {
520                 half_expr = (*half_pred_expressions)[i];
521
522                 uint old_size = predicates.size();
523                 for (uint j = 0;j < old_size;j++) {
524                         Predicate * pred = predicates[j];
525                         Predicate * new_pred = new Predicate(next_inst);
526                         new_pred->copy_predicate_expr(pred);
527
528                         pred->add_predicate_expr(half_expr->token, half_expr->func_inst, true);
529                         new_pred->add_predicate_expr(half_expr->token, half_expr->func_inst, false);
530
531                         predicates.push_back(new_pred);
532                 }
533         }
534
535         for (uint i = 0;i < predicates.size();i++) {
536                 Predicate * pred= predicates[i];
537                 curr_pred->add_child(pred);
538                 pred->set_parent(curr_pred);
539
540                 /* Add new predicate leaves */
541                 predicate_leaves.add(pred);
542         }
543
544         /* Remove predicate node that has children */
545         predicate_leaves.remove(curr_pred);
546
547         /* Free memories allocated by infer_predicate */
548         for (uint i = 0;i < half_pred_expressions->size();i++) {
549                 struct half_pred_expr * tmp = (*half_pred_expressions)[i];
550                 snapshot_free(tmp);
551         }
552 }
553
554 /* Amend predicates that contain no predicate expressions. Currenlty only amend with NULLITY predicates */
555 bool FuncNode::amend_predicate_expr(Predicate * curr_pred, FuncInst * next_inst, ModelAction * next_act)
556 {
557         ModelVector<Predicate *> * children = curr_pred->get_children();
558
559         Predicate * unset_pred = NULL;
560         for (uint i = 0;i < children->size();i++) {
561                 Predicate * child = (*children)[i];
562                 if (child->get_func_inst() == next_inst) {
563                         unset_pred = child;
564                         break;
565                 }
566         }
567
568         uint64_t read_val = next_act->get_reads_from_value();
569
570         // only generate NULLITY predicate when it is actually NULL.
571         if ( !next_inst->is_single_location() && (void*)read_val == NULL ) {
572                 Predicate * new_pred = new Predicate(next_inst);
573
574                 curr_pred->add_child(new_pred);
575                 new_pred->set_parent(curr_pred);
576
577                 unset_pred->add_predicate_expr(NULLITY, NULL, false);
578                 new_pred->add_predicate_expr(NULLITY, NULL, true);
579
580                 return true;
581         }
582
583         return false;
584 }
585
586 void FuncNode::add_to_val_loc_map(uint64_t val, void * loc)
587 {
588         loc_set_t * locations = val_loc_map->get(val);
589
590         if (locations == NULL) {
591                 locations = new loc_set_t();
592                 val_loc_map->put(val, locations);
593         }
594
595         update_loc_may_equal_map(loc, locations);
596         locations->add(loc);
597         // values_may_read_from->add(val);
598 }
599
600 void FuncNode::add_to_val_loc_map(value_set_t * values, void * loc)
601 {
602         if (values == NULL)
603                 return;
604
605         value_set_iter * it = values->iterator();
606         while (it->hasNext()) {
607                 uint64_t val = it->next();
608                 add_to_val_loc_map(val, loc);
609         }
610
611         delete it;
612 }
613
614 void FuncNode::update_loc_may_equal_map(void * new_loc, loc_set_t * old_locations)
615 {
616         if ( old_locations->contains(new_loc) )
617                 return;
618
619         loc_set_t * neighbors = loc_may_equal_map->get(new_loc);
620
621         if (neighbors == NULL) {
622                 neighbors = new loc_set_t();
623                 loc_may_equal_map->put(new_loc, neighbors);
624         }
625
626         loc_set_iter * loc_it = old_locations->iterator();
627         while (loc_it->hasNext()) {
628                 // new_loc: { old_locations, ... }
629                 void * member = loc_it->next();
630                 neighbors->add(member);
631
632                 // for each i in old_locations, i : { new_loc, ... }
633                 loc_set_t * _neighbors = loc_may_equal_map->get(member);
634                 if (_neighbors == NULL) {
635                         _neighbors = new loc_set_t();
636                         loc_may_equal_map->put(member, _neighbors);
637                 }
638                 _neighbors->add(new_loc);
639         }
640
641         delete loc_it;
642 }
643
644 /* Every time a thread enters a function, set its position to the predicate tree entry */
645 void FuncNode::init_predicate_tree_position(thread_id_t tid)
646 {
647         int thread_id = id_to_int(tid);
648         if (predicate_tree_position.size() <= (uint) thread_id)
649                 predicate_tree_position.resize(thread_id + 1);
650
651         predicate_tree_position[thread_id] = predicate_tree_entry;
652 }
653
654 void FuncNode::set_predicate_tree_position(thread_id_t tid, Predicate * pred)
655 {
656         int thread_id = id_to_int(tid);
657         predicate_tree_position[thread_id] = pred;
658 }
659
660 /* @return The position of a thread in a predicate tree */
661 Predicate * FuncNode::get_predicate_tree_position(thread_id_t tid)
662 {
663         int thread_id = id_to_int(tid);
664         return predicate_tree_position[thread_id];
665 }
666
667 /* Make sure elements of thrd_inst_act_map are initialized properly when threads enter functions */
668 void FuncNode::init_inst_act_map(thread_id_t tid)
669 {
670         int thread_id = id_to_int(tid);
671         SnapVector<inst_act_map_t *> * thrd_inst_act_map = history->getThrdInstActMap(func_id);
672         uint old_size = thrd_inst_act_map->size();
673
674         if (thrd_inst_act_map->size() <= (uint) thread_id) {
675                 uint new_size = thread_id + 1;
676                 thrd_inst_act_map->resize(new_size);
677
678                 for (uint i = old_size;i < new_size;i++)
679                         (*thrd_inst_act_map)[i] = new inst_act_map_t(128);
680         }
681 }
682
683 /* Reset elements of thrd_inst_act_map when threads exit functions */
684 void FuncNode::reset_inst_act_map(thread_id_t tid)
685 {
686         int thread_id = id_to_int(tid);
687         SnapVector<inst_act_map_t *> * thrd_inst_act_map = history->getThrdInstActMap(func_id);
688
689         inst_act_map_t * map = (*thrd_inst_act_map)[thread_id];
690         map->reset();
691 }
692
693 void FuncNode::update_inst_act_map(thread_id_t tid, ModelAction * read_act)
694 {
695         int thread_id = id_to_int(tid);
696         SnapVector<inst_act_map_t *> * thrd_inst_act_map = history->getThrdInstActMap(func_id);
697
698         inst_act_map_t * map = (*thrd_inst_act_map)[thread_id];
699         FuncInst * read_inst = get_inst(read_act);
700         map->put(read_inst, read_act);
701 }
702
703 inst_act_map_t * FuncNode::get_inst_act_map(thread_id_t tid)
704 {
705         int thread_id = id_to_int(tid);
706         SnapVector<inst_act_map_t *> * thrd_inst_act_map = history->getThrdInstActMap(func_id);
707
708         return (*thrd_inst_act_map)[thread_id];
709 }
710
711 /* Add FuncNodes that this node may follow */
712 void FuncNode::add_out_edge(FuncNode * other)
713 {
714         if ( !edge_table.contains(other) ) {
715                 edge_table.put(other, OUT_EDGE);
716                 out_edges.push_back(other);
717                 return;
718         }
719
720         edge_type_t edge = edge_table.get(other);
721         if (edge == IN_EDGE) {
722                 edge_table.put(other, BI_EDGE);
723                 out_edges.push_back(other);
724         }
725 }
726
727 /* Compute the distance between this FuncNode and the target node.
728  * Return -1 if the target node is unreachable or the actual distance
729  * is greater than max_step.
730  */
731 int FuncNode::compute_distance(FuncNode * target, int max_step)
732 {
733         if (target == NULL)
734                 return -1;
735         else if (target == this)
736                 return 0;
737
738         SnapList<FuncNode *> queue;
739         HashTable<FuncNode *, int, uintptr_t, 0> distances(128);
740
741         queue.push_back(this);
742         distances.put(this, 0);
743
744         while (!queue.empty()) {
745                 FuncNode * curr = queue.front();
746                 queue.pop_front();
747                 int dist = distances.get(curr);
748
749                 if (max_step <= dist)
750                         return -1;
751
752                 ModelList<FuncNode *> * outEdges = curr->get_out_edges();
753                 mllnode<FuncNode *> * it;
754                 for (it = outEdges->begin();it != NULL;it = it->getNext()) {
755                         FuncNode * out_node = it->getVal();
756
757                         /* This node has not been visited before */
758                         if ( !distances.contains(out_node) ) {
759                                 if (out_node == target)
760                                         return dist + 1;
761
762                                 queue.push_back(out_node);
763                                 distances.put(out_node, dist + 1);
764                         }
765                 }
766         }
767
768         /* Target node is unreachable */
769         return -1;
770 }
771
772 void FuncNode::add_failed_predicate(Predicate * pred)
773 {
774         failed_predicates.add(pred);
775 }
776
777 /* Implement quick sort to sort leaves before assigning base scores */
778 template<typename _Tp>
779 static int partition(ModelVector<_Tp *> * arr, int low, int high)
780 {
781         unsigned int pivot = (*arr)[high] -> get_depth();
782         int i = low - 1;
783
784         for (int j = low;j <= high - 1;j ++) {
785                 if ( (*arr)[j] -> get_depth() < pivot ) {
786                         i ++;
787                         _Tp * tmp = (*arr)[i];
788                         (*arr)[i] = (*arr)[j];
789                         (*arr)[j] = tmp;
790                 }
791         }
792
793         _Tp * tmp = (*arr)[i + 1];
794         (*arr)[i + 1] = (*arr)[high];
795         (*arr)[high] = tmp;
796
797         return i + 1;
798 }
799
800 /* Implement quick sort to sort leaves before assigning base scores */
801 template<typename _Tp>
802 static void quickSort(ModelVector<_Tp *> * arr, int low, int high)
803 {
804         if (low < high) {
805                 int pi = partition(arr, low, high);
806
807                 quickSort(arr, low, pi - 1);
808                 quickSort(arr, pi + 1, high);
809         }
810 }
811
812 void FuncNode::assign_initial_weight()
813 {
814         PredSetIter * it = predicate_leaves.iterator();
815         leaves_tmp_storage.clear();
816
817         while (it->hasNext()) {
818                 Predicate * pred = it->next();
819                 double weight = 100.0 / sqrt(pred->get_expl_count() + pred->get_fail_count() + 1);
820                 pred->set_weight(weight);
821                 leaves_tmp_storage.push_back(pred);
822         }
823         delete it;
824
825         quickSort(&leaves_tmp_storage, 0, leaves_tmp_storage.size() - 1);
826
827         // assign scores for internal nodes;
828         while ( !leaves_tmp_storage.empty() ) {
829                 Predicate * leaf = leaves_tmp_storage.back();
830                 leaves_tmp_storage.pop_back();
831
832                 Predicate * curr = leaf->get_parent();
833                 while (curr != NULL) {
834                         if (curr->get_weight() != 0) {
835                                 // Has been exlpored
836                                 break;
837                         }
838
839                         ModelVector<Predicate *> * children = curr->get_children();
840                         double weight_sum = 0;
841                         bool has_unassigned_node = false;
842
843                         for (uint i = 0;i < children->size();i++) {
844                                 Predicate * child = (*children)[i];
845
846                                 // If a child has unassigned weight
847                                 double weight = child->get_weight();
848                                 if (weight == 0) {
849                                         has_unassigned_node = true;
850                                         break;
851                                 } else
852                                         weight_sum += weight;
853                         }
854
855                         if (!has_unassigned_node) {
856                                 double average_weight = (double) weight_sum / (double) children->size();
857                                 double weight = average_weight * pow(0.9, curr->get_depth());
858                                 curr->set_weight(weight);
859                         } else
860                                 break;
861
862                         curr = curr->get_parent();
863                 }
864         }
865 }
866
867 void FuncNode::update_predicate_tree_weight()
868 {
869         if (marker == 2) {
870                 // Predicate tree is initially built
871                 assign_initial_weight();
872                 return;
873         }
874
875         weight_debug_vec.clear();
876
877         PredSetIter * it = failed_predicates.iterator();
878         while (it->hasNext()) {
879                 Predicate * pred = it->next();
880                 leaves_tmp_storage.push_back(pred);
881         }
882         delete it;
883         failed_predicates.reset();
884
885         quickSort(&leaves_tmp_storage, 0, leaves_tmp_storage.size() - 1);
886         for (uint i = 0;i < leaves_tmp_storage.size();i++) {
887                 Predicate * pred = leaves_tmp_storage[i];
888                 double weight = 100.0 / sqrt(pred->get_expl_count() + pred->get_fail_count() + 1);
889                 pred->set_weight(weight);
890         }
891
892         // Update weights in internal nodes
893         while ( !leaves_tmp_storage.empty() ) {
894                 Predicate * leaf = leaves_tmp_storage.back();
895                 leaves_tmp_storage.pop_back();
896
897                 Predicate * curr = leaf->get_parent();
898                 while (curr != NULL) {
899                         ModelVector<Predicate *> * children = curr->get_children();
900                         double weight_sum = 0;
901                         bool has_unassigned_node = false;
902
903                         for (uint i = 0;i < children->size();i++) {
904                                 Predicate * child = (*children)[i];
905
906                                 double weight = child->get_weight();
907                                 if (weight != 0)
908                                         weight_sum += weight;
909                                 else if ( predicate_leaves.contains(child) ) {
910                                         // If this child is a leaf
911                                         double weight = 100.0 / sqrt(child->get_expl_count() + 1);
912                                         child->set_weight(weight);
913                                         weight_sum += weight;
914                                 } else {
915                                         has_unassigned_node = true;
916                                         weight_debug_vec.push_back(child);      // For debugging purpose
917                                         break;
918                                 }
919                         }
920
921                         if (!has_unassigned_node) {
922                                 double average_weight = (double) weight_sum / (double) children->size();
923                                 double weight = average_weight * pow(0.9, curr->get_depth());
924                                 curr->set_weight(weight);
925                         } else
926                                 break;
927
928                         curr = curr->get_parent();
929                 }
930         }
931
932         for (uint i = 0;i < weight_debug_vec.size();i++) {
933                 Predicate * tmp = weight_debug_vec[i];
934                 ASSERT( tmp->get_weight() != 0 );
935         }
936 }
937
938 void FuncNode::print_predicate_tree()
939 {
940         model_print("digraph function_%s {\n", func_name);
941         predicate_tree_entry->print_pred_subtree();
942         predicate_tree_exit->print_predicate();
943         model_print("}\n");     // end of graph
944 }