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