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/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"
32 //******************** Internal Data Declarations ************************/
35 enum SelectDebugLevel_t {
37 Select_PrintMachineCode,
38 Select_DebugInstTrees,
39 Select_DebugBurgTrees,
43 // Enable Debug Options to be specified on the command line
44 static cl::opt<SelectDebugLevel_t>
45 SelectDebugLevel("dselect", cl::Hidden,
46 cl::desc("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",
51 "print debugging info for instruction selection"),
52 clEnumValN(Select_DebugBurgTrees, "b", "print burg trees"),
56 //******************** Forward Function Declarations ***********************/
59 static bool SelectInstructionsForTree (InstrTreeNode* treeRoot,
61 TargetMachine &target);
63 static void PostprocessMachineCodeForTree(InstructionNode* instrNode,
66 TargetMachine &target);
68 static void InsertCode4AllPhisInMeth(Function *F, TargetMachine &target);
72 //******************* Externally Visible Functions *************************/
75 //---------------------------------------------------------------------------
76 // Entry point for instruction selection using BURG.
77 // Returns true if instruction selection failed, false otherwise.
78 //---------------------------------------------------------------------------
81 SelectInstructionsForMethod(Function *F, TargetMachine &target)
86 // Build the instruction trees to be given as inputs to BURG.
88 InstrForest instrForest(F);
90 if (SelectDebugLevel >= Select_DebugInstTrees)
92 cerr << "\n\n*** Input to instruction selection for function "
93 << F->getName() << "\n\n";
96 cerr << "\n\n*** Instruction trees for function "
97 << F->getName() << "\n\n";
102 // Invoke BURG instruction selection for each tree
104 for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
105 RI != instrForest.roots_end(); ++RI)
107 InstructionNode* basicNode = *RI;
108 assert(basicNode->parent() == NULL && "A `root' node has a parent?");
110 // Invoke BURM to label each tree node with a state
111 burm_label(basicNode);
113 if (SelectDebugLevel >= Select_DebugBurgTrees)
115 printcover(basicNode, 1, 0);
116 cerr << "\nCover cost == " << treecost(basicNode, 1, 0) << "\n\n";
117 printMatches(basicNode);
120 // Then recursively walk the tree to select instructions
121 if (SelectInstructionsForTree(basicNode, /*goalnt*/1, target))
129 // Record instructions in the vector for each basic block
131 for (Function::iterator BI = F->begin(), BE = F->end(); BI != BE; ++BI)
132 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 MachineCodeForBasicBlock::get(BI).push_back(mvec[i]);
138 // Insert phi elimination code -- added by Ruchira
139 InsertCode4AllPhisInMeth(F, target);
142 if (SelectDebugLevel >= Select_PrintMachineCode)
144 cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
145 MachineCodeForMethod::get(F).dump();
152 //*********************** Private Functions *****************************/
155 //-------------------------------------------------------------------------
156 // Thid method inserts a copy instruction to a predecessor BB as a result
157 // of phi elimination.
158 //-------------------------------------------------------------------------
161 InsertPhiElimInstructions(BasicBlock *BB, const std::vector<MachineInstr*>& CpVec)
163 Instruction *TermInst = (Instruction*)BB->getTerminator();
164 MachineCodeForInstruction &MC4Term =MachineCodeForInstruction::get(TermInst);
165 MachineInstr *FirstMIOfTerm = *( MC4Term.begin() );
167 assert( FirstMIOfTerm && "No Machine Instrs for terminator" );
169 // get an iterator to machine instructions in the BB
170 MachineCodeForBasicBlock& bbMvec = MachineCodeForBasicBlock::get(BB);
171 MachineCodeForBasicBlock::iterator MCIt = bbMvec.begin();
173 // find the position of first machine instruction generated by the
174 // terminator of this BB
175 for( ; (MCIt != bbMvec.end()) && (*MCIt != FirstMIOfTerm) ; ++MCIt )
177 assert( MCIt != bbMvec.end() && "Start inst of terminator not found");
179 // insert the copy instructions just before the first machine instruction
180 // generated for the terminator
181 bbMvec.insert(MCIt, CpVec.begin(), CpVec.end());
183 //cerr << "\nPhiElimination copy inst: " << *CopyInstVec[0];
187 //-------------------------------------------------------------------------
188 // This method inserts phi elimination code for all BBs in a method
189 //-------------------------------------------------------------------------
192 InsertCode4AllPhisInMeth(Function *F, TargetMachine &target)
194 // for all basic blocks in function
196 for (Function::iterator BB = F->begin(); BB != F->end(); ++BB) {
197 BasicBlock::InstListType &InstList = BB->getInstList();
198 for (BasicBlock::iterator IIt = InstList.begin();
199 PHINode *PN = dyn_cast<PHINode>(&*IIt); ++IIt) {
200 // FIXME: This is probably wrong...
201 Value *PhiCpRes = new PHINode(PN->getType(), "PhiCp:");
203 // for each incoming value of the phi, insert phi elimination
205 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
206 // insert the copy instruction to the predecessor BB
207 vector<MachineInstr*> mvec, CpVec;
208 target.getRegInfo().cpValue2Value(PN->getIncomingValue(i), PhiCpRes,
210 for (vector<MachineInstr*>::iterator MI=mvec.begin();
211 MI != mvec.end(); ++MI) {
212 vector<MachineInstr*> CpVec2 =
213 FixConstantOperandsForInstr(PN, *MI, target);
214 CpVec2.push_back(*MI);
215 CpVec.insert(CpVec.end(), CpVec2.begin(), CpVec2.end());
218 InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
221 vector<MachineInstr*> mvec;
222 target.getRegInfo().cpValue2Value(PhiCpRes, PN, mvec);
224 // get an iterator to machine instructions in the BB
225 MachineCodeForBasicBlock& bbMvec = MachineCodeForBasicBlock::get(BB);
227 bbMvec.insert(bbMvec.begin(), mvec.begin(), mvec.end());
228 } // for each Phi Instr in BB
229 } // for all BBs in function
233 //---------------------------------------------------------------------------
234 // Function PostprocessMachineCodeForTree
236 // Apply any final cleanups to machine code for the root of a subtree
237 // after selection for all its children has been completed.
238 //---------------------------------------------------------------------------
241 PostprocessMachineCodeForTree(InstructionNode* instrNode,
244 TargetMachine &target)
246 // Fix up any constant operands in the machine instructions to either
247 // use an immediate field or to load the constant into a register
248 // Walk backwards and use direct indexes to allow insertion before current
250 Instruction* vmInstr = instrNode->getInstruction();
251 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
252 for (int i = (int) mvec.size()-1; i >= 0; i--)
254 std::vector<MachineInstr*> loadConstVec =
255 FixConstantOperandsForInstr(vmInstr, mvec[i], target);
257 if (loadConstVec.size() > 0)
258 mvec.insert(mvec.begin()+i, loadConstVec.begin(), loadConstVec.end());
262 //---------------------------------------------------------------------------
263 // Function SelectInstructionsForTree
265 // Recursively walk the tree to select instructions.
266 // Do this top-down so that child instructions can exploit decisions
267 // made at the child instructions.
269 // E.g., if br(setle(reg,const)) decides the constant is 0 and uses
270 // a branch-on-integer-register instruction, then the setle node
271 // can use that information to avoid generating the SUBcc instruction.
273 // Note that this cannot be done bottom-up because setle must do this
274 // only if it is a child of the branch (otherwise, the result of setle
275 // may be used by multiple instructions).
276 //---------------------------------------------------------------------------
279 SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt,
280 TargetMachine &target)
282 // Get the rule that matches this node.
284 int ruleForNode = burm_rule(treeRoot->state, goalnt);
286 if (ruleForNode == 0)
288 cerr << "Could not match instruction tree for instr selection\n";
293 // Get this rule's non-terminals and the corresponding child nodes (if any)
295 short *nts = burm_nts[ruleForNode];
297 // First, select instructions for the current node and rule.
298 // (If this is a list node, not an instruction, then skip this step).
299 // This function is specific to the target architecture.
301 if (treeRoot->opLabel != VRegListOp)
303 std::vector<MachineInstr*> minstrVec;
305 InstructionNode* instrNode = (InstructionNode*)treeRoot;
306 assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
308 GetInstructionsByRule(instrNode, ruleForNode, nts, target, minstrVec);
310 MachineCodeForInstruction &mvec =
311 MachineCodeForInstruction::get(instrNode->getInstruction());
312 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
315 // Then, recursively compile the child nodes, if any.
318 { // i.e., there is at least one kid
319 InstrTreeNode* kids[2];
320 int currentRule = ruleForNode;
321 burm_kids(treeRoot, currentRule, kids);
323 // First skip over any chain rules so that we don't visit
324 // the current node again.
326 while (ThisIsAChainRule(currentRule))
328 currentRule = burm_rule(treeRoot->state, nts[0]);
329 nts = burm_nts[currentRule];
330 burm_kids(treeRoot, currentRule, kids);
333 // Now we have the first non-chain rule so we have found
334 // the actual child nodes. Recursively compile them.
336 for (int i = 0; nts[i]; i++)
339 InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
340 if (nodeType == InstrTreeNode::NTVRegListNode ||
341 nodeType == InstrTreeNode::NTInstructionNode)
343 if (SelectInstructionsForTree(kids[i], nts[i], target))
344 return true; // failure
349 // Finally, do any postprocessing on this node after its children
350 // have been translated
352 if (treeRoot->opLabel != VRegListOp)
354 InstructionNode* instrNode = (InstructionNode*)treeRoot;
355 PostprocessMachineCodeForTree(instrNode, ruleForNode, nts, target);
358 return false; // success