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