Added LLVM project notice to the top of every C++ source file.
[oota-llvm.git] / lib / CodeGen / InstrSelection / InstrForest.cpp
1 //===-- InstrForest.cpp - Build instruction forest for inst selection -----===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
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 target 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 //===----------------------------------------------------------------------===//
21
22 #include "llvm/CodeGen/InstrForest.h"
23 #include "llvm/CodeGen/MachineCodeForInstruction.h"
24 #include "llvm/Function.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/iMemory.h"
27 #include "llvm/Constant.h"
28 #include "llvm/Type.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "Support/STLExtras.h"
31 #include "Config/alloca.h"
32
33 //------------------------------------------------------------------------ 
34 // class InstrTreeNode
35 //------------------------------------------------------------------------ 
36
37 void
38 InstrTreeNode::dump(int dumpChildren, int indent) const
39 {
40   dumpNode(indent);
41   
42   if (dumpChildren)
43     {
44       if (LeftChild)
45         LeftChild->dump(dumpChildren, indent+1);
46       if (RightChild)
47         RightChild->dump(dumpChildren, indent+1);
48     }
49 }
50
51
52 InstructionNode::InstructionNode(Instruction* I)
53   : InstrTreeNode(NTInstructionNode, I),
54     codeIsFoldedIntoParent(false)
55 {
56   opLabel = I->getOpcode();
57
58   // Distinguish special cases of some instructions such as Ret and Br
59   // 
60   if (opLabel == Instruction::Ret && cast<ReturnInst>(I)->getReturnValue())
61     {
62       opLabel = RetValueOp;                      // ret(value) operation
63     }
64   else if (opLabel ==Instruction::Br && !cast<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::GetElementPtr &&
77            cast<GetElementPtrInst>(I)->hasIndices())
78     {
79       opLabel = opLabel + 100;           // getElem with index vector
80     }
81   else if (opLabel == Instruction::Xor &&
82            BinaryOperator::isNot(I))
83     {
84       opLabel = (I->getType() == Type::BoolTy)?  NotOp  // boolean Not operator
85                                               : BNotOp; // bitwise Not operator
86     }
87   else if (opLabel == Instruction::And ||
88            opLabel == Instruction::Or ||
89            opLabel == Instruction::Xor)
90     {
91       // Distinguish bitwise operators from logical operators!
92       if (I->getType() != Type::BoolTy)
93         opLabel = opLabel + 100;         // bitwise operator
94     }
95   else if (opLabel == Instruction::Cast)
96     {
97       const Type *ITy = I->getType();
98       switch(ITy->getPrimitiveID())
99         {
100         case Type::BoolTyID:    opLabel = ToBoolTy;    break;
101         case Type::UByteTyID:   opLabel = ToUByteTy;   break;
102         case Type::SByteTyID:   opLabel = ToSByteTy;   break;
103         case Type::UShortTyID:  opLabel = ToUShortTy;  break;
104         case Type::ShortTyID:   opLabel = ToShortTy;   break;
105         case Type::UIntTyID:    opLabel = ToUIntTy;    break;
106         case Type::IntTyID:     opLabel = ToIntTy;     break;
107         case Type::ULongTyID:   opLabel = ToULongTy;   break;
108         case Type::LongTyID:    opLabel = ToLongTy;    break;
109         case Type::FloatTyID:   opLabel = ToFloatTy;   break;
110         case Type::DoubleTyID:  opLabel = ToDoubleTy;  break;
111         case Type::ArrayTyID:   opLabel = ToArrayTy;   break;
112         case Type::PointerTyID: opLabel = ToPointerTy; break;
113         default:
114           // Just use `Cast' opcode otherwise. It's probably ignored.
115           break;
116         }
117     }
118 }
119
120
121 void
122 InstructionNode::dumpNode(int indent) const
123 {
124   for (int i=0; i < indent; i++)
125     std::cerr << "    ";
126   std::cerr << getInstruction()->getOpcodeName()
127             << " [label " << getOpLabel() << "]" << "\n";
128 }
129
130
131 void
132 VRegListNode::dumpNode(int indent) const
133 {
134   for (int i=0; i < indent; i++)
135     std::cerr << "    ";
136   
137   std::cerr << "List" << "\n";
138 }
139
140
141 void
142 VRegNode::dumpNode(int indent) const
143 {
144   for (int i=0; i < indent; i++)
145     std::cerr << "    ";
146   
147   std::cerr << "VReg " << getValue() << "\t(type "
148             << (int) getValue()->getValueType() << ")" << "\n";
149 }
150
151 void
152 ConstantNode::dumpNode(int indent) const
153 {
154   for (int i=0; i < indent; i++)
155     std::cerr << "    ";
156   
157   std::cerr << "Constant " << getValue() << "\t(type "
158             << (int) getValue()->getValueType() << ")" << "\n";
159 }
160
161 void
162 LabelNode::dumpNode(int indent) const
163 {
164   for (int i=0; i < indent; i++)
165     std::cerr << "    ";
166   
167   std::cerr << "Label " << getValue() << "\n";
168 }
169
170 //------------------------------------------------------------------------
171 // class InstrForest
172 // 
173 // A forest of instruction trees, usually for a single method.
174 //------------------------------------------------------------------------ 
175
176 InstrForest::InstrForest(Function *F)
177 {
178   for (Function::iterator BB = F->begin(), FE = F->end(); BB != FE; ++BB) {
179     for(BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
180       buildTreeForInstruction(I);
181   }
182 }
183
184 InstrForest::~InstrForest()
185 {
186   for_each(treeRoots.begin(), treeRoots.end(), deleter<InstructionNode>);
187 }
188
189 void
190 InstrForest::dump() const
191 {
192   for (const_root_iterator I = roots_begin(); I != roots_end(); ++I)
193     (*I)->dump(/*dumpChildren*/ 1, /*indent*/ 0);
194 }
195
196 inline void
197 InstrForest::eraseRoot(InstructionNode* node)
198 {
199   for (RootSet::reverse_iterator RI=treeRoots.rbegin(), RE=treeRoots.rend();
200        RI != RE; ++RI)
201     if (*RI == node)
202       treeRoots.erase(RI.base()-1);
203 }
204
205 inline void
206 InstrForest::noteTreeNodeForInstr(Instruction *instr,
207                                   InstructionNode *treeNode)
208 {
209   (*this)[instr] = treeNode;
210   treeRoots.push_back(treeNode);        // mark node as root of a new tree
211 }
212
213
214 inline void
215 InstrForest::setLeftChild(InstrTreeNode *parent, InstrTreeNode *child)
216 {
217   parent->LeftChild = child;
218   child->Parent = parent;
219   if (InstructionNode* instrNode = dyn_cast<InstructionNode>(child))
220     eraseRoot(instrNode); // no longer a tree root
221 }
222
223 inline void
224 InstrForest::setRightChild(InstrTreeNode *parent, InstrTreeNode *child)
225 {
226   parent->RightChild = child;
227   child->Parent = parent;
228   if (InstructionNode* instrNode = dyn_cast<InstructionNode>(child))
229     eraseRoot(instrNode); // no longer a tree root
230 }
231
232
233 InstructionNode*
234 InstrForest::buildTreeForInstruction(Instruction *instr)
235 {
236   InstructionNode *treeNode = getTreeNodeForInstr(instr);
237   if (treeNode)
238     {
239       // treeNode has already been constructed for this instruction
240       assert(treeNode->getInstruction() == instr);
241       return treeNode;
242     }
243   
244   // Otherwise, create a new tree node for this instruction.
245   // 
246   treeNode = new InstructionNode(instr);
247   noteTreeNodeForInstr(instr, treeNode);
248   
249   if (instr->getOpcode() == Instruction::Call)
250     { // Operands of call instruction
251       return treeNode;
252     }
253   
254   // If the instruction has more than 2 instruction operands,
255   // then we need to create artificial list nodes to hold them.
256   // (Note that we only count operands that get tree nodes, and not
257   // others such as branch labels for a branch or switch instruction.)
258   //
259   // To do this efficiently, we'll walk all operands, build treeNodes
260   // for all appropriate operands and save them in an array.  We then
261   // insert children at the end, creating list nodes where needed.
262   // As a performance optimization, allocate a child array only
263   // if a fixed array is too small.
264   // 
265   int numChildren = 0;
266   InstrTreeNode** childArray = new InstrTreeNode*[instr->getNumOperands()];
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         (isa<BasicBlock>(operand) || isa<Function>(operand))
283         && !instr->isTerminator();
284     
285       if (includeAddressOperand || isa<Instruction>(operand) ||
286           isa<Constant>(operand) || isa<Argument>(operand) ||
287           isa<GlobalVariable>(operand))
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 (isa<Instruction>(operand) && operand->hasOneUse() &&
308               cast<Instruction>(operand)->getParent() == instr->getParent() &&
309               instr->getOpcode() != Instruction::PHI &&
310               instr->getOpcode() != Instruction::Call)
311             {
312               // Recursively create a treeNode for it.
313               opTreeNode = buildTreeForInstruction((Instruction*)operand);
314             }
315           else if (Constant *CPV = dyn_cast<Constant>(operand))
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::PHI ||
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   delete [] childArray;
375   return treeNode;
376 }