Eliminate many unneccesary #includes
[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 //*************************** User Include Files ***************************/
26
27 #include "llvm/CodeGen/InstrForest.h"
28 #include "llvm/Module.h"
29 #include "llvm/Method.h"
30 #include "llvm/iTerminators.h"
31 #include "llvm/iMemory.h"
32 #include "llvm/ConstPoolVals.h"
33 #include "llvm/BasicBlock.h"
34 #include "llvm/CodeGen/MachineInstr.h"
35
36 //************************ Class Implementations **************************/
37
38
39 //------------------------------------------------------------------------ 
40 // class InstrTreeNode
41 //------------------------------------------------------------------------ 
42
43
44 InstrTreeNode::InstrTreeNode(InstrTreeNodeType nodeType,
45                              Value* _val)
46   : treeNodeType(nodeType),
47     val(_val)
48 {
49   basicNode.leftChild = NULL;
50   basicNode.rightChild = NULL;
51   basicNode.parent = NULL;
52   basicNode.opLabel = InvalidOp;
53   basicNode.treeNodePtr = this;
54 }
55
56 InstrTreeNode::~InstrTreeNode()
57 {}
58
59
60 void
61 InstrTreeNode::dump(int dumpChildren,
62                     int indent) const
63 {
64   this->dumpNode(indent);
65   
66   if (dumpChildren)
67     {
68       if (leftChild())
69         leftChild()->dump(dumpChildren, indent+1);
70       if (rightChild())
71         rightChild()->dump(dumpChildren, indent+1);
72     }
73 }
74
75
76 InstructionNode::InstructionNode(Instruction* _instr)
77   : InstrTreeNode(NTInstructionNode, _instr)
78 {
79   OpLabel opLabel = _instr->getOpcode();
80
81   // Distinguish special cases of some instructions such as Ret and Br
82   // 
83   if (opLabel == Instruction::Ret && ((ReturnInst*) _instr)->getReturnValue())
84     {
85       opLabel = RetValueOp;              // ret(value) operation
86     }
87   else if (opLabel == Instruction::Br && ! ((BranchInst*) _instr)->isUnconditional())
88     {
89       opLabel = BrCondOp;               // br(cond) operation
90     }
91   else if (opLabel >= Instruction::SetEQ && opLabel <= Instruction::SetGT)
92     {
93       opLabel = SetCCOp;                // common label for all SetCC ops
94     }
95   else if (opLabel == Instruction::Alloca && _instr->getNumOperands() > 0)
96     {
97       opLabel = AllocaN;                 // Alloca(ptr, N) operation
98     }
99   else if ((opLabel == Instruction::Load ||
100             opLabel == Instruction::GetElementPtr)
101            && ((MemAccessInst*)_instr)->getFirstOffsetIdx() > 0)
102     {
103       opLabel = opLabel + 100;           // load/getElem with index vector
104     }
105   else if (opLabel == Instruction::Cast)
106     {
107       const Type* instrValueType = _instr->getType();
108       switch(instrValueType->getPrimitiveID())
109         {
110         case Type::BoolTyID:    opLabel = ToBoolTy;  break;
111         case Type::UByteTyID:   opLabel = ToUByteTy; break;
112         case Type::SByteTyID:   opLabel = ToSByteTy; break;
113         case Type::UShortTyID:  opLabel = ToUShortTy; break;
114         case Type::ShortTyID:   opLabel = ToShortTy; break;
115         case Type::UIntTyID:    opLabel = ToUIntTy; break;
116         case Type::IntTyID:     opLabel = ToIntTy; break;
117         case Type::ULongTyID:   opLabel = ToULongTy; break;
118         case Type::LongTyID:    opLabel = ToLongTy; break;
119         case Type::FloatTyID:   opLabel = ToFloatTy; break;
120         case Type::DoubleTyID:  opLabel = ToDoubleTy; break;
121         default:
122           if (instrValueType->isArrayType())
123             opLabel = ToArrayTy;
124           else if (instrValueType->isPointerType())
125             opLabel = ToPointerTy;
126           else
127             ; // Just use `Cast' opcode otherwise. It's probably ignored.
128           break;
129         }
130     }
131   
132   basicNode.opLabel = opLabel;
133 }
134
135 void
136 InstructionNode::reverseBinaryArgumentOrder()
137 {
138   assert(getInstruction()->isBinaryOp());
139   
140   // switch arguments for the instruction
141   ((BinaryOperator*) getInstruction())->swapOperands();
142   
143   // switch arguments for this tree node itself
144   BasicTreeNode* leftCopy = basicNode.leftChild;
145   basicNode.leftChild = basicNode.rightChild;
146   basicNode.rightChild = leftCopy;
147 }
148
149 void
150 InstructionNode::dumpNode(int indent) const
151 {
152   for (int i=0; i < indent; i++)
153     cout << "    ";
154   
155   cout << getInstruction()->getOpcodeName();
156   
157   const vector<MachineInstr*>& mvec = getInstruction()->getMachineInstrVec();
158   if (mvec.size() > 0)
159     cout << "\tMachine Instructions:  ";
160   for (unsigned int i=0; i < mvec.size(); i++)
161     {
162       mvec[i]->dump(0);
163       if (i < mvec.size() - 1)
164         cout << ";  ";
165     }
166   
167   cout << endl;
168 }
169
170
171 VRegListNode::VRegListNode()
172   : InstrTreeNode(NTVRegListNode, NULL)
173 {
174   basicNode.opLabel = VRegListOp;
175 }
176
177 void
178 VRegListNode::dumpNode(int indent) const
179 {
180   for (int i=0; i < indent; i++)
181     cout << "    ";
182   
183   cout << "List" << endl;
184 }
185
186
187 VRegNode::VRegNode(Value* _val)
188   : InstrTreeNode(NTVRegNode, _val)
189 {
190   basicNode.opLabel = VRegNodeOp;
191 }
192
193 void
194 VRegNode::dumpNode(int indent) const
195 {
196   for (int i=0; i < indent; i++)
197     cout << "    ";
198   
199   cout << "VReg " << getValue() << "\t(type "
200        << (int) getValue()->getValueType() << ")" << endl;
201 }
202
203
204 ConstantNode::ConstantNode(ConstPoolVal* constVal)
205   : InstrTreeNode(NTConstNode, constVal)
206 {
207   basicNode.opLabel = ConstantNodeOp;
208 }
209
210 void
211 ConstantNode::dumpNode(int indent) const
212 {
213   for (int i=0; i < indent; i++)
214     cout << "    ";
215   
216   cout << "Constant " << getValue() << "\t(type "
217        << (int) getValue()->getValueType() << ")" << endl;
218 }
219
220
221 LabelNode::LabelNode(BasicBlock* _bblock)
222   : InstrTreeNode(NTLabelNode, _bblock)
223 {
224   basicNode.opLabel = LabelNodeOp;
225 }
226
227 void
228 LabelNode::dumpNode(int indent) const
229 {
230   for (int i=0; i < indent; i++)
231     cout << "    ";
232   
233   cout << "Label " << getValue() << endl;
234 }
235
236 //------------------------------------------------------------------------
237 // class InstrForest
238 // 
239 // A forest of instruction trees, usually for a single method.
240 //------------------------------------------------------------------------ 
241
242 void
243 InstrForest::buildTreesForMethod(Method *method)
244 {
245   for (Method::inst_iterator instrIter = method->inst_begin();
246        instrIter != method->inst_end();
247        ++instrIter)
248     {
249       Instruction *instr = *instrIter;
250       if (! instr->isPHINode())
251         (void) this->buildTreeForInstruction(instr);
252     } 
253 }
254
255
256 void
257 InstrForest::dump() const
258 {
259   for (hash_set<InstructionNode*, ptrHashFunc >::const_iterator
260          treeRootIter = treeRoots.begin();
261        treeRootIter != treeRoots.end();
262        ++treeRootIter)
263     {
264       (*treeRootIter)->dump(/*dumpChildren*/ 1, /*indent*/ 0);
265     }
266 }
267
268 inline void
269 InstrForest::noteTreeNodeForInstr(Instruction* instr,
270                                   InstructionNode* treeNode)
271 {
272   assert(treeNode->getNodeType() == InstrTreeNode::NTInstructionNode);
273   (*this)[instr] = treeNode;
274   treeRoots.insert(treeNode);           // mark node as root of a new tree
275 }
276
277
278 inline void
279 InstrForest::setLeftChild(InstrTreeNode* parent, InstrTreeNode* child)
280 {
281   parent->basicNode.leftChild = & child->basicNode;
282   child->basicNode.parent = & parent->basicNode;
283   if (child->getNodeType() == InstrTreeNode::NTInstructionNode)
284     treeRoots.erase((InstructionNode*) child);  // no longer a tree root
285 }
286
287
288 inline void
289 InstrForest::setRightChild(InstrTreeNode* parent, InstrTreeNode* child)
290 {
291   parent->basicNode.rightChild = & child->basicNode;
292   child->basicNode.parent = & parent->basicNode;
293   if (child->getNodeType() == InstrTreeNode::NTInstructionNode)
294     treeRoots.erase((InstructionNode*) child);  // no longer a tree root
295 }
296
297
298 InstructionNode*
299 InstrForest::buildTreeForInstruction(Instruction* instr)
300 {
301   InstructionNode* treeNode = this->getTreeNodeForInstr(instr);
302   if (treeNode != NULL)
303     {// treeNode has already been constructed for this instruction
304       assert(treeNode->getInstruction() == instr);
305       return treeNode;
306     }
307   
308   // Otherwise, create a new tree node for this instruction.
309   // 
310   treeNode = new InstructionNode(instr);
311   this->noteTreeNodeForInstr(instr, treeNode);
312   
313   // If the instruction has more than 2 instruction operands,
314   // then we will not add any children.  This assumes that instructions
315   // like 'call' that have more than 2 instruction operands do not
316   // ever get combined with the instructions that compute the operands. 
317   // Note that we only count operands of type instruction and not other
318   // values such as branch labels for a branch or switch instruction.
319   //
320   // To do this efficiently, we'll walk all operands, build treeNodes
321   // for all instruction operands and save them in an array, and then
322   // insert children at the end if there are not more than 2.
323   // As a performance optimization, allocate a child array only
324   // if a fixed array is too small.
325   // 
326   int numChildren = 0;
327   const unsigned int MAX_CHILD = 8;
328   static InstrTreeNode* fixedChildArray[MAX_CHILD];
329   InstrTreeNode** childArray =
330     (instr->getNumOperands() > MAX_CHILD)
331     ? new (InstrTreeNode*)[instr->getNumOperands()]
332     : fixedChildArray;
333   
334   //
335   // Walk the operands of the instruction
336   // 
337   for (Instruction::op_iterator opIter = instr->op_begin();
338        opIter != instr->op_end();
339        ++opIter)
340     {
341       Value* operand = *opIter;
342       
343       // Check if the operand is a data value, not an branch label, type,
344       // method or module.  If the operand is an address type (i.e., label
345       // or method) that is used in an non-branching operation, e.g., `add'.
346       // that should be considered a data value.
347       
348       // Check latter condition here just to simplify the next IF.
349       bool includeAddressOperand =
350         ((operand->getValueType() == Value::BasicBlockVal
351           || operand->getValueType() == Value::MethodVal)
352          && ! instr->isTerminator());
353          
354       if (/* (*opIter) != NULL
355              &&*/ includeAddressOperand
356                   || operand->getValueType() == Value::InstructionVal
357                   ||  operand->getValueType() == Value::ConstantVal
358                   ||  operand->getValueType() == Value::MethodArgumentVal)
359         {// This operand is a data value
360           
361           // An instruction that computes the incoming value is added as a
362           // child of the current instruction if:
363           //   the value has only a single use
364           //   AND both instructions are in the same basic block
365           //   AND the instruction is not a PHI
366           // 
367           // (Note that if the value has only a single use (viz., `instr'),
368           //  the def of the value can be safely moved just before instr
369           //  and therefore it is safe to combine these two instructions.)
370           // 
371           // In all other cases, the virtual register holding the value
372           // is used directly, i.e., made a child of the instruction node.
373           // 
374           InstrTreeNode* opTreeNode;
375           if (operand->getValueType() == Value::InstructionVal
376               && operand->use_size() == 1
377               && ((Instruction*)operand)->getParent() == instr->getParent()
378               && ! ((Instruction*)operand)->isPHINode())
379             {
380               // Recursively create a treeNode for it.
381               opTreeNode =this->buildTreeForInstruction((Instruction*)operand);
382             }
383           else if (operand->getValueType() == Value::ConstantVal)
384             {
385               // Create a leaf node for a constant
386               opTreeNode = new ConstantNode((ConstPoolVal*) operand);
387             }
388           else
389             {
390               // Create a leaf node for the virtual register
391               opTreeNode = new VRegNode(operand);
392             }
393           
394           childArray[numChildren] = opTreeNode;
395           numChildren++;
396         }
397     }
398   
399   //-------------------------------------------------------------------- 
400   // Add any selected operands as children in the tree.
401   // Certain instructions can have more than 2 in some instances (viz.,
402   // a CALL or a memory access -- LOAD, STORE, and GetElemPtr -- to an
403   // array or struct). Make the operands of every such instruction into
404   // a right-leaning binary tree with the operand nodes at the leaves
405   // and VRegList nodes as internal nodes.
406   //-------------------------------------------------------------------- 
407   
408   InstrTreeNode* parent = treeNode;             // new VRegListNode();
409   int n;
410   
411   if (numChildren > 2)
412     {
413       unsigned instrOpcode = treeNode->getInstruction()->getOpcode();
414       assert(instrOpcode == Instruction::Call ||
415              instrOpcode == Instruction::Load ||
416              instrOpcode == Instruction::Store ||
417              instrOpcode == Instruction::GetElementPtr);
418     }
419   
420   // Insert the first child as a direct child
421   if (numChildren >= 1)
422     this->setLeftChild(parent, childArray[0]);
423   
424   // Create a list node for children 2 .. N-1, if any
425   for (n = numChildren-1; n >= 2; n--)
426     { // We have more than two children
427       InstrTreeNode* listNode = new VRegListNode();
428       this->setRightChild(parent, listNode);
429       this->setLeftChild(listNode, childArray[numChildren - n]);
430       parent = listNode;
431     }
432   
433   // Now insert the last remaining child (if any).
434   if (numChildren >= 2)
435     {
436       assert(n == 1);
437       this->setRightChild(parent, childArray[numChildren - 1]);
438     }
439   
440   if (childArray != fixedChildArray)
441     {
442       delete[] childArray; 
443     }
444   
445   return treeNode;
446 }
447