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"
33 //******************** Internal Data Declarations ************************/
36 enum SelectDebugLevel_t {
38 Select_PrintMachineCode,
39 Select_DebugInstTrees,
40 Select_DebugBurgTrees,
43 // Enable Debug Options to be specified on the command line
44 cl::Enum<enum SelectDebugLevel_t> SelectDebugLevel("dselect", cl::Hidden,
45 "enable instruction selection debugging information",
46 clEnumValN(Select_NoDebugInfo, "n", "disable debug output"),
47 clEnumValN(Select_PrintMachineCode, "y", "print generated machine code"),
48 clEnumValN(Select_DebugInstTrees, "i", "print debugging info for instruction selection "),
49 clEnumValN(Select_DebugBurgTrees, "b", "print burg trees"), 0);
52 //******************** Forward Function Declarations ***********************/
55 static bool SelectInstructionsForTree (InstrTreeNode* treeRoot,
57 TargetMachine &target);
59 static void PostprocessMachineCodeForTree(InstructionNode* instrNode,
62 TargetMachine &target);
64 static void InsertCode4AllPhisInMeth(Function *F, TargetMachine &target);
68 //******************* Externally Visible Functions *************************/
71 //---------------------------------------------------------------------------
72 // Entry point for instruction selection using BURG.
73 // Returns true if instruction selection failed, false otherwise.
74 //---------------------------------------------------------------------------
77 SelectInstructionsForMethod(Function *F, TargetMachine &target)
82 // Build the instruction trees to be given as inputs to BURG.
84 InstrForest instrForest(F);
86 if (SelectDebugLevel >= Select_DebugInstTrees)
88 cerr << "\n\n*** Input to instruction selection for function "
89 << F->getName() << "\n\n";
92 cerr << "\n\n*** Instruction trees for function "
93 << F->getName() << "\n\n";
98 // Invoke BURG instruction selection for each tree
100 for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
101 RI != instrForest.roots_end(); ++RI)
103 InstructionNode* basicNode = *RI;
104 assert(basicNode->parent() == NULL && "A `root' node has a parent?");
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 (Function::iterator BI = F->begin(), BE = F->end(); BI != BE; ++BI)
128 for (BasicBlock::iterator II = BI->begin(); II != BI->end(); ++II) {
129 MachineCodeForInstruction &mvec =MachineCodeForInstruction::get(II);
130 for (unsigned i=0; i < mvec.size(); i++)
131 MachineCodeForBasicBlock::get(BI).push_back(mvec[i]);
134 // Insert phi elimination code -- added by Ruchira
135 InsertCode4AllPhisInMeth(F, target);
138 if (SelectDebugLevel >= Select_PrintMachineCode)
140 cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
141 MachineCodeForMethod::get(F).dump();
148 //*********************** Private Functions *****************************/
151 //-------------------------------------------------------------------------
152 // Thid method inserts a copy instruction to a predecessor BB as a result
153 // of phi elimination.
154 //-------------------------------------------------------------------------
157 InsertPhiElimInstructions(BasicBlock *BB, const std::vector<MachineInstr*>& CpVec)
159 Instruction *TermInst = (Instruction*)BB->getTerminator();
160 MachineCodeForInstruction &MC4Term =MachineCodeForInstruction::get(TermInst);
161 MachineInstr *FirstMIOfTerm = *( MC4Term.begin() );
163 assert( FirstMIOfTerm && "No Machine Instrs for terminator" );
165 // get an iterator to machine instructions in the BB
166 MachineCodeForBasicBlock& bbMvec = MachineCodeForBasicBlock::get(BB);
167 MachineCodeForBasicBlock::iterator MCIt = bbMvec.begin();
169 // find the position of first machine instruction generated by the
170 // terminator of this BB
171 for( ; (MCIt != bbMvec.end()) && (*MCIt != FirstMIOfTerm) ; ++MCIt )
173 assert( MCIt != bbMvec.end() && "Start inst of terminator not found");
175 // insert the copy instructions just before the first machine instruction
176 // generated for the terminator
177 bbMvec.insert(MCIt, CpVec.begin(), CpVec.end());
179 //cerr << "\nPhiElimination copy inst: " << *CopyInstVec[0];
183 //-------------------------------------------------------------------------
184 // This method inserts phi elimination code for all BBs in a method
185 //-------------------------------------------------------------------------
188 InsertCode4AllPhisInMeth(Function *F, TargetMachine &target)
190 // for all basic blocks in function
192 for (Function::iterator BB = F->begin(); BB != F->end(); ++BB) {
193 BasicBlock::InstListType &InstList = BB->getInstList();
194 for (BasicBlock::iterator IIt = InstList.begin();
195 PHINode *PN = dyn_cast<PHINode>(&*IIt); ++IIt) {
196 // FIXME: This is probably wrong...
197 Value *PhiCpRes = new PHINode(PN->getType(), "PhiCp:");
199 // for each incoming value of the phi, insert phi elimination
201 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
202 // insert the copy instruction to the predecessor BB
203 vector<MachineInstr*> mvec, CpVec;
204 target.getRegInfo().cpValue2Value(PN->getIncomingValue(i), PhiCpRes,
206 for (vector<MachineInstr*>::iterator MI=mvec.begin();
207 MI != mvec.end(); ++MI) {
208 vector<MachineInstr*> CpVec2 =
209 FixConstantOperandsForInstr(PN, *MI, target);
210 CpVec2.push_back(*MI);
211 CpVec.insert(CpVec.end(), CpVec2.begin(), CpVec2.end());
214 InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
217 vector<MachineInstr*> mvec;
218 target.getRegInfo().cpValue2Value(PhiCpRes, PN, mvec);
220 // get an iterator to machine instructions in the BB
221 MachineCodeForBasicBlock& bbMvec = MachineCodeForBasicBlock::get(BB);
223 bbMvec.insert(bbMvec.begin(), mvec.begin(), mvec.end());
224 } // for each Phi Instr in BB
225 } // for all BBs in function
229 //---------------------------------------------------------------------------
230 // Function PostprocessMachineCodeForTree
232 // Apply any final cleanups to machine code for the root of a subtree
233 // after selection for all its children has been completed.
234 //---------------------------------------------------------------------------
237 PostprocessMachineCodeForTree(InstructionNode* instrNode,
240 TargetMachine &target)
242 // Fix up any constant operands in the machine instructions to either
243 // use an immediate field or to load the constant into a register
244 // Walk backwards and use direct indexes to allow insertion before current
246 Instruction* vmInstr = instrNode->getInstruction();
247 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
248 for (int i = (int) mvec.size()-1; i >= 0; i--)
250 std::vector<MachineInstr*> loadConstVec =
251 FixConstantOperandsForInstr(vmInstr, mvec[i], target);
253 if (loadConstVec.size() > 0)
254 mvec.insert(mvec.begin()+i, loadConstVec.begin(), loadConstVec.end());
258 //---------------------------------------------------------------------------
259 // Function SelectInstructionsForTree
261 // Recursively walk the tree to select instructions.
262 // Do this top-down so that child instructions can exploit decisions
263 // made at the child instructions.
265 // E.g., if br(setle(reg,const)) decides the constant is 0 and uses
266 // a branch-on-integer-register instruction, then the setle node
267 // can use that information to avoid generating the SUBcc instruction.
269 // Note that this cannot be done bottom-up because setle must do this
270 // only if it is a child of the branch (otherwise, the result of setle
271 // may be used by multiple instructions).
272 //---------------------------------------------------------------------------
275 SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt,
276 TargetMachine &target)
278 // Get the rule that matches this node.
280 int ruleForNode = burm_rule(treeRoot->state, goalnt);
282 if (ruleForNode == 0)
284 cerr << "Could not match instruction tree for instr selection\n";
289 // Get this rule's non-terminals and the corresponding child nodes (if any)
291 short *nts = burm_nts[ruleForNode];
293 // First, select instructions for the current node and rule.
294 // (If this is a list node, not an instruction, then skip this step).
295 // This function is specific to the target architecture.
297 if (treeRoot->opLabel != VRegListOp)
299 std::vector<MachineInstr*> minstrVec;
301 InstructionNode* instrNode = (InstructionNode*)treeRoot;
302 assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
304 GetInstructionsByRule(instrNode, ruleForNode, nts, target, minstrVec);
306 MachineCodeForInstruction &mvec =
307 MachineCodeForInstruction::get(instrNode->getInstruction());
308 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
311 // Then, recursively compile the child nodes, if any.
314 { // i.e., there is at least one kid
315 InstrTreeNode* kids[2];
316 int currentRule = ruleForNode;
317 burm_kids(treeRoot, currentRule, kids);
319 // First skip over any chain rules so that we don't visit
320 // the current node again.
322 while (ThisIsAChainRule(currentRule))
324 currentRule = burm_rule(treeRoot->state, nts[0]);
325 nts = burm_nts[currentRule];
326 burm_kids(treeRoot, currentRule, kids);
329 // Now we have the first non-chain rule so we have found
330 // the actual child nodes. Recursively compile them.
332 for (int i = 0; nts[i]; i++)
335 InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
336 if (nodeType == InstrTreeNode::NTVRegListNode ||
337 nodeType == InstrTreeNode::NTInstructionNode)
339 if (SelectInstructionsForTree(kids[i], nts[i], target))
340 return true; // failure
345 // Finally, do any postprocessing on this node after its children
346 // have been translated
348 if (treeRoot->opLabel != VRegListOp)
350 InstructionNode* instrNode = (InstructionNode*)treeRoot;
351 PostprocessMachineCodeForTree(instrNode, ruleForNode, nts, target);
354 return false; // success