Convert more code to use new style casts
[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       delete (*I).second;
186 }
187
188 void
189 InstrForest::dump() const
190 {
191   for (hash_set<InstructionNode*>::const_iterator I = treeRoots.begin();
192        I != treeRoots.end(); ++I)
193     (*I)->dump(/*dumpChildren*/ 1, /*indent*/ 0);
194 }
195
196 inline void
197 InstrForest::noteTreeNodeForInstr(Instruction *instr,
198                                   InstructionNode *treeNode)
199 {
200   assert(treeNode->getNodeType() == InstrTreeNode::NTInstructionNode);
201   (*this)[instr] = treeNode;
202   treeRoots.insert(treeNode);           // mark node as root of a new tree
203 }
204
205
206 inline void
207 InstrForest::setLeftChild(InstrTreeNode *Par, InstrTreeNode *Chld)
208 {
209   Par->LeftChild = Chld;
210   Chld->Parent = Par;
211   if (Chld->getNodeType() == InstrTreeNode::NTInstructionNode)
212     treeRoots.erase((InstructionNode*)Chld); // no longer a tree root
213 }
214
215 inline void
216 InstrForest::setRightChild(InstrTreeNode *Par, InstrTreeNode *Chld)
217 {
218   Par->RightChild = Chld;
219   Chld->Parent = Par;
220   if (Chld->getNodeType() == InstrTreeNode::NTInstructionNode)
221     treeRoots.erase((InstructionNode*)Chld); // no longer a tree root
222 }
223
224
225 InstructionNode*
226 InstrForest::buildTreeForInstruction(Instruction *instr)
227 {
228   InstructionNode *treeNode = getTreeNodeForInstr(instr);
229   if (treeNode)
230     {
231       // treeNode has already been constructed for this instruction
232       assert(treeNode->getInstruction() == instr);
233       return treeNode;
234     }
235   
236   // Otherwise, create a new tree node for this instruction.
237   // 
238   treeNode = new InstructionNode(instr);
239   noteTreeNodeForInstr(instr, treeNode);
240   
241   if (instr->getOpcode() == Instruction::Call)
242     { // Operands of call instruction
243       return treeNode;
244     }
245   
246   // If the instruction has more than 2 instruction operands,
247   // then we need to create artificial list nodes to hold them.
248   // (Note that we only count operands that get tree nodes, and not
249   // others such as branch labels for a branch or switch instruction.)
250   //
251   // To do this efficiently, we'll walk all operands, build treeNodes
252   // for all appropriate operands and save them in an array.  We then
253   // insert children at the end, creating list nodes where needed.
254   // As a performance optimization, allocate a child array only
255   // if a fixed array is too small.
256   // 
257   int numChildren = 0;
258   const unsigned int MAX_CHILD = 8;
259   static InstrTreeNode *fixedChildArray[MAX_CHILD];
260   InstrTreeNode **childArray =
261     (instr->getNumOperands() > MAX_CHILD)
262     ? new (InstrTreeNode*)[instr->getNumOperands()] : fixedChildArray;
263   
264   //
265   // Walk the operands of the instruction
266   // 
267   for (Instruction::op_iterator O = instr->op_begin(); O!=instr->op_end(); ++O)
268     {
269       Value* operand = *O;
270       
271       // Check if the operand is a data value, not an branch label, type,
272       // method or module.  If the operand is an address type (i.e., label
273       // or method) that is used in an non-branching operation, e.g., `add'.
274       // that should be considered a data value.
275     
276       // Check latter condition here just to simplify the next IF.
277       bool includeAddressOperand =
278         (isa<BasicBlock>(operand) || isa<Method>(operand))
279         && !instr->isTerminator();
280     
281       if (includeAddressOperand || isa<Instruction>(operand) ||
282           isa<ConstPoolVal>(operand) || isa<MethodArgument>(operand) ||
283           isa<GlobalVariable>(operand))
284         {
285           // This operand is a data value
286         
287           // An instruction that computes the incoming value is added as a
288           // child of the current instruction if:
289           //   the value has only a single use
290           //   AND both instructions are in the same basic block.
291           //   AND the current instruction is not a PHI (because the incoming
292           //            value is conceptually in a predecessor block,
293           //            even though it may be in the same static block)
294           // 
295           // (Note that if the value has only a single use (viz., `instr'),
296           //  the def of the value can be safely moved just before instr
297           //  and therefore it is safe to combine these two instructions.)
298           // 
299           // In all other cases, the virtual register holding the value
300           // is used directly, i.e., made a child of the instruction node.
301           // 
302           InstrTreeNode* opTreeNode;
303           if (isa<Instruction>(operand) && operand->use_size() == 1 &&
304               cast<Instruction>(operand)->getParent() == instr->getParent() &&
305               ! instr->isPHINode() &&
306               instr->getOpcode() != Instruction::Call)
307             {
308               // Recursively create a treeNode for it.
309               opTreeNode = buildTreeForInstruction((Instruction*)operand);
310             }
311           else if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(operand))
312             {
313               // Create a leaf node for a constant
314               opTreeNode = new ConstantNode(CPV);
315             }
316           else
317             {
318               // Create a leaf node for the virtual register
319               opTreeNode = new VRegNode(operand);
320             }
321
322           childArray[numChildren++] = opTreeNode;
323         }
324     }
325   
326   //-------------------------------------------------------------------- 
327   // Add any selected operands as children in the tree.
328   // Certain instructions can have more than 2 in some instances (viz.,
329   // a CALL or a memory access -- LOAD, STORE, and GetElemPtr -- to an
330   // array or struct). Make the operands of every such instruction into
331   // a right-leaning binary tree with the operand nodes at the leaves
332   // and VRegList nodes as internal nodes.
333   //-------------------------------------------------------------------- 
334   
335   InstrTreeNode *parent = treeNode;
336   
337   if (numChildren > 2)
338     {
339       unsigned instrOpcode = treeNode->getInstruction()->getOpcode();
340       assert(instrOpcode == Instruction::PHINode ||
341              instrOpcode == Instruction::Call ||
342              instrOpcode == Instruction::Load ||
343              instrOpcode == Instruction::Store ||
344              instrOpcode == Instruction::GetElementPtr);
345     }
346   
347   // Insert the first child as a direct child
348   if (numChildren >= 1)
349     setLeftChild(parent, childArray[0]);
350
351   int n;
352   
353   // Create a list node for children 2 .. N-1, if any
354   for (n = numChildren-1; n >= 2; n--)
355     {
356       // We have more than two children
357       InstrTreeNode *listNode = new VRegListNode();
358       setRightChild(parent, listNode);
359       setLeftChild(listNode, childArray[numChildren - n]);
360       parent = listNode;
361     }
362   
363   // Now insert the last remaining child (if any).
364   if (numChildren >= 2)
365     {
366       assert(n == 1);
367       setRightChild(parent, childArray[numChildren - 1]);
368     }
369   
370   if (childArray != fixedChildArray)
371     delete [] childArray; 
372   
373   return treeNode;
374 }
375