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