Moved class MachineCodeForBasicBlock to MachineCodeForBasicBlock.h.
[oota-llvm.git] / lib / Target / SparcV9 / 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/InstrForest.h"
20 #include "llvm/CodeGen/MachineCodeForInstruction.h"
21 #include "llvm/CodeGen/MachineCodeForBasicBlock.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/Function.h"
27 #include "llvm/iPHINode.h"
28 #include "Support/CommandLine.h"
29 #include <iostream>
30 using std::cerr;
31 using std::vector;
32
33 //******************** Internal Data Declarations ************************/
34
35
36 enum SelectDebugLevel_t {
37   Select_NoDebugInfo,
38   Select_PrintMachineCode, 
39   Select_DebugInstTrees, 
40   Select_DebugBurgTrees,
41 };
42
43 // Enable Debug Options to be specified on the command line
44 cl::Enum<enum SelectDebugLevel_t> SelectDebugLevel("dselect", cl::Hidden,
45    "enable instruction selection debugging information",
46    clEnumValN(Select_NoDebugInfo,      "n", "disable debug output"),
47    clEnumValN(Select_PrintMachineCode, "y", "print generated machine code"),
48    clEnumValN(Select_DebugInstTrees,   "i", "print debugging info for instruction selection "),
49    clEnumValN(Select_DebugBurgTrees,   "b", "print burg trees"), 0);
50
51
52 //******************** Forward Function Declarations ***********************/
53
54
55 static bool SelectInstructionsForTree   (InstrTreeNode* treeRoot,
56                                          int goalnt,
57                                          TargetMachine &target);
58
59 static void PostprocessMachineCodeForTree(InstructionNode* instrNode,
60                                           int ruleForNode,
61                                           short* nts,
62                                           TargetMachine &target);
63
64 static void InsertCode4AllPhisInMeth(Function *F, TargetMachine &target);
65
66
67
68 //******************* Externally Visible Functions *************************/
69
70
71 //---------------------------------------------------------------------------
72 // Entry point for instruction selection using BURG.
73 // Returns true if instruction selection failed, false otherwise.
74 //---------------------------------------------------------------------------
75
76 bool
77 SelectInstructionsForMethod(Function *F, TargetMachine &target)
78 {
79   bool failed = false;
80   
81   //
82   // Build the instruction trees to be given as inputs to BURG.
83   // 
84   InstrForest instrForest(F);
85   
86   if (SelectDebugLevel >= Select_DebugInstTrees)
87     {
88       cerr << "\n\n*** Input to instruction selection for function "
89            << F->getName() << "\n\n";
90       F->dump();
91       
92       cerr << "\n\n*** Instruction trees for function "
93            << F->getName() << "\n\n";
94       instrForest.dump();
95     }
96   
97   //
98   // Invoke BURG instruction selection for each tree
99   // 
100   for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
101        RI != instrForest.roots_end(); ++RI)
102     {
103       InstructionNode* basicNode = *RI;
104       assert(basicNode->parent() == NULL && "A `root' node has a parent?"); 
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 (Function::iterator BI = F->begin(), BE = F->end(); BI != BE; ++BI)
128     for (BasicBlock::iterator II = BI->begin(); II != BI->end(); ++II) {
129       MachineCodeForInstruction &mvec =MachineCodeForInstruction::get(II);
130       for (unsigned i=0; i < mvec.size(); i++)
131         MachineCodeForBasicBlock::get(BI).push_back(mvec[i]);
132     }
133
134   // Insert phi elimination code -- added by Ruchira
135   InsertCode4AllPhisInMeth(F, target);
136
137   
138   if (SelectDebugLevel >= Select_PrintMachineCode)
139     {
140       cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
141       MachineCodeForMethod::get(F).dump();
142     }
143   
144   return false;
145 }
146
147
148 //*********************** Private Functions *****************************/
149
150
151 //-------------------------------------------------------------------------
152 // Thid method inserts a copy instruction to a predecessor BB as a result
153 // of phi elimination.
154 //-------------------------------------------------------------------------
155
156 void
157 InsertPhiElimInstructions(BasicBlock *BB, const std::vector<MachineInstr*>& CpVec)
158
159   Instruction *TermInst = (Instruction*)BB->getTerminator();
160   MachineCodeForInstruction &MC4Term =MachineCodeForInstruction::get(TermInst);
161   MachineInstr *FirstMIOfTerm = *( MC4Term.begin() );
162   
163   assert( FirstMIOfTerm && "No Machine Instrs for terminator" );
164   
165   // get an iterator to machine instructions in the BB
166   MachineCodeForBasicBlock& bbMvec = MachineCodeForBasicBlock::get(BB);
167   MachineCodeForBasicBlock::iterator MCIt =  bbMvec.begin();
168   
169   // find the position of first machine instruction generated by the
170   // terminator of this BB
171   for( ; (MCIt != bbMvec.end()) && (*MCIt != FirstMIOfTerm) ; ++MCIt )
172     ;
173   assert( MCIt != bbMvec.end() && "Start inst of terminator not found");
174   
175   // insert the copy instructions just before the first machine instruction
176   // generated for the terminator
177   bbMvec.insert(MCIt, CpVec.begin(), CpVec.end());
178   
179   //cerr << "\nPhiElimination copy inst: " <<   *CopyInstVec[0];
180 }
181
182
183 //-------------------------------------------------------------------------
184 // This method inserts phi elimination code for all BBs in a method
185 //-------------------------------------------------------------------------
186
187 void
188 InsertCode4AllPhisInMeth(Function *F, TargetMachine &target)
189 {
190   // for all basic blocks in function
191   //
192   for (Function::iterator BB = F->begin(); BB != F->end(); ++BB) {
193     BasicBlock::InstListType &InstList = BB->getInstList();
194     for (BasicBlock::iterator IIt = InstList.begin();
195          PHINode *PN = dyn_cast<PHINode>(&*IIt); ++IIt) {
196       // FIXME: This is probably wrong...
197       Value *PhiCpRes = new PHINode(PN->getType(), "PhiCp:");
198         
199       // for each incoming value of the phi, insert phi elimination
200       //
201       for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
202         // insert the copy instruction to the predecessor BB
203         vector<MachineInstr*> mvec, CpVec;
204         target.getRegInfo().cpValue2Value(PN->getIncomingValue(i), PhiCpRes,
205                                           mvec);
206         for (vector<MachineInstr*>::iterator MI=mvec.begin();
207              MI != mvec.end(); ++MI) {
208           vector<MachineInstr*> CpVec2 =
209             FixConstantOperandsForInstr(PN, *MI, target);
210           CpVec2.push_back(*MI);
211           CpVec.insert(CpVec.end(), CpVec2.begin(), CpVec2.end());
212         }
213         
214         InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
215       }
216       
217       vector<MachineInstr*> mvec;
218       target.getRegInfo().cpValue2Value(PhiCpRes, PN, mvec);
219       
220       // get an iterator to machine instructions in the BB
221       MachineCodeForBasicBlock& bbMvec = MachineCodeForBasicBlock::get(BB);
222       
223       bbMvec.insert(bbMvec.begin(), mvec.begin(), mvec.end());
224     }  // for each Phi Instr in BB
225   } // for all BBs in function
226 }
227
228
229 //---------------------------------------------------------------------------
230 // Function PostprocessMachineCodeForTree
231 // 
232 // Apply any final cleanups to machine code for the root of a subtree
233 // after selection for all its children has been completed.
234 //---------------------------------------------------------------------------
235
236 static void
237 PostprocessMachineCodeForTree(InstructionNode* instrNode,
238                               int ruleForNode,
239                               short* nts,
240                               TargetMachine &target)
241 {
242   // Fix up any constant operands in the machine instructions to either
243   // use an immediate field or to load the constant into a register
244   // Walk backwards and use direct indexes to allow insertion before current
245   // 
246   Instruction* vmInstr = instrNode->getInstruction();
247   MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
248   for (int i = (int) mvec.size()-1; i >= 0; i--)
249     {
250       std::vector<MachineInstr*> loadConstVec =
251         FixConstantOperandsForInstr(vmInstr, mvec[i], target);
252       
253       if (loadConstVec.size() > 0)
254         mvec.insert(mvec.begin()+i, loadConstVec.begin(), loadConstVec.end());
255     }
256 }
257
258 //---------------------------------------------------------------------------
259 // Function SelectInstructionsForTree 
260 // 
261 // Recursively walk the tree to select instructions.
262 // Do this top-down so that child instructions can exploit decisions
263 // made at the child instructions.
264 // 
265 // E.g., if br(setle(reg,const)) decides the constant is 0 and uses
266 // a branch-on-integer-register instruction, then the setle node
267 // can use that information to avoid generating the SUBcc instruction.
268 //
269 // Note that this cannot be done bottom-up because setle must do this
270 // only if it is a child of the branch (otherwise, the result of setle
271 // may be used by multiple instructions).
272 //---------------------------------------------------------------------------
273
274 bool
275 SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt,
276                           TargetMachine &target)
277 {
278   // Get the rule that matches this node.
279   // 
280   int ruleForNode = burm_rule(treeRoot->state, goalnt);
281   
282   if (ruleForNode == 0)
283     {
284       cerr << "Could not match instruction tree for instr selection\n";
285       assert(0);
286       return true;
287     }
288   
289   // Get this rule's non-terminals and the corresponding child nodes (if any)
290   // 
291   short *nts = burm_nts[ruleForNode];
292   
293   // First, select instructions for the current node and rule.
294   // (If this is a list node, not an instruction, then skip this step).
295   // This function is specific to the target architecture.
296   // 
297   if (treeRoot->opLabel != VRegListOp)
298     {
299       std::vector<MachineInstr*> minstrVec;
300       
301       InstructionNode* instrNode = (InstructionNode*)treeRoot;
302       assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
303       
304       GetInstructionsByRule(instrNode, ruleForNode, nts, target, minstrVec);
305       
306       MachineCodeForInstruction &mvec = 
307         MachineCodeForInstruction::get(instrNode->getInstruction());
308       mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
309     }
310   
311   // Then, recursively compile the child nodes, if any.
312   // 
313   if (nts[0])
314     { // i.e., there is at least one kid
315       InstrTreeNode* kids[2];
316       int currentRule = ruleForNode;
317       burm_kids(treeRoot, currentRule, kids);
318     
319       // First skip over any chain rules so that we don't visit
320       // the current node again.
321       // 
322       while (ThisIsAChainRule(currentRule))
323         {
324           currentRule = burm_rule(treeRoot->state, nts[0]);
325           nts = burm_nts[currentRule];
326           burm_kids(treeRoot, currentRule, kids);
327         }
328       
329       // Now we have the first non-chain rule so we have found
330       // the actual child nodes.  Recursively compile them.
331       // 
332       for (int i = 0; nts[i]; i++)
333         {
334           assert(i < 2);
335           InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
336           if (nodeType == InstrTreeNode::NTVRegListNode ||
337               nodeType == InstrTreeNode::NTInstructionNode)
338             {
339               if (SelectInstructionsForTree(kids[i], nts[i], target))
340                 return true;                    // failure
341             }
342         }
343     }
344   
345   // Finally, do any postprocessing on this node after its children
346   // have been translated
347   // 
348   if (treeRoot->opLabel != VRegListOp)
349     {
350       InstructionNode* instrNode = (InstructionNode*)treeRoot;
351       PostprocessMachineCodeForTree(instrNode, ruleForNode, nts, target);
352     }
353   
354   return false;                         // success
355 }
356