The nearest basic block being dominated by all used values.

Hello,

Presumably I have two value v1 and v2 from two different basic block A
and B. Now I need to insert to a printf to print those two values at
the same time.
This means I need to find a basic block to insert such a calling
isntruction and at the same time, the basic block should be dominated
by v1 and v2. Is there any easy way to find such a basic block?

Cheers,
Zheng

Zheng Wang wrote:

Hello,

Presumably I have two value v1 and v2 from two different basic block A
and B. Now I need to insert to a printf to print those two values at
the same time.
This means I need to find a basic block to insert such a calling
isntruction and at the same time, the basic block should be dominated
by v1 and v2. Is there any easy way to find such a basic block?
  
In general, you are not guaranteed that such as basic block exists. A or B might be leaves in the dominator tree (i.e., they may not dominate any blocks).

The best way to do this (assuming you can't print v1 and v2 separately), is to do the following:

0) Run the pass that transforms the code to ensure that each function as a single exit block (-mergereturn).
1) Create an alloca'ed location to hold v1 and v2 in the entry block.
2) Store an undef in v1 and v2 in the entry block.
3) After generating v1 and v2, store them into the alloca'ed location.
4) Using the postdominator tree, find the first ancestor in the tree that postdominates A and B. Call this node C.
5) In node C, add code to load the values out of the alloca'ed memory locations and print them.
6) Run mem2reg after your pass. This should remove the allocas and insert the proper phi nodes.

-- John T.