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/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"
31 //******************** Internal Data Declarations ************************/
34 enum SelectDebugLevel_t {
36 Select_PrintMachineCode,
37 Select_DebugInstTrees,
38 Select_DebugBurgTrees,
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);
50 //******************** Forward Function Declarations ***********************/
53 static bool SelectInstructionsForTree (InstrTreeNode* treeRoot,
55 TargetMachine &target);
57 static void PostprocessMachineCodeForTree(InstructionNode* instrNode,
60 TargetMachine &target);
62 static void InsertCode4AllPhisInMeth(Function *F, TargetMachine &target);
66 //******************* Externally Visible Functions *************************/
69 //---------------------------------------------------------------------------
70 // Entry point for instruction selection using BURG.
71 // Returns true if instruction selection failed, false otherwise.
72 //---------------------------------------------------------------------------
75 SelectInstructionsForMethod(Function *F, TargetMachine &target)
80 // Build the instruction trees to be given as inputs to BURG.
82 InstrForest instrForest(F);
84 if (SelectDebugLevel >= Select_DebugInstTrees)
86 cerr << "\n\n*** Input to instruction selection for function "
87 << F->getName() << "\n\n";
90 cerr << "\n\n*** Instruction trees for function "
91 << F->getName() << "\n\n";
96 // Invoke BURG instruction selection for each tree
98 for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
99 RI != instrForest.roots_end(); ++RI)
101 InstructionNode* basicNode = *RI;
102 assert(basicNode->parent() == NULL && "A `root' node has a parent?");
104 // Invoke BURM to label each tree node with a state
105 burm_label(basicNode);
107 if (SelectDebugLevel >= Select_DebugBurgTrees)
109 printcover(basicNode, 1, 0);
110 cerr << "\nCover cost == " << treecost(basicNode, 1, 0) << "\n\n";
111 printMatches(basicNode);
114 // Then recursively walk the tree to select instructions
115 if (SelectInstructionsForTree(basicNode, /*goalnt*/1, target))
123 // Record instructions in the vector for each basic block
125 for (Function::iterator BI = F->begin(), BE = F->end(); BI != BE; ++BI)
127 MachineCodeForBasicBlock& bbMvec = (*BI)->getMachineInstrVec();
128 for (BasicBlock::iterator II = (*BI)->begin(); II != (*BI)->end(); ++II)
130 MachineCodeForInstruction &mvec =MachineCodeForInstruction::get(*II);
131 for (unsigned i=0; i < mvec.size(); i++)
132 bbMvec.push_back(mvec[i]);
136 // Insert phi elimination code -- added by Ruchira
137 InsertCode4AllPhisInMeth(F, target);
140 if (SelectDebugLevel >= Select_PrintMachineCode)
142 cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
143 MachineCodeForMethod::get(F).dump();
150 //*********************** Private Functions *****************************/
153 //-------------------------------------------------------------------------
154 // Thid method inserts a copy instruction to a predecessor BB as a result
155 // of phi elimination.
156 //-------------------------------------------------------------------------
159 InsertPhiElimInstructions(BasicBlock *BB, const vector<MachineInstr*>& CpVec)
161 Instruction *TermInst = (Instruction*)BB->getTerminator();
162 MachineCodeForInstruction &MC4Term =MachineCodeForInstruction::get(TermInst);
163 MachineInstr *FirstMIOfTerm = *( MC4Term.begin() );
165 assert( FirstMIOfTerm && "No Machine Instrs for terminator" );
167 // get an iterator to machine instructions in the BB
168 MachineCodeForBasicBlock& bbMvec = BB->getMachineInstrVec();
169 MachineCodeForBasicBlock::iterator MCIt = bbMvec.begin();
171 // find the position of first machine instruction generated by the
172 // terminator of this BB
173 for( ; (MCIt != bbMvec.end()) && (*MCIt != FirstMIOfTerm) ; ++MCIt )
175 assert( MCIt != bbMvec.end() && "Start inst of terminator not found");
177 // insert the copy instructions just before the first machine instruction
178 // generated for the terminator
179 bbMvec.insert(MCIt, CpVec.begin(), CpVec.end());
181 //cerr << "\nPhiElimination copy inst: " << *CopyInstVec[0];
185 //-------------------------------------------------------------------------
186 // This method inserts phi elimination code for all BBs in a method
187 //-------------------------------------------------------------------------
190 InsertCode4AllPhisInMeth(Function *F, TargetMachine &target)
192 // for all basic blocks in function
194 for (Function::iterator BI = F->begin(); BI != F->end(); ++BI) {
196 BasicBlock *BB = *BI;
197 const BasicBlock::InstListType &InstList = BB->getInstList();
198 BasicBlock::InstListType::const_iterator IIt = InstList.begin();
200 // for all instructions in the basic block
202 for( ; IIt != InstList.end(); ++IIt ) {
204 if (PHINode *PN = dyn_cast<PHINode>(*IIt)) {
205 // FIXME: This is probably wrong...
206 Value *PhiCpRes = new PHINode(PN->getType(), "PhiCp:");
208 // for each incoming value of the phi, insert phi elimination
210 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
211 // insert the copy instruction to the predecessor BB
213 target.getRegInfo().cpValue2Value(PN->getIncomingValue(i),
216 vector<MachineInstr*> CpVec = FixConstantOperandsForInstr(PN, CpMI,
218 CpVec.push_back(CpMI);
220 InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
223 MachineInstr *CpMI2 =
224 target.getRegInfo().cpValue2Value(PhiCpRes, PN);
226 // get an iterator to machine instructions in the BB
227 MachineCodeForBasicBlock& bbMvec = BB->getMachineInstrVec();
229 bbMvec.insert( bbMvec.begin(), CpMI2);
231 else break; // since PHI nodes can only be at the top
233 } // for each Phi Instr in BB
234 } // for all BBs in function
238 //---------------------------------------------------------------------------
239 // Function PostprocessMachineCodeForTree
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 //---------------------------------------------------------------------------
246 PostprocessMachineCodeForTree(InstructionNode* instrNode,
249 TargetMachine &target)
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
255 Instruction* vmInstr = instrNode->getInstruction();
256 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
257 for (int i = (int) mvec.size()-1; i >= 0; i--)
259 std::vector<MachineInstr*> loadConstVec =
260 FixConstantOperandsForInstr(vmInstr, mvec[i], target);
262 if (loadConstVec.size() > 0)
263 mvec.insert(mvec.begin()+i, loadConstVec.begin(), loadConstVec.end());
267 //---------------------------------------------------------------------------
268 // Function SelectInstructionsForTree
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.
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.
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 //---------------------------------------------------------------------------
284 SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt,
285 TargetMachine &target)
287 // Get the rule that matches this node.
289 int ruleForNode = burm_rule(treeRoot->state, goalnt);
291 if (ruleForNode == 0)
293 cerr << "Could not match instruction tree for instr selection\n";
298 // Get this rule's non-terminals and the corresponding child nodes (if any)
300 short *nts = burm_nts[ruleForNode];
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.
306 if (treeRoot->opLabel != VRegListOp)
308 vector<MachineInstr*> minstrVec;
310 InstructionNode* instrNode = (InstructionNode*)treeRoot;
311 assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
313 GetInstructionsByRule(instrNode, ruleForNode, nts, target, minstrVec);
315 MachineCodeForInstruction &mvec =
316 MachineCodeForInstruction::get(instrNode->getInstruction());
317 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
320 // Then, recursively compile the child nodes, if any.
323 { // i.e., there is at least one kid
324 InstrTreeNode* kids[2];
325 int currentRule = ruleForNode;
326 burm_kids(treeRoot, currentRule, kids);
328 // First skip over any chain rules so that we don't visit
329 // the current node again.
331 while (ThisIsAChainRule(currentRule))
333 currentRule = burm_rule(treeRoot->state, nts[0]);
334 nts = burm_nts[currentRule];
335 burm_kids(treeRoot, currentRule, kids);
338 // Now we have the first non-chain rule so we have found
339 // the actual child nodes. Recursively compile them.
341 for (int i = 0; nts[i]; i++)
344 InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
345 if (nodeType == InstrTreeNode::NTVRegListNode ||
346 nodeType == InstrTreeNode::NTInstructionNode)
348 if (SelectInstructionsForTree(kids[i], nts[i], target))
349 return true; // failure
354 // Finally, do any postprocessing on this node after its children
355 // have been translated
357 if (treeRoot->opLabel != VRegListOp)
359 InstructionNode* instrNode = (InstructionNode*)treeRoot;
360 PostprocessMachineCodeForTree(instrNode, ruleForNode, nts, target);
363 return false; // success