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