Minor changes.
[oota-llvm.git] / lib / Target / SparcV9 / InstrSelection / InstrForest.cpp
1 // $Id$
2 //---------------------------------------------------------------------------
3 // File:
4 //      InstrForest.cpp
5 // 
6 // Purpose:
7 //      Convert SSA graph to instruction trees for instruction selection.
8 // 
9 // Strategy:
10 //  The key goal is to group instructions into a single
11 //  tree if one or more of them might be potentially combined into a single
12 //  complex instruction in the target machine.
13 //  Since this grouping is completely machine-independent, we do it as
14 //  aggressive as possible to exploit any possible taret instructions.
15 //  In particular, we group two instructions O and I if:
16 //      (1) Instruction O computes an operand used by instruction I,
17 //  and (2) O and I are part of the same basic block,
18 //  and (3) O has only a single use, viz., I.
19 // 
20 // History:
21 //      6/28/01  -  Vikram Adve  -  Created
22 // 
23 //---------------------------------------------------------------------------
24
25 #include "llvm/CodeGen/InstrForest.h"
26 #include "llvm/Method.h"
27 #include "llvm/iTerminators.h"
28 #include "llvm/iMemory.h"
29 #include "llvm/ConstPoolVals.h"
30 #include "llvm/BasicBlock.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/Support/STLExtras.h"
33
34 //------------------------------------------------------------------------ 
35 // class InstrTreeNode
36 //------------------------------------------------------------------------ 
37
38 void
39 InstrTreeNode::dump(int dumpChildren, int indent) const
40 {
41   dumpNode(indent);
42   
43   if (dumpChildren)
44     {
45       if (LeftChild)
46         LeftChild->dump(dumpChildren, indent+1);
47       if (RightChild)
48         RightChild->dump(dumpChildren, indent+1);
49     }
50 }
51
52
53 InstructionNode::InstructionNode(Instruction* I)
54   : InstrTreeNode(NTInstructionNode, I)
55 {
56   opLabel = I->getOpcode();
57
58   // Distinguish special cases of some instructions such as Ret and Br
59   // 
60   if (opLabel == Instruction::Ret && ((ReturnInst*)I)->getReturnValue())
61     {
62       opLabel = RetValueOp;                      // ret(value) operation
63     }
64   else if (opLabel == Instruction::Br && ! ((BranchInst*)I)->isUnconditional())
65     {
66       opLabel = BrCondOp;               // br(cond) operation
67     }
68   else if (opLabel >= Instruction::SetEQ && opLabel <= Instruction::SetGT)
69     {
70       opLabel = SetCCOp;                // common label for all SetCC ops
71     }
72   else if (opLabel == Instruction::Alloca && I->getNumOperands() > 0)
73     {
74       opLabel = AllocaN;                 // Alloca(ptr, N) operation
75     }
76   else if ((opLabel == Instruction::Load ||
77             opLabel == Instruction::GetElementPtr) &&
78            ((MemAccessInst*)I)->getFirstOffsetIdx() > 0)
79     {
80       opLabel = opLabel + 100;           // load/getElem with index vector
81     }
82   else if (opLabel == Instruction::Cast)
83     {
84       const Type *ITy = I->getType();
85       switch(ITy->getPrimitiveID())
86         {
87         case Type::BoolTyID:    opLabel = ToBoolTy;    break;
88         case Type::UByteTyID:   opLabel = ToUByteTy;   break;
89         case Type::SByteTyID:   opLabel = ToSByteTy;   break;
90         case Type::UShortTyID:  opLabel = ToUShortTy;  break;
91         case Type::ShortTyID:   opLabel = ToShortTy;   break;
92         case Type::UIntTyID:    opLabel = ToUIntTy;    break;
93         case Type::IntTyID:     opLabel = ToIntTy;     break;
94         case Type::ULongTyID:   opLabel = ToULongTy;   break;
95         case Type::LongTyID:    opLabel = ToLongTy;    break;
96         case Type::FloatTyID:   opLabel = ToFloatTy;   break;
97         case Type::DoubleTyID:  opLabel = ToDoubleTy;  break;
98         case Type::ArrayTyID:   opLabel = ToArrayTy;   break;
99         case Type::PointerTyID: opLabel = ToPointerTy; break;
100         default:
101           // Just use `Cast' opcode otherwise. It's probably ignored.
102           break;
103         }
104     }
105 }
106
107
108 void
109 InstructionNode::dumpNode(int indent) const
110 {
111   for (int i=0; i < indent; i++)
112     cout << "    ";
113   
114   cout << getInstruction()->getOpcodeName();
115   
116   const vector<MachineInstr*> &mvec = getInstruction()->getMachineInstrVec();
117   if (mvec.size() > 0)
118     cout << "\tMachine Instructions:  ";
119   for (unsigned int i=0; i < mvec.size(); i++)
120     {
121       mvec[i]->dump(0);
122       if (i < mvec.size() - 1)
123         cout << ";  ";
124     }
125   
126   cout << endl;
127 }
128
129
130 void
131 VRegListNode::dumpNode(int indent) const
132 {
133   for (int i=0; i < indent; i++)
134     cout << "    ";
135   
136   cout << "List" << endl;
137 }
138
139
140 void
141 VRegNode::dumpNode(int indent) const
142 {
143   for (int i=0; i < indent; i++)
144     cout << "    ";
145   
146   cout << "VReg " << getValue() << "\t(type "
147        << (int) getValue()->getValueType() << ")" << endl;
148 }
149
150 void
151 ConstantNode::dumpNode(int indent) const
152 {
153   for (int i=0; i < indent; i++)
154     cout << "    ";
155   
156   cout << "Constant " << getValue() << "\t(type "
157        << (int) getValue()->getValueType() << ")" << endl;
158 }
159
160 void
161 LabelNode::dumpNode(int indent) const
162 {
163   for (int i=0; i < indent; i++)
164     cout << "    ";
165   
166   cout << "Label " << getValue() << endl;
167 }
168
169 //------------------------------------------------------------------------
170 // class InstrForest
171 // 
172 // A forest of instruction trees, usually for a single method.
173 //------------------------------------------------------------------------ 
174
175 InstrForest::InstrForest(Method *M)
176 {
177   for (Method::inst_iterator I = M->inst_begin(); I != M->inst_end(); ++I)
178     this->buildTreeForInstruction(*I);
179 }
180
181 InstrForest::~InstrForest()
182 {
183   for (hash_map<const Instruction*, InstructionNode*>:: iterator I = begin();
184        I != end(); ++I)
185     {
186       InstructionNode* node = (*I).second;
187       if (node)
188         delete node;
189     }
190 }
191
192 void
193 InstrForest::dump() const
194 {
195   for (hash_set<InstructionNode*>::const_iterator I = treeRoots.begin();
196        I != treeRoots.end(); ++I)
197     (*I)->dump(/*dumpChildren*/ 1, /*indent*/ 0);
198 }
199
200 inline void
201 InstrForest::noteTreeNodeForInstr(Instruction *instr,
202                                   InstructionNode *treeNode)
203 {
204   assert(treeNode->getNodeType() == InstrTreeNode::NTInstructionNode);
205   (*this)[instr] = treeNode;
206   treeRoots.insert(treeNode);           // mark node as root of a new tree
207 }
208
209
210 inline void
211 InstrForest::setLeftChild(InstrTreeNode *Par, InstrTreeNode *Chld)
212 {
213   Par->LeftChild = Chld;
214   Chld->Parent = Par;
215   if (Chld->getNodeType() == InstrTreeNode::NTInstructionNode)
216     treeRoots.erase((InstructionNode*)Chld); // no longer a tree root
217 }
218
219 inline void
220 InstrForest::setRightChild(InstrTreeNode *Par, InstrTreeNode *Chld)
221 {
222   Par->RightChild = Chld;
223   Chld->Parent = Par;
224   if (Chld->getNodeType() == InstrTreeNode::NTInstructionNode)
225     treeRoots.erase((InstructionNode*)Chld); // no longer a tree root
226 }
227
228
229 InstructionNode*
230 InstrForest::buildTreeForInstruction(Instruction *instr)
231 {
232   InstructionNode *treeNode = getTreeNodeForInstr(instr);
233   if (treeNode)
234     {
235       // treeNode has already been constructed for this instruction
236       assert(treeNode->getInstruction() == instr);
237       return treeNode;
238     }
239   
240   // Otherwise, create a new tree node for this instruction.
241   // 
242   treeNode = new InstructionNode(instr);
243   noteTreeNodeForInstr(instr, treeNode);
244   
245   if (instr->getOpcode() == Instruction::Call)
246     { // Operands of call instruction
247       return treeNode;
248     }
249   
250   // If the instruction has more than 2 instruction operands,
251   // then we need to create artificial list nodes to hold them.
252   // (Note that we only count operands that get tree nodes, and not
253   // others such as branch labels for a branch or switch instruction.)
254   //
255   // To do this efficiently, we'll walk all operands, build treeNodes
256   // for all appropriate operands and save them in an array.  We then
257   // insert children at the end, creating list nodes where needed.
258   // As a performance optimization, allocate a child array only
259   // if a fixed array is too small.
260   // 
261   int numChildren = 0;
262   const unsigned int MAX_CHILD = 8;
263   static InstrTreeNode *fixedChildArray[MAX_CHILD];
264   InstrTreeNode **childArray =
265     (instr->getNumOperands() > MAX_CHILD)
266     ? new (InstrTreeNode*)[instr->getNumOperands()] : fixedChildArray;
267   
268   //
269   // Walk the operands of the instruction
270   // 
271   for (Instruction::op_iterator O = instr->op_begin(); O!=instr->op_end(); ++O)
272     {
273       Value* operand = *O;
274       
275       // Check if the operand is a data value, not an branch label, type,
276       // method or module.  If the operand is an address type (i.e., label
277       // or method) that is used in an non-branching operation, e.g., `add'.
278       // that should be considered a data value.
279     
280       // Check latter condition here just to simplify the next IF.
281       bool includeAddressOperand =
282         (operand->isBasicBlock() || operand->isMethod())
283         && !instr->isTerminator();
284     
285       if (includeAddressOperand || operand->isInstruction() ||
286           operand->isConstant() || operand->isMethodArgument() ||
287           operand->isGlobal()) 
288         {
289           // This operand is a data value
290         
291           // An instruction that computes the incoming value is added as a
292           // child of the current instruction if:
293           //   the value has only a single use
294           //   AND both instructions are in the same basic block.
295           //   AND the current instruction is not a PHI (because the incoming
296           //            value is conceptually in a predecessor block,
297           //            even though it may be in the same static block)
298           // 
299           // (Note that if the value has only a single use (viz., `instr'),
300           //  the def of the value can be safely moved just before instr
301           //  and therefore it is safe to combine these two instructions.)
302           // 
303           // In all other cases, the virtual register holding the value
304           // is used directly, i.e., made a child of the instruction node.
305           // 
306           InstrTreeNode* opTreeNode;
307           if (operand->isInstruction() && operand->use_size() == 1 &&
308               ((Instruction*)operand)->getParent() == instr->getParent() &&
309               ! instr->isPHINode() &&
310               ! instr->getOpcode() == Instruction::Call)
311             {
312               // Recursively create a treeNode for it.
313               opTreeNode = buildTreeForInstruction((Instruction*)operand);
314             }
315           else if (ConstPoolVal *CPV = operand->castConstant())
316             {
317               // Create a leaf node for a constant
318               opTreeNode = new ConstantNode(CPV);
319             }
320           else
321             {
322               // Create a leaf node for the virtual register
323               opTreeNode = new VRegNode(operand);
324             }
325
326           childArray[numChildren++] = opTreeNode;
327         }
328     }
329   
330   //-------------------------------------------------------------------- 
331   // Add any selected operands as children in the tree.
332   // Certain instructions can have more than 2 in some instances (viz.,
333   // a CALL or a memory access -- LOAD, STORE, and GetElemPtr -- to an
334   // array or struct). Make the operands of every such instruction into
335   // a right-leaning binary tree with the operand nodes at the leaves
336   // and VRegList nodes as internal nodes.
337   //-------------------------------------------------------------------- 
338   
339   InstrTreeNode *parent = treeNode;
340   
341   if (numChildren > 2)
342     {
343       unsigned instrOpcode = treeNode->getInstruction()->getOpcode();
344       assert(instrOpcode == Instruction::PHINode ||
345              instrOpcode == Instruction::Call ||
346              instrOpcode == Instruction::Load ||
347              instrOpcode == Instruction::Store ||
348              instrOpcode == Instruction::GetElementPtr);
349     }
350   
351   // Insert the first child as a direct child
352   if (numChildren >= 1)
353     setLeftChild(parent, childArray[0]);
354
355   int n;
356   
357   // Create a list node for children 2 .. N-1, if any
358   for (n = numChildren-1; n >= 2; n--)
359     {
360       // We have more than two children
361       InstrTreeNode *listNode = new VRegListNode();
362       setRightChild(parent, listNode);
363       setLeftChild(listNode, childArray[numChildren - n]);
364       parent = listNode;
365     }
366   
367   // Now insert the last remaining child (if any).
368   if (numChildren >= 2)
369     {
370       assert(n == 1);
371       setRightChild(parent, childArray[numChildren - 1]);
372     }
373   
374   if (childArray != fixedChildArray)
375     delete [] childArray; 
376   
377   return treeNode;
378 }
379