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