1 //===- InstrSelection.cpp - Machine Independant Inst Selection Driver -----===//
3 // Machine-independent driver file for instruction selection. This file
4 // constructs a forest of BURG instruction trees and then uses the
5 // BURG-generated tree grammar (BURM) to find the optimal instruction sequences
6 // for a given machine.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/CodeGen/InstrSelection.h"
11 #include "llvm/CodeGen/InstrSelectionSupport.h"
12 #include "llvm/CodeGen/InstrForest.h"
13 #include "llvm/CodeGen/MachineCodeForInstruction.h"
14 #include "llvm/CodeGen/MachineCodeForBasicBlock.h"
15 #include "llvm/CodeGen/MachineCodeForMethod.h"
16 #include "llvm/Target/MachineRegInfo.h"
17 #include "llvm/Target/TargetMachine.h"
18 #include "llvm/Function.h"
19 #include "llvm/iPHINode.h"
20 #include "llvm/Pass.h"
21 #include "Support/CommandLine.h"
22 #include "Support/LeakDetector.h"
27 //===--------------------------------------------------------------------===//
28 // SelectDebugLevel - Allow command line control over debugging.
30 enum SelectDebugLevel_t {
32 Select_PrintMachineCode,
33 Select_DebugInstTrees,
34 Select_DebugBurgTrees,
37 // Enable Debug Options to be specified on the command line
38 cl::opt<SelectDebugLevel_t>
39 SelectDebugLevel("dselect", cl::Hidden,
40 cl::desc("enable instruction selection debug information"),
42 clEnumValN(Select_NoDebugInfo, "n", "disable debug output"),
43 clEnumValN(Select_PrintMachineCode, "y", "print generated machine code"),
44 clEnumValN(Select_DebugInstTrees, "i",
45 "print debugging info for instruction selection"),
46 clEnumValN(Select_DebugBurgTrees, "b", "print burg trees"),
50 //===--------------------------------------------------------------------===//
51 // InstructionSelection Pass
53 // This is the actual pass object that drives the instruction selection
56 class InstructionSelection : public FunctionPass {
57 TargetMachine &Target;
58 void InsertCodeForPhis(Function &F);
59 void InsertPhiElimInstructions(BasicBlock *BB,
60 const vector<MachineInstr*>& CpVec);
61 void SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt);
62 void PostprocessMachineCodeForTree(InstructionNode* instrNode,
63 int ruleForNode, short* nts);
65 InstructionSelection(TargetMachine &T) : Target(T) {}
67 bool runOnFunction(Function &F);
71 // Register the pass...
72 static RegisterLLC<InstructionSelection>
73 X("instselect", "Instruction Selection", createInstructionSelectionPass);
75 TmpInstruction::TmpInstruction(Value *s1, Value *s2, const std::string &name)
76 : Instruction(s1->getType(), Instruction::UserOp1, name) {
77 Operands.push_back(Use(s1, this)); // s1 must be nonnull
79 Operands.push_back(Use(s2, this));
82 // TmpInstructions should not be garbage checked.
83 LeakDetector::removeGarbageObject(this);
86 // Constructor that requires the type of the temporary to be specified.
87 // Both S1 and S2 may be NULL.(
88 TmpInstruction::TmpInstruction(const Type *Ty, Value *s1, Value* s2,
89 const std::string &name)
90 : Instruction(Ty, Instruction::UserOp1, name) {
91 if (s1) { Operands.push_back(Use(s1, this)); }
92 if (s2) { Operands.push_back(Use(s2, this)); }
94 // TmpInstructions should not be garbage checked.
95 LeakDetector::removeGarbageObject(this);
99 bool InstructionSelection::runOnFunction(Function &F)
102 // Build the instruction trees to be given as inputs to BURG.
104 InstrForest instrForest(&F);
106 if (SelectDebugLevel >= Select_DebugInstTrees)
108 cerr << "\n\n*** Input to instruction selection for function "
109 << F.getName() << "\n\n" << F
110 << "\n\n*** Instruction trees for function "
111 << F.getName() << "\n\n";
116 // Invoke BURG instruction selection for each tree
118 for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
119 RI != instrForest.roots_end(); ++RI)
121 InstructionNode* basicNode = *RI;
122 assert(basicNode->parent() == NULL && "A `root' node has a parent?");
124 // Invoke BURM to label each tree node with a state
125 burm_label(basicNode);
127 if (SelectDebugLevel >= Select_DebugBurgTrees)
129 printcover(basicNode, 1, 0);
130 cerr << "\nCover cost == " << treecost(basicNode, 1, 0) << "\n\n";
131 printMatches(basicNode);
134 // Then recursively walk the tree to select instructions
135 SelectInstructionsForTree(basicNode, /*goalnt*/1);
139 // Record instructions in the vector for each basic block
141 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI)
142 for (BasicBlock::iterator II = BI->begin(); II != BI->end(); ++II) {
143 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(II);
144 MachineCodeForBasicBlock &MCBB = MachineCodeForBasicBlock::get(BI);
145 MCBB.insert(MCBB.end(), mvec.begin(), mvec.end());
148 // Insert phi elimination code
149 InsertCodeForPhis(F);
151 if (SelectDebugLevel >= Select_PrintMachineCode)
153 cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
154 MachineCodeForMethod::get(&F).dump();
161 //-------------------------------------------------------------------------
162 // This method inserts phi elimination code for all BBs in a method
163 //-------------------------------------------------------------------------
166 InstructionSelection::InsertCodeForPhis(Function &F)
168 // for all basic blocks in function
170 for (Function::iterator BB = F.begin(); BB != F.end(); ++BB) {
171 BasicBlock::InstListType &InstList = BB->getInstList();
172 for (BasicBlock::iterator IIt = InstList.begin();
173 PHINode *PN = dyn_cast<PHINode>(&*IIt); ++IIt) {
174 // FIXME: This is probably wrong...
175 Value *PhiCpRes = new PHINode(PN->getType(), "PhiCp:");
177 // The leak detector shouldn't track these nodes. They are not garbage,
178 // even though their parent field is never filled in.
180 LeakDetector::removeGarbageObject(PhiCpRes);
182 // for each incoming value of the phi, insert phi elimination
184 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
185 // insert the copy instruction to the predecessor BB
186 vector<MachineInstr*> mvec, CpVec;
187 Target.getRegInfo().cpValue2Value(PN->getIncomingValue(i), PhiCpRes,
189 for (vector<MachineInstr*>::iterator MI=mvec.begin();
190 MI != mvec.end(); ++MI) {
191 vector<MachineInstr*> CpVec2 =
192 FixConstantOperandsForInstr(PN, *MI, Target);
193 CpVec2.push_back(*MI);
194 CpVec.insert(CpVec.end(), CpVec2.begin(), CpVec2.end());
197 InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
200 vector<MachineInstr*> mvec;
201 Target.getRegInfo().cpValue2Value(PhiCpRes, PN, mvec);
203 // get an iterator to machine instructions in the BB
204 MachineCodeForBasicBlock& bbMvec = MachineCodeForBasicBlock::get(BB);
206 bbMvec.insert(bbMvec.begin(), mvec.begin(), mvec.end());
207 } // for each Phi Instr in BB
208 } // for all BBs in function
211 //-------------------------------------------------------------------------
212 // Thid method inserts a copy instruction to a predecessor BB as a result
213 // of phi elimination.
214 //-------------------------------------------------------------------------
217 InstructionSelection::InsertPhiElimInstructions(BasicBlock *BB,
218 const vector<MachineInstr*>& CpVec)
220 Instruction *TermInst = (Instruction*)BB->getTerminator();
221 MachineCodeForInstruction &MC4Term = MachineCodeForInstruction::get(TermInst);
222 MachineInstr *FirstMIOfTerm = MC4Term.front();
224 assert (FirstMIOfTerm && "No Machine Instrs for terminator");
226 MachineCodeForBasicBlock &bbMvec = MachineCodeForBasicBlock::get(BB);
228 // find the position of first machine instruction generated by the
229 // terminator of this BB
230 MachineCodeForBasicBlock::iterator MCIt =
231 std::find(bbMvec.begin(), bbMvec.end(), FirstMIOfTerm);
233 assert( MCIt != bbMvec.end() && "Start inst of terminator not found");
235 // insert the copy instructions just before the first machine instruction
236 // generated for the terminator
237 bbMvec.insert(MCIt, CpVec.begin(), CpVec.end());
241 //---------------------------------------------------------------------------
242 // Function SelectInstructionsForTree
244 // Recursively walk the tree to select instructions.
245 // Do this top-down so that child instructions can exploit decisions
246 // made at the child instructions.
248 // E.g., if br(setle(reg,const)) decides the constant is 0 and uses
249 // a branch-on-integer-register instruction, then the setle node
250 // can use that information to avoid generating the SUBcc instruction.
252 // Note that this cannot be done bottom-up because setle must do this
253 // only if it is a child of the branch (otherwise, the result of setle
254 // may be used by multiple instructions).
255 //---------------------------------------------------------------------------
258 InstructionSelection::SelectInstructionsForTree(InstrTreeNode* treeRoot,
261 // Get the rule that matches this node.
263 int ruleForNode = burm_rule(treeRoot->state, goalnt);
265 if (ruleForNode == 0) {
266 cerr << "Could not match instruction tree for instr selection\n";
270 // Get this rule's non-terminals and the corresponding child nodes (if any)
272 short *nts = burm_nts[ruleForNode];
274 // First, select instructions for the current node and rule.
275 // (If this is a list node, not an instruction, then skip this step).
276 // This function is specific to the target architecture.
278 if (treeRoot->opLabel != VRegListOp)
280 vector<MachineInstr*> minstrVec;
282 InstructionNode* instrNode = (InstructionNode*)treeRoot;
283 assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
285 GetInstructionsByRule(instrNode, ruleForNode, nts, Target, minstrVec);
287 MachineCodeForInstruction &mvec =
288 MachineCodeForInstruction::get(instrNode->getInstruction());
289 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
292 // Then, recursively compile the child nodes, if any.
295 { // i.e., there is at least one kid
296 InstrTreeNode* kids[2];
297 int currentRule = ruleForNode;
298 burm_kids(treeRoot, currentRule, kids);
300 // First skip over any chain rules so that we don't visit
301 // the current node again.
303 while (ThisIsAChainRule(currentRule))
305 currentRule = burm_rule(treeRoot->state, nts[0]);
306 nts = burm_nts[currentRule];
307 burm_kids(treeRoot, currentRule, kids);
310 // Now we have the first non-chain rule so we have found
311 // the actual child nodes. Recursively compile them.
313 for (unsigned i = 0; nts[i]; i++)
316 InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
317 if (nodeType == InstrTreeNode::NTVRegListNode ||
318 nodeType == InstrTreeNode::NTInstructionNode)
319 SelectInstructionsForTree(kids[i], nts[i]);
323 // Finally, do any postprocessing on this node after its children
324 // have been translated
326 if (treeRoot->opLabel != VRegListOp)
327 PostprocessMachineCodeForTree((InstructionNode*)treeRoot, ruleForNode, nts);
330 //---------------------------------------------------------------------------
331 // Function PostprocessMachineCodeForTree
333 // Apply any final cleanups to machine code for the root of a subtree
334 // after selection for all its children has been completed.
337 InstructionSelection::PostprocessMachineCodeForTree(InstructionNode* instrNode,
341 // Fix up any constant operands in the machine instructions to either
342 // use an immediate field or to load the constant into a register
343 // Walk backwards and use direct indexes to allow insertion before current
345 Instruction* vmInstr = instrNode->getInstruction();
346 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
347 for (unsigned i = mvec.size(); i != 0; --i)
349 vector<MachineInstr*> loadConstVec =
350 FixConstantOperandsForInstr(vmInstr, mvec[i-1], Target);
352 mvec.insert(mvec.begin()+i-1, loadConstVec.begin(), loadConstVec.end());
358 //===----------------------------------------------------------------------===//
359 // createInstructionSelectionPass - Public entrypoint for instruction selection
360 // and this file as a whole...
362 Pass *createInstructionSelectionPass(TargetMachine &T) {
363 return new InstructionSelection(T);