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/MachineFunction.h"
15 #include "llvm/Target/TargetRegInfo.h"
16 #include "llvm/Target/TargetMachine.h"
17 #include "llvm/Function.h"
18 #include "llvm/iPHINode.h"
19 #include "llvm/Pass.h"
20 #include "Support/CommandLine.h"
21 #include "Support/LeakDetector.h"
24 std::vector<MachineInstr*>
25 FixConstantOperandsForInstr(Instruction* vmInstr, MachineInstr* minstr,
26 TargetMachine& target);
29 //===--------------------------------------------------------------------===//
30 // SelectDebugLevel - Allow command line control over debugging.
32 enum SelectDebugLevel_t {
34 Select_PrintMachineCode,
35 Select_DebugInstTrees,
36 Select_DebugBurgTrees,
39 // Enable Debug Options to be specified on the command line
40 cl::opt<SelectDebugLevel_t>
41 SelectDebugLevel("dselect", cl::Hidden,
42 cl::desc("enable instruction selection debug information"),
44 clEnumValN(Select_NoDebugInfo, "n", "disable debug output"),
45 clEnumValN(Select_PrintMachineCode, "y", "print generated machine code"),
46 clEnumValN(Select_DebugInstTrees, "i",
47 "print debugging info for instruction selection"),
48 clEnumValN(Select_DebugBurgTrees, "b", "print burg trees"),
52 //===--------------------------------------------------------------------===//
53 // InstructionSelection Pass
55 // This is the actual pass object that drives the instruction selection
58 class InstructionSelection : public FunctionPass {
59 TargetMachine &Target;
60 void InsertCodeForPhis(Function &F);
61 void InsertPhiElimInstructions(BasicBlock *BB,
62 const vector<MachineInstr*>& CpVec);
63 void SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt);
64 void PostprocessMachineCodeForTree(InstructionNode* instrNode,
65 int ruleForNode, short* nts);
67 InstructionSelection(TargetMachine &T) : Target(T) {}
69 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 bool runOnFunction(Function &F);
77 // Register the pass...
78 static RegisterLLC<InstructionSelection>
79 X("instselect", "Instruction Selection", createInstructionSelectionPass);
81 TmpInstruction::TmpInstruction(MachineCodeForInstruction& mcfi,
82 Value *s1, Value *s2, const std::string &name)
83 : Instruction(s1->getType(), Instruction::UserOp1, name)
87 Operands.push_back(Use(s1, this)); // s1 must be nonnull
89 Operands.push_back(Use(s2, this));
92 // TmpInstructions should not be garbage checked.
93 LeakDetector::removeGarbageObject(this);
96 // Constructor that requires the type of the temporary to be specified.
97 // Both S1 and S2 may be NULL.(
98 TmpInstruction::TmpInstruction(MachineCodeForInstruction& mcfi,
99 const Type *Ty, Value *s1, Value* s2,
100 const std::string &name)
101 : Instruction(Ty, Instruction::UserOp1, name)
105 if (s1) { Operands.push_back(Use(s1, this)); }
106 if (s2) { Operands.push_back(Use(s2, this)); }
108 // TmpInstructions should not be garbage checked.
109 LeakDetector::removeGarbageObject(this);
113 bool InstructionSelection::runOnFunction(Function &F)
116 // Build the instruction trees to be given as inputs to BURG.
118 InstrForest instrForest(&F);
120 if (SelectDebugLevel >= Select_DebugInstTrees)
122 std::cerr << "\n\n*** Input to instruction selection for function "
123 << F.getName() << "\n\n" << F
124 << "\n\n*** Instruction trees for function "
125 << F.getName() << "\n\n";
130 // Invoke BURG instruction selection for each tree
132 for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
133 RI != instrForest.roots_end(); ++RI)
135 InstructionNode* basicNode = *RI;
136 assert(basicNode->parent() == NULL && "A `root' node has a parent?");
138 // Invoke BURM to label each tree node with a state
139 burm_label(basicNode);
141 if (SelectDebugLevel >= Select_DebugBurgTrees)
143 printcover(basicNode, 1, 0);
144 std::cerr << "\nCover cost == " << treecost(basicNode, 1, 0) <<"\n\n";
145 printMatches(basicNode);
148 // Then recursively walk the tree to select instructions
149 SelectInstructionsForTree(basicNode, /*goalnt*/1);
153 // Create the MachineBasicBlock records and add all of the MachineInstrs
154 // defined in the MachineCodeForInstruction objects to also live in the
155 // MachineBasicBlock objects.
157 MachineFunction &MF = MachineFunction::get(&F);
158 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
159 MachineBasicBlock *MCBB = new MachineBasicBlock(BI);
160 MF.getBasicBlockList().push_back(MCBB);
162 for (BasicBlock::iterator II = BI->begin(); II != BI->end(); ++II) {
163 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(II);
164 MCBB->insert(MCBB->end(), mvec.begin(), mvec.end());
168 // Insert phi elimination code
169 InsertCodeForPhis(F);
171 if (SelectDebugLevel >= Select_PrintMachineCode)
173 std::cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
174 MachineFunction::get(&F).dump();
181 //-------------------------------------------------------------------------
182 // This method inserts phi elimination code for all BBs in a method
183 //-------------------------------------------------------------------------
186 InstructionSelection::InsertCodeForPhis(Function &F)
188 // for all basic blocks in function
190 MachineFunction &MF = MachineFunction::get(&F);
191 for (MachineFunction::iterator BB = MF.begin(); BB != MF.end(); ++BB) {
192 for (BasicBlock::iterator IIt = BB->getBasicBlock()->begin();
193 PHINode *PN = dyn_cast<PHINode>(IIt); ++IIt) {
194 // FIXME: This is probably wrong...
195 Value *PhiCpRes = new PHINode(PN->getType(), "PhiCp:");
197 // The leak detector shouldn't track these nodes. They are not garbage,
198 // even though their parent field is never filled in.
200 LeakDetector::removeGarbageObject(PhiCpRes);
202 // for each incoming value of the phi, insert phi elimination
204 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
205 // insert the copy instruction to the predecessor BB
206 vector<MachineInstr*> mvec, CpVec;
207 Target.getRegInfo().cpValue2Value(PN->getIncomingValue(i), PhiCpRes,
209 for (vector<MachineInstr*>::iterator MI=mvec.begin();
210 MI != mvec.end(); ++MI) {
211 vector<MachineInstr*> CpVec2 =
212 FixConstantOperandsForInstr(PN, *MI, Target);
213 CpVec2.push_back(*MI);
214 CpVec.insert(CpVec.end(), CpVec2.begin(), CpVec2.end());
217 InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
220 vector<MachineInstr*> mvec;
221 Target.getRegInfo().cpValue2Value(PhiCpRes, PN, mvec);
222 BB->insert(BB->begin(), mvec.begin(), mvec.end());
223 } // for each Phi Instr in BB
224 } // for all BBs in function
227 //-------------------------------------------------------------------------
228 // Thid method inserts a copy instruction to a predecessor BB as a result
229 // of phi elimination.
230 //-------------------------------------------------------------------------
233 InstructionSelection::InsertPhiElimInstructions(BasicBlock *BB,
234 const vector<MachineInstr*>& CpVec)
236 Instruction *TermInst = (Instruction*)BB->getTerminator();
237 MachineCodeForInstruction &MC4Term = MachineCodeForInstruction::get(TermInst);
238 MachineInstr *FirstMIOfTerm = MC4Term.front();
239 assert (FirstMIOfTerm && "No Machine Instrs for terminator");
241 MachineFunction &MF = MachineFunction::get(BB->getParent());
243 // FIXME: if PHI instructions existed in the machine code, this would be
245 MachineBasicBlock *MBB = 0;
246 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
247 if (I->getBasicBlock() == BB) {
252 // find the position of first machine instruction generated by the
253 // terminator of this BB
254 MachineBasicBlock::iterator MCIt =
255 std::find(MBB->begin(), MBB->end(), FirstMIOfTerm);
257 assert(MCIt != MBB->end() && "Start inst of terminator not found");
259 // insert the copy instructions just before the first machine instruction
260 // generated for the terminator
261 MBB->insert(MCIt, CpVec.begin(), CpVec.end());
265 //---------------------------------------------------------------------------
266 // Function SelectInstructionsForTree
268 // Recursively walk the tree to select instructions.
269 // Do this top-down so that child instructions can exploit decisions
270 // made at the child instructions.
272 // E.g., if br(setle(reg,const)) decides the constant is 0 and uses
273 // a branch-on-integer-register instruction, then the setle node
274 // can use that information to avoid generating the SUBcc instruction.
276 // Note that this cannot be done bottom-up because setle must do this
277 // only if it is a child of the branch (otherwise, the result of setle
278 // may be used by multiple instructions).
279 //---------------------------------------------------------------------------
282 InstructionSelection::SelectInstructionsForTree(InstrTreeNode* treeRoot,
285 // Get the rule that matches this node.
287 int ruleForNode = burm_rule(treeRoot->state, goalnt);
289 if (ruleForNode == 0) {
290 std::cerr << "Could not match instruction tree for instr selection\n";
294 // Get this rule's non-terminals and the corresponding child nodes (if any)
296 short *nts = burm_nts[ruleForNode];
298 // First, select instructions for the current node and rule.
299 // (If this is a list node, not an instruction, then skip this step).
300 // This function is specific to the target architecture.
302 if (treeRoot->opLabel != VRegListOp)
304 vector<MachineInstr*> minstrVec;
306 InstructionNode* instrNode = (InstructionNode*)treeRoot;
307 assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
309 GetInstructionsByRule(instrNode, ruleForNode, nts, Target, minstrVec);
311 MachineCodeForInstruction &mvec =
312 MachineCodeForInstruction::get(instrNode->getInstruction());
313 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
316 // Then, recursively compile the child nodes, if any.
319 { // i.e., there is at least one kid
320 InstrTreeNode* kids[2];
321 int currentRule = ruleForNode;
322 burm_kids(treeRoot, currentRule, kids);
324 // First skip over any chain rules so that we don't visit
325 // the current node again.
327 while (ThisIsAChainRule(currentRule))
329 currentRule = burm_rule(treeRoot->state, nts[0]);
330 nts = burm_nts[currentRule];
331 burm_kids(treeRoot, currentRule, kids);
334 // Now we have the first non-chain rule so we have found
335 // the actual child nodes. Recursively compile them.
337 for (unsigned i = 0; nts[i]; i++)
340 InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
341 if (nodeType == InstrTreeNode::NTVRegListNode ||
342 nodeType == InstrTreeNode::NTInstructionNode)
343 SelectInstructionsForTree(kids[i], nts[i]);
347 // Finally, do any postprocessing on this node after its children
348 // have been translated
350 if (treeRoot->opLabel != VRegListOp)
351 PostprocessMachineCodeForTree((InstructionNode*)treeRoot, ruleForNode, nts);
354 //---------------------------------------------------------------------------
355 // Function PostprocessMachineCodeForTree
357 // Apply any final cleanups to machine code for the root of a subtree
358 // after selection for all its children has been completed.
361 InstructionSelection::PostprocessMachineCodeForTree(InstructionNode* instrNode,
365 // Fix up any constant operands in the machine instructions to either
366 // use an immediate field or to load the constant into a register
367 // Walk backwards and use direct indexes to allow insertion before current
369 Instruction* vmInstr = instrNode->getInstruction();
370 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
371 for (unsigned i = mvec.size(); i != 0; --i)
373 vector<MachineInstr*> loadConstVec =
374 FixConstantOperandsForInstr(vmInstr, mvec[i-1], Target);
376 mvec.insert(mvec.begin()+i-1, loadConstVec.begin(), loadConstVec.end());
382 //===----------------------------------------------------------------------===//
383 // createInstructionSelectionPass - Public entrypoint for instruction selection
384 // and this file as a whole...
386 Pass *createInstructionSelectionPass(TargetMachine &T) {
387 return new InstructionSelection(T);