* Pull BasicBlock::pred_* and BasicBlock::succ_* out of BasicBlock.h and into
[oota-llvm.git] / lib / CodeGen / InstrSelection / InstrSelection.cpp
1 // $Id$ -*-c++-*-
2 //***************************************************************************
3 // File:
4 //      InstrSelection.cpp
5 // 
6 // Purpose:
7 //      Machine-independent driver file for instruction selection.
8 //      This file constructs a forest of BURG instruction trees and then
9 //      uses the BURG-generated tree grammar (BURM) to find the optimal
10 //      instruction sequences for a given machine.
11 //      
12 // History:
13 //      7/02/01  -  Vikram Adve  -  Created
14 //**************************************************************************/
15
16
17 #include "llvm/CodeGen/InstrSelection.h"
18 #include "llvm/CodeGen/InstrSelectionSupport.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/InstrForest.h"
21 #include "llvm/CodeGen/MachineCodeForInstruction.h"
22 #include "llvm/CodeGen/MachineCodeForMethod.h"
23 #include "llvm/Target/MachineRegInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/BasicBlock.h"
26 #include "llvm/Method.h"
27 #include "llvm/iPHINode.h"
28 #include "Support/CommandLine.h"
29 #include <iostream>
30 using std::cerr;
31
32 //******************** Internal Data Declarations ************************/
33
34 // Use a static vector to avoid allocating a new one per VM instruction
35 static MachineInstr* minstrVec[MAX_INSTR_PER_VMINSTR];
36   
37
38 enum SelectDebugLevel_t {
39   Select_NoDebugInfo,
40   Select_PrintMachineCode, 
41   Select_DebugInstTrees, 
42   Select_DebugBurgTrees,
43 };
44
45 // Enable Debug Options to be specified on the command line
46 cl::Enum<enum SelectDebugLevel_t> SelectDebugLevel("dselect", cl::NoFlags,
47    "enable instruction selection debugging information",
48    clEnumValN(Select_NoDebugInfo,      "n", "disable debug output"),
49    clEnumValN(Select_PrintMachineCode, "y", "print generated machine code"),
50    clEnumValN(Select_DebugInstTrees,   "i", "print debugging info for instruction selection "),
51    clEnumValN(Select_DebugBurgTrees,   "b", "print burg trees"), 0);
52
53
54 //******************** Forward Function Declarations ***********************/
55
56
57 static bool SelectInstructionsForTree   (InstrTreeNode* treeRoot,
58                                          int goalnt,
59                                          TargetMachine &target);
60
61 static void PostprocessMachineCodeForTree(InstructionNode* instrNode,
62                                           int ruleForNode,
63                                           short* nts,
64                                           TargetMachine &target);
65
66 static void InsertCode4AllPhisInMeth(Method *method, TargetMachine &target);
67
68
69
70 //******************* Externally Visible Functions *************************/
71
72
73 //---------------------------------------------------------------------------
74 // Entry point for instruction selection using BURG.
75 // Returns true if instruction selection failed, false otherwise.
76 //---------------------------------------------------------------------------
77
78 bool
79 SelectInstructionsForMethod(Method* method, TargetMachine &target)
80 {
81   bool failed = false;
82   
83   //
84   // Build the instruction trees to be given as inputs to BURG.
85   // 
86   InstrForest instrForest(method);
87   
88   if (SelectDebugLevel >= Select_DebugInstTrees)
89     {
90       cerr << "\n\n*** Instruction trees for method "
91            << (method->hasName()? method->getName() : "")
92            << "\n\n";
93       instrForest.dump();
94     }
95   
96   //
97   // Invoke BURG instruction selection for each tree
98   // 
99   const std::hash_set<InstructionNode*> &treeRoots = instrForest.getRootSet();
100   for (std::hash_set<InstructionNode*>::const_iterator
101          treeRootIter = treeRoots.begin(); treeRootIter != treeRoots.end();
102        ++treeRootIter)
103     {
104       InstrTreeNode* basicNode = *treeRootIter;
105       
106       // Invoke BURM to label each tree node with a state
107       burm_label(basicNode);
108       
109       if (SelectDebugLevel >= Select_DebugBurgTrees)
110         {
111           printcover(basicNode, 1, 0);
112           cerr << "\nCover cost == " << treecost(basicNode, 1, 0) << "\n\n";
113           printMatches(basicNode);
114         }
115       
116       // Then recursively walk the tree to select instructions
117       if (SelectInstructionsForTree(basicNode, /*goalnt*/1, target))
118         {
119           failed = true;
120           break;
121         }
122     }
123   
124   //
125   // Record instructions in the vector for each basic block
126   // 
127   for (Method::iterator BI = method->begin(); BI != method->end(); ++BI)
128     {
129       MachineCodeForBasicBlock& bbMvec = (*BI)->getMachineInstrVec();
130       for (BasicBlock::iterator II = (*BI)->begin(); II != (*BI)->end(); ++II)
131         {
132           MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(*II);
133           for (unsigned i=0; i < mvec.size(); i++)
134             bbMvec.push_back(mvec[i]);
135         }
136     }
137
138   // Insert phi elimination code -- added by Ruchira
139   InsertCode4AllPhisInMeth(method, target);
140
141   
142   if (SelectDebugLevel >= Select_PrintMachineCode)
143     {
144       cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
145       MachineCodeForMethod::get(method).dump();
146     }
147   
148   return false;
149 }
150
151
152 //*********************** Private Functions *****************************/
153
154
155 //-------------------------------------------------------------------------
156 // Thid method inserts a copy instruction to a predecessor BB as a result
157 // of phi elimination.
158 //-------------------------------------------------------------------------
159
160 void InsertPhiElimInst(BasicBlock *BB, MachineInstr *CpMI) { 
161
162   Instruction *TermInst = (Instruction*)BB->getTerminator();
163   MachineCodeForInstruction &MC4Term = MachineCodeForInstruction::get(TermInst);
164   MachineInstr *FirstMIOfTerm = *( MC4Term.begin() );
165
166   assert( FirstMIOfTerm && "No Machine Instrs for terminator" );
167
168   // get an iterator to machine instructions in the BB
169   MachineCodeForBasicBlock& bbMvec = BB->getMachineInstrVec();
170   MachineCodeForBasicBlock::iterator MCIt =  bbMvec.begin();
171
172   // find the position of first machine instruction generated by the
173   // terminator of this BB
174   for( ; (MCIt != bbMvec.end()) && (*MCIt != FirstMIOfTerm) ; ++MCIt ) ;
175   
176   assert( MCIt != bbMvec.end() && "Start inst of terminator not found");
177
178   // insert the copy instruction just before the first machine instruction
179   // generated for the terminator
180   bbMvec.insert( MCIt , CpMI );
181
182   //cerr << "\nPhiElimination copy inst: " <<   *CopyInstVec[0];
183
184 }
185
186 #if 0
187 //-------------------------------------------------------------------------
188 // This method inserts phi elimination code for all BBs in a method
189 //-------------------------------------------------------------------------
190 void InsertCode4AllPhisInMeth(Method *method, TargetMachine &target) {
191
192
193   // for all basic blocks in method
194   //
195   for (Method::iterator BI = method->begin(); BI != method->end(); ++BI) {
196
197     BasicBlock *BB = *BI;
198     const BasicBlock::InstListType &InstList = BB->getInstList();
199     BasicBlock::InstListType::const_iterator  IIt = InstList.begin();
200
201     // for all instructions in the basic block
202     //
203     for( ; IIt != InstList.end(); ++IIt ) {
204
205       if( (*IIt)->getOpcode() == Instruction::PHINode ) {
206
207         PHINode *PN = (PHINode *) (*IIt);
208
209         // for each incoming value of the phi, insert phi elimination
210         //
211         for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
212
213           // insert the copy instruction to the predecessor BB
214
215           std::vector<MachineInstr*> CopyInstVec;
216
217           MachineInstr *CpMI =
218             target.getRegInfo().cpValue2Value(PN->getIncomingValue(i), PN);
219
220           InsertPhiElimInst( PN->getIncomingBlock(i), CpMI);
221         }
222       }
223       else break;   // since PHI nodes can only be at the top
224       
225     }  // for each Phi Instr in BB
226
227   } // for all BBs in method
228
229 }
230 #endif
231
232
233 //-------------------------------------------------------------------------
234 // This method inserts phi elimination code for all BBs in a method
235 //-------------------------------------------------------------------------
236 void InsertCode4AllPhisInMeth(Method *method, TargetMachine &target) {
237
238
239   // for all basic blocks in method
240   //
241   for (Method::iterator BI = method->begin(); BI != method->end(); ++BI) {
242
243     BasicBlock *BB = *BI;
244     const BasicBlock::InstListType &InstList = BB->getInstList();
245     BasicBlock::InstListType::const_iterator  IIt = InstList.begin();
246
247     // for all instructions in the basic block
248     //
249     for( ; IIt != InstList.end(); ++IIt ) {
250
251       if( (*IIt)->getOpcode() == Instruction::PHINode ) {
252
253         PHINode *PN = (PHINode *) (*IIt);
254
255         Value *PhiCpRes = new Value(PN->getType(), PN->getValueType(),"PhiCp:");
256
257         // for each incoming value of the phi, insert phi elimination
258         //
259         for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
260           // insert the copy instruction to the predecessor BB
261           MachineInstr *CpMI =
262             target.getRegInfo().cpValue2Value(PN->getIncomingValue(i),
263                                               PhiCpRes);
264
265           InsertPhiElimInst(PN->getIncomingBlock(i), CpMI);
266         }
267
268         MachineInstr *CpMI2 =
269           target.getRegInfo().cpValue2Value(PhiCpRes, PN);
270
271         // get an iterator to machine instructions in the BB
272         MachineCodeForBasicBlock& bbMvec = BB->getMachineInstrVec();
273
274         bbMvec.insert( bbMvec.begin(),  CpMI2);
275       }
276       else break;   // since PHI nodes can only be at the top
277       
278     }  // for each Phi Instr in BB
279
280   } // for all BBs in method
281
282 }
283
284
285 //---------------------------------------------------------------------------
286 // Function PostprocessMachineCodeForTree
287 // 
288 // Apply any final cleanups to machine code for the root of a subtree
289 // after selection for all its children has been completed.
290 //---------------------------------------------------------------------------
291
292 static void
293 PostprocessMachineCodeForTree(InstructionNode* instrNode,
294                               int ruleForNode,
295                               short* nts,
296                               TargetMachine &target)
297 {
298   // Fix up any constant operands in the machine instructions to either
299   // use an immediate field or to load the constant into a register
300   // Walk backwards and use direct indexes to allow insertion before current
301   // 
302   Instruction* vmInstr = instrNode->getInstruction();
303   MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
304   for (int i = (int) mvec.size()-1; i >= 0; i--)
305     {
306       std::vector<MachineInstr*> loadConstVec =
307         FixConstantOperandsForInstr(vmInstr, mvec[i], target);
308       
309       if (loadConstVec.size() > 0)
310         mvec.insert(mvec.begin()+i, loadConstVec.begin(), loadConstVec.end());
311     }
312 }
313
314 //---------------------------------------------------------------------------
315 // Function SelectInstructionsForTree 
316 // 
317 // Recursively walk the tree to select instructions.
318 // Do this top-down so that child instructions can exploit decisions
319 // made at the child instructions.
320 // 
321 // E.g., if br(setle(reg,const)) decides the constant is 0 and uses
322 // a branch-on-integer-register instruction, then the setle node
323 // can use that information to avoid generating the SUBcc instruction.
324 //
325 // Note that this cannot be done bottom-up because setle must do this
326 // only if it is a child of the branch (otherwise, the result of setle
327 // may be used by multiple instructions).
328 //---------------------------------------------------------------------------
329
330 bool
331 SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt,
332                           TargetMachine &target)
333 {
334   // Get the rule that matches this node.
335   // 
336   int ruleForNode = burm_rule(treeRoot->state, goalnt);
337   
338   if (ruleForNode == 0)
339     {
340       cerr << "Could not match instruction tree for instr selection\n";
341       assert(0);
342       return true;
343     }
344   
345   // Get this rule's non-terminals and the corresponding child nodes (if any)
346   // 
347   short *nts = burm_nts[ruleForNode];
348   
349   // First, select instructions for the current node and rule.
350   // (If this is a list node, not an instruction, then skip this step).
351   // This function is specific to the target architecture.
352   // 
353   if (treeRoot->opLabel != VRegListOp)
354     {
355       InstructionNode* instrNode = (InstructionNode*)treeRoot;
356       assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
357       
358       unsigned N = GetInstructionsByRule(instrNode, ruleForNode, nts, target,
359                                          minstrVec);
360       assert(N <= MAX_INSTR_PER_VMINSTR);
361       MachineCodeForInstruction &mvec = 
362         MachineCodeForInstruction::get(instrNode->getInstruction());
363       mvec.insert(mvec.end(), minstrVec, minstrVec+N); 
364     }
365   
366   // Then, recursively compile the child nodes, if any.
367   // 
368   if (nts[0])
369     { // i.e., there is at least one kid
370       InstrTreeNode* kids[2];
371       int currentRule = ruleForNode;
372       burm_kids(treeRoot, currentRule, kids);
373     
374       // First skip over any chain rules so that we don't visit
375       // the current node again.
376       // 
377       while (ThisIsAChainRule(currentRule))
378         {
379           currentRule = burm_rule(treeRoot->state, nts[0]);
380           nts = burm_nts[currentRule];
381           burm_kids(treeRoot, currentRule, kids);
382         }
383       
384       // Now we have the first non-chain rule so we have found
385       // the actual child nodes.  Recursively compile them.
386       // 
387       for (int i = 0; nts[i]; i++)
388         {
389           assert(i < 2);
390           InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
391           if (nodeType == InstrTreeNode::NTVRegListNode ||
392               nodeType == InstrTreeNode::NTInstructionNode)
393             {
394               if (SelectInstructionsForTree(kids[i], nts[i], target))
395                 return true;                    // failure
396             }
397         }
398     }
399   
400   // Finally, do any postprocessing on this node after its children
401   // have been translated
402   // 
403   if (treeRoot->opLabel != VRegListOp)
404     {
405       InstructionNode* instrNode = (InstructionNode*)treeRoot;
406       PostprocessMachineCodeForTree(instrNode, ruleForNode, nts, target);
407     }
408   
409   return false;                         // success
410 }
411