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 ************************/
35 enum SelectDebugLevel_t {
37 Select_PrintMachineCode,
38 Select_DebugInstTrees,
39 Select_DebugBurgTrees,
42 // Enable Debug Options to be specified on the command line
43 cl::Enum<enum SelectDebugLevel_t> SelectDebugLevel("dselect", cl::NoFlags,
44 "enable instruction selection debugging information",
45 clEnumValN(Select_NoDebugInfo, "n", "disable debug output"),
46 clEnumValN(Select_PrintMachineCode, "y", "print generated machine code"),
47 clEnumValN(Select_DebugInstTrees, "i", "print debugging info for instruction selection "),
48 clEnumValN(Select_DebugBurgTrees, "b", "print burg trees"), 0);
51 //******************** Forward Function Declarations ***********************/
54 static bool SelectInstructionsForTree (InstrTreeNode* treeRoot,
56 TargetMachine &target);
58 static void PostprocessMachineCodeForTree(InstructionNode* instrNode,
61 TargetMachine &target);
63 static void InsertCode4AllPhisInMeth(Method *method, TargetMachine &target);
67 //******************* Externally Visible Functions *************************/
70 //---------------------------------------------------------------------------
71 // Entry point for instruction selection using BURG.
72 // Returns true if instruction selection failed, false otherwise.
73 //---------------------------------------------------------------------------
76 SelectInstructionsForMethod(Method* method, TargetMachine &target)
81 // Build the instruction trees to be given as inputs to BURG.
83 InstrForest instrForest(method);
85 if (SelectDebugLevel >= Select_DebugInstTrees)
87 cerr << "\n\n*** Input to instruction selection for method "
88 << (method->hasName()? method->getName() : "")
92 cerr << "\n\n*** Instruction trees for method "
93 << (method->hasName()? method->getName() : "")
99 // Invoke BURG instruction selection for each tree
101 for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
102 RI != instrForest.roots_end(); ++RI)
104 InstructionNode* basicNode = *RI;
105 assert(basicNode->parent() == NULL && "A `root' node has a parent?");
107 // Invoke BURM to label each tree node with a state
108 burm_label(basicNode);
110 if (SelectDebugLevel >= Select_DebugBurgTrees)
112 printcover(basicNode, 1, 0);
113 cerr << "\nCover cost == " << treecost(basicNode, 1, 0) << "\n\n";
114 printMatches(basicNode);
117 // Then recursively walk the tree to select instructions
118 if (SelectInstructionsForTree(basicNode, /*goalnt*/1, target))
126 // Record instructions in the vector for each basic block
128 for (Method::iterator BI = method->begin(); BI != method->end(); ++BI)
130 MachineCodeForBasicBlock& bbMvec = (*BI)->getMachineInstrVec();
131 for (BasicBlock::iterator II = (*BI)->begin(); II != (*BI)->end(); ++II)
133 MachineCodeForInstruction &mvec =MachineCodeForInstruction::get(*II);
134 for (unsigned i=0; i < mvec.size(); i++)
135 bbMvec.push_back(mvec[i]);
139 // Insert phi elimination code -- added by Ruchira
140 InsertCode4AllPhisInMeth(method, target);
143 if (SelectDebugLevel >= Select_PrintMachineCode)
145 cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
146 MachineCodeForMethod::get(method).dump();
153 //*********************** Private Functions *****************************/
156 //-------------------------------------------------------------------------
157 // Thid method inserts a copy instruction to a predecessor BB as a result
158 // of phi elimination.
159 //-------------------------------------------------------------------------
162 InsertPhiElimInstructions(BasicBlock *BB, const vector<MachineInstr*>& CpVec)
164 Instruction *TermInst = (Instruction*)BB->getTerminator();
165 MachineCodeForInstruction &MC4Term =MachineCodeForInstruction::get(TermInst);
166 MachineInstr *FirstMIOfTerm = *( MC4Term.begin() );
168 assert( FirstMIOfTerm && "No Machine Instrs for terminator" );
170 // get an iterator to machine instructions in the BB
171 MachineCodeForBasicBlock& bbMvec = BB->getMachineInstrVec();
172 MachineCodeForBasicBlock::iterator MCIt = bbMvec.begin();
174 // find the position of first machine instruction generated by the
175 // terminator of this BB
176 for( ; (MCIt != bbMvec.end()) && (*MCIt != FirstMIOfTerm) ; ++MCIt )
178 assert( MCIt != bbMvec.end() && "Start inst of terminator not found");
180 // insert the copy instructions just before the first machine instruction
181 // generated for the terminator
182 bbMvec.insert(MCIt, CpVec.begin(), CpVec.end());
184 //cerr << "\nPhiElimination copy inst: " << *CopyInstVec[0];
188 //-------------------------------------------------------------------------
189 // This method inserts phi elimination code for all BBs in a method
190 //-------------------------------------------------------------------------
193 InsertCode4AllPhisInMeth(Method *method, TargetMachine &target)
195 // for all basic blocks in method
197 for (Method::iterator BI = method->begin(); BI != method->end(); ++BI) {
199 BasicBlock *BB = *BI;
200 const BasicBlock::InstListType &InstList = BB->getInstList();
201 BasicBlock::InstListType::const_iterator IIt = InstList.begin();
203 // for all instructions in the basic block
205 for( ; IIt != InstList.end(); ++IIt ) {
207 if( (*IIt)->getOpcode() == Instruction::PHINode ) {
209 PHINode *PN = (PHINode *) (*IIt);
211 Value *PhiCpRes = new Value(PN->getType(),PN->getValueType(),"PhiCp:");
213 // for each incoming value of the phi, insert phi elimination
215 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
216 // insert the copy instruction to the predecessor BB
218 target.getRegInfo().cpValue2Value(PN->getIncomingValue(i),
221 vector<MachineInstr*> CpVec = FixConstantOperandsForInstr(PN, CpMI,
223 CpVec.push_back(CpMI);
225 InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
228 MachineInstr *CpMI2 =
229 target.getRegInfo().cpValue2Value(PhiCpRes, PN);
231 // get an iterator to machine instructions in the BB
232 MachineCodeForBasicBlock& bbMvec = BB->getMachineInstrVec();
234 bbMvec.insert( bbMvec.begin(), CpMI2);
236 else break; // since PHI nodes can only be at the top
238 } // for each Phi Instr in BB
240 } // for all BBs in method
245 //---------------------------------------------------------------------------
246 // Function PostprocessMachineCodeForTree
248 // Apply any final cleanups to machine code for the root of a subtree
249 // after selection for all its children has been completed.
250 //---------------------------------------------------------------------------
253 PostprocessMachineCodeForTree(InstructionNode* instrNode,
256 TargetMachine &target)
258 // Fix up any constant operands in the machine instructions to either
259 // use an immediate field or to load the constant into a register
260 // Walk backwards and use direct indexes to allow insertion before current
262 Instruction* vmInstr = instrNode->getInstruction();
263 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
264 for (int i = (int) mvec.size()-1; i >= 0; i--)
266 std::vector<MachineInstr*> loadConstVec =
267 FixConstantOperandsForInstr(vmInstr, mvec[i], target);
269 if (loadConstVec.size() > 0)
270 mvec.insert(mvec.begin()+i, loadConstVec.begin(), loadConstVec.end());
274 //---------------------------------------------------------------------------
275 // Function SelectInstructionsForTree
277 // Recursively walk the tree to select instructions.
278 // Do this top-down so that child instructions can exploit decisions
279 // made at the child instructions.
281 // E.g., if br(setle(reg,const)) decides the constant is 0 and uses
282 // a branch-on-integer-register instruction, then the setle node
283 // can use that information to avoid generating the SUBcc instruction.
285 // Note that this cannot be done bottom-up because setle must do this
286 // only if it is a child of the branch (otherwise, the result of setle
287 // may be used by multiple instructions).
288 //---------------------------------------------------------------------------
291 SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt,
292 TargetMachine &target)
294 // Get the rule that matches this node.
296 int ruleForNode = burm_rule(treeRoot->state, goalnt);
298 if (ruleForNode == 0)
300 cerr << "Could not match instruction tree for instr selection\n";
305 // Get this rule's non-terminals and the corresponding child nodes (if any)
307 short *nts = burm_nts[ruleForNode];
309 // First, select instructions for the current node and rule.
310 // (If this is a list node, not an instruction, then skip this step).
311 // This function is specific to the target architecture.
313 if (treeRoot->opLabel != VRegListOp)
315 vector<MachineInstr*> minstrVec;
317 InstructionNode* instrNode = (InstructionNode*)treeRoot;
318 assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
320 GetInstructionsByRule(instrNode, ruleForNode, nts, target, minstrVec);
322 MachineCodeForInstruction &mvec =
323 MachineCodeForInstruction::get(instrNode->getInstruction());
324 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
327 // Then, recursively compile the child nodes, if any.
330 { // i.e., there is at least one kid
331 InstrTreeNode* kids[2];
332 int currentRule = ruleForNode;
333 burm_kids(treeRoot, currentRule, kids);
335 // First skip over any chain rules so that we don't visit
336 // the current node again.
338 while (ThisIsAChainRule(currentRule))
340 currentRule = burm_rule(treeRoot->state, nts[0]);
341 nts = burm_nts[currentRule];
342 burm_kids(treeRoot, currentRule, kids);
345 // Now we have the first non-chain rule so we have found
346 // the actual child nodes. Recursively compile them.
348 for (int i = 0; nts[i]; i++)
351 InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
352 if (nodeType == InstrTreeNode::NTVRegListNode ||
353 nodeType == InstrTreeNode::NTInstructionNode)
355 if (SelectInstructionsForTree(kids[i], nts[i], target))
356 return true; // failure
361 // Finally, do any postprocessing on this node after its children
362 // have been translated
364 if (treeRoot->opLabel != VRegListOp)
366 InstructionNode* instrNode = (InstructionNode*)treeRoot;
367 PostprocessMachineCodeForTree(instrNode, ruleForNode, nts, target);
370 return false; // success