Tell PassManager that this pass does not invalidate the CFG so that dominator
[oota-llvm.git] / lib / Target / SparcV9 / InstrSelection / InstrSelection.cpp
1 //===- InstrSelection.cpp - Machine Independant Inst Selection Driver -----===//
2 //
3 // Machine-independent driver file for instruction selection.  This file
4 // constructs a forest of BURG instruction trees and then uses the
5 // BURG-generated tree grammar (BURM) to find the optimal instruction sequences
6 // for a given machine.
7 //      
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/CodeGen/InstrSelection.h"
11 #include "llvm/CodeGen/InstrSelectionSupport.h"
12 #include "llvm/CodeGen/InstrForest.h"
13 #include "llvm/CodeGen/MachineCodeForInstruction.h"
14 #include "llvm/CodeGen/MachineCodeForBasicBlock.h"
15 #include "llvm/CodeGen/MachineCodeForMethod.h"
16 #include "llvm/Target/MachineRegInfo.h"
17 #include "llvm/Target/TargetMachine.h"
18 #include "llvm/Function.h"
19 #include "llvm/iPHINode.h"
20 #include "llvm/Pass.h"
21 #include "Support/CommandLine.h"
22 #include "Support/LeakDetector.h"
23 using std::cerr;
24 using std::vector;
25
26 namespace {
27   //===--------------------------------------------------------------------===//
28   // SelectDebugLevel - Allow command line control over debugging.
29   //
30   enum SelectDebugLevel_t {
31     Select_NoDebugInfo,
32     Select_PrintMachineCode, 
33     Select_DebugInstTrees, 
34     Select_DebugBurgTrees,
35   };
36   
37   // Enable Debug Options to be specified on the command line
38   cl::opt<SelectDebugLevel_t>
39   SelectDebugLevel("dselect", cl::Hidden,
40                    cl::desc("enable instruction selection debug information"),
41                    cl::values(
42      clEnumValN(Select_NoDebugInfo,      "n", "disable debug output"),
43      clEnumValN(Select_PrintMachineCode, "y", "print generated machine code"),
44      clEnumValN(Select_DebugInstTrees,   "i",
45                 "print debugging info for instruction selection"),
46      clEnumValN(Select_DebugBurgTrees,   "b", "print burg trees"),
47                               0));
48
49
50   //===--------------------------------------------------------------------===//
51   //  InstructionSelection Pass
52   //
53   // This is the actual pass object that drives the instruction selection
54   // process.
55   //
56   class InstructionSelection : public FunctionPass {
57     TargetMachine &Target;
58     void InsertCodeForPhis(Function &F);
59     void InsertPhiElimInstructions(BasicBlock *BB,
60                                    const vector<MachineInstr*>& CpVec);
61     void SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt);
62     void PostprocessMachineCodeForTree(InstructionNode* instrNode,
63                                        int ruleForNode, short* nts);
64   public:
65     InstructionSelection(TargetMachine &T) : Target(T) {}
66
67     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68       AU.setPreservesCFG();
69     }
70     
71     bool runOnFunction(Function &F);
72   };
73 }
74
75 // Register the pass...
76 static RegisterLLC<InstructionSelection>
77 X("instselect", "Instruction Selection", createInstructionSelectionPass);
78
79 TmpInstruction::TmpInstruction(Value *s1, Value *s2, const std::string &name)
80   : Instruction(s1->getType(), Instruction::UserOp1, name) {
81   Operands.push_back(Use(s1, this));  // s1 must be nonnull
82   if (s2) {
83     Operands.push_back(Use(s2, this));
84   }
85
86   // TmpInstructions should not be garbage checked.
87   LeakDetector::removeGarbageObject(this);
88 }
89   
90 // Constructor that requires the type of the temporary to be specified.
91 // Both S1 and S2 may be NULL.(
92 TmpInstruction::TmpInstruction(const Type *Ty, Value *s1, Value* s2,
93                                const std::string &name)
94   : Instruction(Ty, Instruction::UserOp1, name) {
95   if (s1) { Operands.push_back(Use(s1, this)); }
96   if (s2) { Operands.push_back(Use(s2, this)); }
97
98   // TmpInstructions should not be garbage checked.
99   LeakDetector::removeGarbageObject(this);
100 }
101
102
103 bool InstructionSelection::runOnFunction(Function &F)
104 {
105   //
106   // Build the instruction trees to be given as inputs to BURG.
107   // 
108   InstrForest instrForest(&F);
109   
110   if (SelectDebugLevel >= Select_DebugInstTrees)
111     {
112       cerr << "\n\n*** Input to instruction selection for function "
113            << F.getName() << "\n\n" << F
114            << "\n\n*** Instruction trees for function "
115            << F.getName() << "\n\n";
116       instrForest.dump();
117     }
118   
119   //
120   // Invoke BURG instruction selection for each tree
121   // 
122   for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
123        RI != instrForest.roots_end(); ++RI)
124     {
125       InstructionNode* basicNode = *RI;
126       assert(basicNode->parent() == NULL && "A `root' node has a parent?"); 
127       
128       // Invoke BURM to label each tree node with a state
129       burm_label(basicNode);
130       
131       if (SelectDebugLevel >= Select_DebugBurgTrees)
132         {
133           printcover(basicNode, 1, 0);
134           cerr << "\nCover cost == " << treecost(basicNode, 1, 0) << "\n\n";
135           printMatches(basicNode);
136         }
137       
138       // Then recursively walk the tree to select instructions
139       SelectInstructionsForTree(basicNode, /*goalnt*/1);
140     }
141   
142   //
143   // Record instructions in the vector for each basic block
144   // 
145   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI)
146     for (BasicBlock::iterator II = BI->begin(); II != BI->end(); ++II) {
147       MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(II);
148       MachineCodeForBasicBlock &MCBB = MachineCodeForBasicBlock::get(BI);
149       MCBB.insert(MCBB.end(), mvec.begin(), mvec.end());
150     }
151
152   // Insert phi elimination code
153   InsertCodeForPhis(F);
154   
155   if (SelectDebugLevel >= Select_PrintMachineCode)
156     {
157       cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
158       MachineCodeForMethod::get(&F).dump();
159     }
160   
161   return true;
162 }
163
164
165 //-------------------------------------------------------------------------
166 // This method inserts phi elimination code for all BBs in a method
167 //-------------------------------------------------------------------------
168
169 void
170 InstructionSelection::InsertCodeForPhis(Function &F)
171 {
172   // for all basic blocks in function
173   //
174   for (Function::iterator BB = F.begin(); BB != F.end(); ++BB) {
175     BasicBlock::InstListType &InstList = BB->getInstList();
176     for (BasicBlock::iterator IIt = InstList.begin();
177          PHINode *PN = dyn_cast<PHINode>(&*IIt); ++IIt) {
178       // FIXME: This is probably wrong...
179       Value *PhiCpRes = new PHINode(PN->getType(), "PhiCp:");
180
181       // The leak detector shouldn't track these nodes.  They are not garbage,
182       // even though their parent field is never filled in.
183       //
184       LeakDetector::removeGarbageObject(PhiCpRes);
185
186       // for each incoming value of the phi, insert phi elimination
187       //
188       for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
189         // insert the copy instruction to the predecessor BB
190         vector<MachineInstr*> mvec, CpVec;
191         Target.getRegInfo().cpValue2Value(PN->getIncomingValue(i), PhiCpRes,
192                                           mvec);
193         for (vector<MachineInstr*>::iterator MI=mvec.begin();
194              MI != mvec.end(); ++MI) {
195           vector<MachineInstr*> CpVec2 =
196             FixConstantOperandsForInstr(PN, *MI, Target);
197           CpVec2.push_back(*MI);
198           CpVec.insert(CpVec.end(), CpVec2.begin(), CpVec2.end());
199         }
200         
201         InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
202       }
203       
204       vector<MachineInstr*> mvec;
205       Target.getRegInfo().cpValue2Value(PhiCpRes, PN, mvec);
206       
207       // get an iterator to machine instructions in the BB
208       MachineCodeForBasicBlock& bbMvec = MachineCodeForBasicBlock::get(BB);
209       
210       bbMvec.insert(bbMvec.begin(), mvec.begin(), mvec.end());
211     }  // for each Phi Instr in BB
212   } // for all BBs in function
213 }
214
215 //-------------------------------------------------------------------------
216 // Thid method inserts a copy instruction to a predecessor BB as a result
217 // of phi elimination.
218 //-------------------------------------------------------------------------
219
220 void
221 InstructionSelection::InsertPhiElimInstructions(BasicBlock *BB,
222                                                 const vector<MachineInstr*>& CpVec)
223
224   Instruction *TermInst = (Instruction*)BB->getTerminator();
225   MachineCodeForInstruction &MC4Term = MachineCodeForInstruction::get(TermInst);
226   MachineInstr *FirstMIOfTerm = MC4Term.front();
227   
228   assert (FirstMIOfTerm && "No Machine Instrs for terminator");
229   
230   MachineCodeForBasicBlock &bbMvec = MachineCodeForBasicBlock::get(BB);
231
232   // find the position of first machine instruction generated by the
233   // terminator of this BB
234   MachineCodeForBasicBlock::iterator MCIt =
235     std::find(bbMvec.begin(), bbMvec.end(), FirstMIOfTerm);
236
237   assert( MCIt != bbMvec.end() && "Start inst of terminator not found");
238   
239   // insert the copy instructions just before the first machine instruction
240   // generated for the terminator
241   bbMvec.insert(MCIt, CpVec.begin(), CpVec.end());
242 }
243
244
245 //---------------------------------------------------------------------------
246 // Function SelectInstructionsForTree 
247 // 
248 // Recursively walk the tree to select instructions.
249 // Do this top-down so that child instructions can exploit decisions
250 // made at the child instructions.
251 // 
252 // E.g., if br(setle(reg,const)) decides the constant is 0 and uses
253 // a branch-on-integer-register instruction, then the setle node
254 // can use that information to avoid generating the SUBcc instruction.
255 //
256 // Note that this cannot be done bottom-up because setle must do this
257 // only if it is a child of the branch (otherwise, the result of setle
258 // may be used by multiple instructions).
259 //---------------------------------------------------------------------------
260
261 void 
262 InstructionSelection::SelectInstructionsForTree(InstrTreeNode* treeRoot,
263                                                 int goalnt)
264 {
265   // Get the rule that matches this node.
266   // 
267   int ruleForNode = burm_rule(treeRoot->state, goalnt);
268   
269   if (ruleForNode == 0) {
270     cerr << "Could not match instruction tree for instr selection\n";
271     abort();
272   }
273   
274   // Get this rule's non-terminals and the corresponding child nodes (if any)
275   // 
276   short *nts = burm_nts[ruleForNode];
277   
278   // First, select instructions for the current node and rule.
279   // (If this is a list node, not an instruction, then skip this step).
280   // This function is specific to the target architecture.
281   // 
282   if (treeRoot->opLabel != VRegListOp)
283     {
284       vector<MachineInstr*> minstrVec;
285       
286       InstructionNode* instrNode = (InstructionNode*)treeRoot;
287       assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
288       
289       GetInstructionsByRule(instrNode, ruleForNode, nts, Target, minstrVec);
290       
291       MachineCodeForInstruction &mvec = 
292         MachineCodeForInstruction::get(instrNode->getInstruction());
293       mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
294     }
295   
296   // Then, recursively compile the child nodes, if any.
297   // 
298   if (nts[0])
299     { // i.e., there is at least one kid
300       InstrTreeNode* kids[2];
301       int currentRule = ruleForNode;
302       burm_kids(treeRoot, currentRule, kids);
303     
304       // First skip over any chain rules so that we don't visit
305       // the current node again.
306       // 
307       while (ThisIsAChainRule(currentRule))
308         {
309           currentRule = burm_rule(treeRoot->state, nts[0]);
310           nts = burm_nts[currentRule];
311           burm_kids(treeRoot, currentRule, kids);
312         }
313       
314       // Now we have the first non-chain rule so we have found
315       // the actual child nodes.  Recursively compile them.
316       // 
317       for (unsigned i = 0; nts[i]; i++)
318         {
319           assert(i < 2);
320           InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
321           if (nodeType == InstrTreeNode::NTVRegListNode ||
322               nodeType == InstrTreeNode::NTInstructionNode)
323             SelectInstructionsForTree(kids[i], nts[i]);
324         }
325     }
326   
327   // Finally, do any postprocessing on this node after its children
328   // have been translated
329   // 
330   if (treeRoot->opLabel != VRegListOp)
331     PostprocessMachineCodeForTree((InstructionNode*)treeRoot, ruleForNode, nts);
332 }
333
334 //---------------------------------------------------------------------------
335 // Function PostprocessMachineCodeForTree
336 // 
337 // Apply any final cleanups to machine code for the root of a subtree
338 // after selection for all its children has been completed.
339 //
340 void
341 InstructionSelection::PostprocessMachineCodeForTree(InstructionNode* instrNode,
342                                                     int ruleForNode,
343                                                     short* nts) 
344 {
345   // Fix up any constant operands in the machine instructions to either
346   // use an immediate field or to load the constant into a register
347   // Walk backwards and use direct indexes to allow insertion before current
348   // 
349   Instruction* vmInstr = instrNode->getInstruction();
350   MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
351   for (unsigned i = mvec.size(); i != 0; --i)
352     {
353       vector<MachineInstr*> loadConstVec =
354         FixConstantOperandsForInstr(vmInstr, mvec[i-1], Target);
355       
356       mvec.insert(mvec.begin()+i-1, loadConstVec.begin(), loadConstVec.end());
357     }
358 }
359
360
361
362 //===----------------------------------------------------------------------===//
363 // createInstructionSelectionPass - Public entrypoint for instruction selection
364 // and this file as a whole...
365 //
366 Pass *createInstructionSelectionPass(TargetMachine &T) {
367   return new InstructionSelection(T);
368 }
369