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