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