2 //***************************************************************************
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.
13 // 7/02/01 - Vikram Adve - Created
14 //**************************************************************************/
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"
32 //******************** Internal Data Declarations ************************/
34 // Use a static vector to avoid allocating a new one per VM instruction
35 static MachineInstr* minstrVec[MAX_INSTR_PER_VMINSTR];
38 enum SelectDebugLevel_t {
40 Select_PrintMachineCode,
41 Select_DebugInstTrees,
42 Select_DebugBurgTrees,
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);
54 //******************** Forward Function Declarations ***********************/
57 static bool SelectInstructionsForTree (InstrTreeNode* treeRoot,
59 TargetMachine &target);
61 static void PostprocessMachineCodeForTree(InstructionNode* instrNode,
64 TargetMachine &target);
66 static void InsertCode4AllPhisInMeth(Method *method, TargetMachine &target);
70 //******************* Externally Visible Functions *************************/
73 //---------------------------------------------------------------------------
74 // Entry point for instruction selection using BURG.
75 // Returns true if instruction selection failed, false otherwise.
76 //---------------------------------------------------------------------------
79 SelectInstructionsForMethod(Method* method, TargetMachine &target)
84 // Build the instruction trees to be given as inputs to BURG.
86 InstrForest instrForest(method);
88 if (SelectDebugLevel >= Select_DebugInstTrees)
90 cerr << "\n\n*** Instruction trees for method "
91 << (method->hasName()? method->getName() : "")
97 // Invoke BURG instruction selection for each tree
99 const std::hash_set<InstructionNode*> &treeRoots = instrForest.getRootSet();
100 for (std::hash_set<InstructionNode*>::const_iterator
101 treeRootIter = treeRoots.begin(); treeRootIter != treeRoots.end();
104 InstrTreeNode* basicNode = *treeRootIter;
106 // Invoke BURM to label each tree node with a state
107 burm_label(basicNode);
109 if (SelectDebugLevel >= Select_DebugBurgTrees)
111 printcover(basicNode, 1, 0);
112 cerr << "\nCover cost == " << treecost(basicNode, 1, 0) << "\n\n";
113 printMatches(basicNode);
116 // Then recursively walk the tree to select instructions
117 if (SelectInstructionsForTree(basicNode, /*goalnt*/1, target))
125 // Record instructions in the vector for each basic block
127 for (Method::iterator BI = method->begin(); BI != method->end(); ++BI)
129 MachineCodeForBasicBlock& bbMvec = (*BI)->getMachineInstrVec();
130 for (BasicBlock::iterator II = (*BI)->begin(); II != (*BI)->end(); ++II)
132 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(*II);
133 for (unsigned i=0; i < mvec.size(); i++)
134 bbMvec.push_back(mvec[i]);
138 // Insert phi elimination code -- added by Ruchira
139 InsertCode4AllPhisInMeth(method, target);
142 if (SelectDebugLevel >= Select_PrintMachineCode)
144 cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
145 MachineCodeForMethod::get(method).dump();
152 //*********************** Private Functions *****************************/
155 //-------------------------------------------------------------------------
156 // Thid method inserts a copy instruction to a predecessor BB as a result
157 // of phi elimination.
158 //-------------------------------------------------------------------------
160 void InsertPhiElimInst(BasicBlock *BB, MachineInstr *CpMI) {
162 TerminatorInst *TermInst = BB->getTerminator();
163 MachineCodeForInstruction &MC4Term = MachineCodeForInstruction::get(TermInst);
164 MachineInstr *FirstMIOfTerm = *( MC4Term.begin() );
166 assert( FirstMIOfTerm && "No Machine Instrs for terminator" );
168 // get an iterator to machine instructions in the BB
169 MachineCodeForBasicBlock& bbMvec = BB->getMachineInstrVec();
170 MachineCodeForBasicBlock::iterator MCIt = bbMvec.begin();
172 // find the position of first machine instruction generated by the
173 // terminator of this BB
174 for( ; (MCIt != bbMvec.end()) && (*MCIt != FirstMIOfTerm) ; ++MCIt ) ;
176 assert( MCIt != bbMvec.end() && "Start inst of terminator not found");
178 // insert the copy instruction just before the first machine instruction
179 // generated for the terminator
180 bbMvec.insert( MCIt , CpMI );
182 //cerr << "\nPhiElimination copy inst: " << *CopyInstVec[0];
187 //-------------------------------------------------------------------------
188 // This method inserts phi elimination code for all BBs in a method
189 //-------------------------------------------------------------------------
190 void InsertCode4AllPhisInMeth(Method *method, TargetMachine &target) {
193 // for all basic blocks in method
195 for (Method::iterator BI = method->begin(); BI != method->end(); ++BI) {
197 BasicBlock *BB = *BI;
198 const BasicBlock::InstListType &InstList = BB->getInstList();
199 BasicBlock::InstListType::const_iterator IIt = InstList.begin();
201 // for all instructions in the basic block
203 for( ; IIt != InstList.end(); ++IIt ) {
205 if( (*IIt)->getOpcode() == Instruction::PHINode ) {
207 PHINode *PN = (PHINode *) (*IIt);
209 // for each incoming value of the phi, insert phi elimination
211 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
213 // insert the copy instruction to the predecessor BB
215 std::vector<MachineInstr*> CopyInstVec;
218 target.getRegInfo().cpValue2Value(PN->getIncomingValue(i), PN);
220 InsertPhiElimInst( PN->getIncomingBlock(i), CpMI);
223 else break; // since PHI nodes can only be at the top
225 } // for each Phi Instr in BB
227 } // for all BBs in method
233 //-------------------------------------------------------------------------
234 // This method inserts phi elimination code for all BBs in a method
235 //-------------------------------------------------------------------------
236 void InsertCode4AllPhisInMeth(Method *method, TargetMachine &target) {
239 // for all basic blocks in method
241 for (Method::iterator BI = method->begin(); BI != method->end(); ++BI) {
243 BasicBlock *BB = *BI;
244 const BasicBlock::InstListType &InstList = BB->getInstList();
245 BasicBlock::InstListType::const_iterator IIt = InstList.begin();
247 // for all instructions in the basic block
249 for( ; IIt != InstList.end(); ++IIt ) {
251 if( (*IIt)->getOpcode() == Instruction::PHINode ) {
253 PHINode *PN = (PHINode *) (*IIt);
255 Value *PhiCpRes = new Value(PN->getType(), PN->getValueType(),"PhiCp:");
257 // for each incoming value of the phi, insert phi elimination
259 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
260 // insert the copy instruction to the predecessor BB
262 target.getRegInfo().cpValue2Value(PN->getIncomingValue(i),
265 InsertPhiElimInst(PN->getIncomingBlock(i), CpMI);
268 MachineInstr *CpMI2 =
269 target.getRegInfo().cpValue2Value(PhiCpRes, PN);
271 // get an iterator to machine instructions in the BB
272 MachineCodeForBasicBlock& bbMvec = BB->getMachineInstrVec();
274 bbMvec.insert( bbMvec.begin(), CpMI2);
276 else break; // since PHI nodes can only be at the top
278 } // for each Phi Instr in BB
280 } // for all BBs in method
285 //---------------------------------------------------------------------------
286 // Function PostprocessMachineCodeForTree
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 //---------------------------------------------------------------------------
293 PostprocessMachineCodeForTree(InstructionNode* instrNode,
296 TargetMachine &target)
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
302 Instruction* vmInstr = instrNode->getInstruction();
303 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
304 for (int i = (int) mvec.size()-1; i >= 0; i--)
306 std::vector<MachineInstr*> loadConstVec =
307 FixConstantOperandsForInstr(vmInstr, mvec[i], target);
309 if (loadConstVec.size() > 0)
310 mvec.insert(mvec.begin()+i, loadConstVec.begin(), loadConstVec.end());
314 //---------------------------------------------------------------------------
315 // Function SelectInstructionsForTree
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.
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.
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 //---------------------------------------------------------------------------
331 SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt,
332 TargetMachine &target)
334 // Get the rule that matches this node.
336 int ruleForNode = burm_rule(treeRoot->state, goalnt);
338 if (ruleForNode == 0)
340 cerr << "Could not match instruction tree for instr selection\n";
345 // Get this rule's non-terminals and the corresponding child nodes (if any)
347 short *nts = burm_nts[ruleForNode];
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.
353 if (treeRoot->opLabel != VRegListOp)
355 InstructionNode* instrNode = (InstructionNode*)treeRoot;
356 assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
358 unsigned N = GetInstructionsByRule(instrNode, ruleForNode, nts, target,
360 assert(N <= MAX_INSTR_PER_VMINSTR);
361 MachineCodeForInstruction &mvec =
362 MachineCodeForInstruction::get(instrNode->getInstruction());
363 mvec.insert(mvec.end(), minstrVec, minstrVec+N);
366 // Then, recursively compile the child nodes, if any.
369 { // i.e., there is at least one kid
370 InstrTreeNode* kids[2];
371 int currentRule = ruleForNode;
372 burm_kids(treeRoot, currentRule, kids);
374 // First skip over any chain rules so that we don't visit
375 // the current node again.
377 while (ThisIsAChainRule(currentRule))
379 currentRule = burm_rule(treeRoot->state, nts[0]);
380 nts = burm_nts[currentRule];
381 burm_kids(treeRoot, currentRule, kids);
384 // Now we have the first non-chain rule so we have found
385 // the actual child nodes. Recursively compile them.
387 for (int i = 0; nts[i]; i++)
390 InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
391 if (nodeType == InstrTreeNode::NTVRegListNode ||
392 nodeType == InstrTreeNode::NTInstructionNode)
394 if (SelectInstructionsForTree(kids[i], nts[i], target))
395 return true; // failure
400 // Finally, do any postprocessing on this node after its children
401 // have been translated
403 if (treeRoot->opLabel != VRegListOp)
405 InstructionNode* instrNode = (InstructionNode*)treeRoot;
406 PostprocessMachineCodeForTree(instrNode, ruleForNode, nts, target);
409 return false; // success