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 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
71 bool runOnFunction(Function &F);
75 // Register the pass...
76 static RegisterLLC<InstructionSelection>
77 X("instselect", "Instruction Selection", createInstructionSelectionPass);
79 TmpInstruction::TmpInstruction(Value *s1, Value *s2, const std::string &name)
80 : Instruction(s1->getType(), Instruction::UserOp1, name) {
81 Operands.push_back(Use(s1, this)); // s1 must be nonnull
83 Operands.push_back(Use(s2, this));
86 // TmpInstructions should not be garbage checked.
87 LeakDetector::removeGarbageObject(this);
90 // Constructor that requires the type of the temporary to be specified.
91 // Both S1 and S2 may be NULL.(
92 TmpInstruction::TmpInstruction(const Type *Ty, Value *s1, Value* s2,
93 const std::string &name)
94 : Instruction(Ty, Instruction::UserOp1, name) {
95 if (s1) { Operands.push_back(Use(s1, this)); }
96 if (s2) { Operands.push_back(Use(s2, this)); }
98 // TmpInstructions should not be garbage checked.
99 LeakDetector::removeGarbageObject(this);
103 bool InstructionSelection::runOnFunction(Function &F)
106 // Build the instruction trees to be given as inputs to BURG.
108 InstrForest instrForest(&F);
110 if (SelectDebugLevel >= Select_DebugInstTrees)
112 cerr << "\n\n*** Input to instruction selection for function "
113 << F.getName() << "\n\n" << F
114 << "\n\n*** Instruction trees for function "
115 << F.getName() << "\n\n";
120 // Invoke BURG instruction selection for each tree
122 for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
123 RI != instrForest.roots_end(); ++RI)
125 InstructionNode* basicNode = *RI;
126 assert(basicNode->parent() == NULL && "A `root' node has a parent?");
128 // Invoke BURM to label each tree node with a state
129 burm_label(basicNode);
131 if (SelectDebugLevel >= Select_DebugBurgTrees)
133 printcover(basicNode, 1, 0);
134 cerr << "\nCover cost == " << treecost(basicNode, 1, 0) << "\n\n";
135 printMatches(basicNode);
138 // Then recursively walk the tree to select instructions
139 SelectInstructionsForTree(basicNode, /*goalnt*/1);
143 // Record instructions in the vector for each basic block
145 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI)
146 for (BasicBlock::iterator II = BI->begin(); II != BI->end(); ++II) {
147 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(II);
148 MachineCodeForBasicBlock &MCBB = MachineCodeForBasicBlock::get(BI);
149 MCBB.insert(MCBB.end(), mvec.begin(), mvec.end());
152 // Insert phi elimination code
153 InsertCodeForPhis(F);
155 if (SelectDebugLevel >= Select_PrintMachineCode)
157 cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
158 MachineCodeForMethod::get(&F).dump();
165 //-------------------------------------------------------------------------
166 // This method inserts phi elimination code for all BBs in a method
167 //-------------------------------------------------------------------------
170 InstructionSelection::InsertCodeForPhis(Function &F)
172 // for all basic blocks in function
174 for (Function::iterator BB = F.begin(); BB != F.end(); ++BB) {
175 BasicBlock::InstListType &InstList = BB->getInstList();
176 for (BasicBlock::iterator IIt = InstList.begin();
177 PHINode *PN = dyn_cast<PHINode>(&*IIt); ++IIt) {
178 // FIXME: This is probably wrong...
179 Value *PhiCpRes = new PHINode(PN->getType(), "PhiCp:");
181 // The leak detector shouldn't track these nodes. They are not garbage,
182 // even though their parent field is never filled in.
184 LeakDetector::removeGarbageObject(PhiCpRes);
186 // for each incoming value of the phi, insert phi elimination
188 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
189 // insert the copy instruction to the predecessor BB
190 vector<MachineInstr*> mvec, CpVec;
191 Target.getRegInfo().cpValue2Value(PN->getIncomingValue(i), PhiCpRes,
193 for (vector<MachineInstr*>::iterator MI=mvec.begin();
194 MI != mvec.end(); ++MI) {
195 vector<MachineInstr*> CpVec2 =
196 FixConstantOperandsForInstr(PN, *MI, Target);
197 CpVec2.push_back(*MI);
198 CpVec.insert(CpVec.end(), CpVec2.begin(), CpVec2.end());
201 InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
204 vector<MachineInstr*> mvec;
205 Target.getRegInfo().cpValue2Value(PhiCpRes, PN, mvec);
207 // get an iterator to machine instructions in the BB
208 MachineCodeForBasicBlock& bbMvec = MachineCodeForBasicBlock::get(BB);
210 bbMvec.insert(bbMvec.begin(), mvec.begin(), mvec.end());
211 } // for each Phi Instr in BB
212 } // for all BBs in function
215 //-------------------------------------------------------------------------
216 // Thid method inserts a copy instruction to a predecessor BB as a result
217 // of phi elimination.
218 //-------------------------------------------------------------------------
221 InstructionSelection::InsertPhiElimInstructions(BasicBlock *BB,
222 const vector<MachineInstr*>& CpVec)
224 Instruction *TermInst = (Instruction*)BB->getTerminator();
225 MachineCodeForInstruction &MC4Term = MachineCodeForInstruction::get(TermInst);
226 MachineInstr *FirstMIOfTerm = MC4Term.front();
228 assert (FirstMIOfTerm && "No Machine Instrs for terminator");
230 MachineCodeForBasicBlock &bbMvec = MachineCodeForBasicBlock::get(BB);
232 // find the position of first machine instruction generated by the
233 // terminator of this BB
234 MachineCodeForBasicBlock::iterator MCIt =
235 std::find(bbMvec.begin(), bbMvec.end(), FirstMIOfTerm);
237 assert( MCIt != bbMvec.end() && "Start inst of terminator not found");
239 // insert the copy instructions just before the first machine instruction
240 // generated for the terminator
241 bbMvec.insert(MCIt, CpVec.begin(), CpVec.end());
245 //---------------------------------------------------------------------------
246 // Function SelectInstructionsForTree
248 // Recursively walk the tree to select instructions.
249 // Do this top-down so that child instructions can exploit decisions
250 // made at the child instructions.
252 // E.g., if br(setle(reg,const)) decides the constant is 0 and uses
253 // a branch-on-integer-register instruction, then the setle node
254 // can use that information to avoid generating the SUBcc instruction.
256 // Note that this cannot be done bottom-up because setle must do this
257 // only if it is a child of the branch (otherwise, the result of setle
258 // may be used by multiple instructions).
259 //---------------------------------------------------------------------------
262 InstructionSelection::SelectInstructionsForTree(InstrTreeNode* treeRoot,
265 // Get the rule that matches this node.
267 int ruleForNode = burm_rule(treeRoot->state, goalnt);
269 if (ruleForNode == 0) {
270 cerr << "Could not match instruction tree for instr selection\n";
274 // Get this rule's non-terminals and the corresponding child nodes (if any)
276 short *nts = burm_nts[ruleForNode];
278 // First, select instructions for the current node and rule.
279 // (If this is a list node, not an instruction, then skip this step).
280 // This function is specific to the target architecture.
282 if (treeRoot->opLabel != VRegListOp)
284 vector<MachineInstr*> minstrVec;
286 InstructionNode* instrNode = (InstructionNode*)treeRoot;
287 assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
289 GetInstructionsByRule(instrNode, ruleForNode, nts, Target, minstrVec);
291 MachineCodeForInstruction &mvec =
292 MachineCodeForInstruction::get(instrNode->getInstruction());
293 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
296 // Then, recursively compile the child nodes, if any.
299 { // i.e., there is at least one kid
300 InstrTreeNode* kids[2];
301 int currentRule = ruleForNode;
302 burm_kids(treeRoot, currentRule, kids);
304 // First skip over any chain rules so that we don't visit
305 // the current node again.
307 while (ThisIsAChainRule(currentRule))
309 currentRule = burm_rule(treeRoot->state, nts[0]);
310 nts = burm_nts[currentRule];
311 burm_kids(treeRoot, currentRule, kids);
314 // Now we have the first non-chain rule so we have found
315 // the actual child nodes. Recursively compile them.
317 for (unsigned i = 0; nts[i]; i++)
320 InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
321 if (nodeType == InstrTreeNode::NTVRegListNode ||
322 nodeType == InstrTreeNode::NTInstructionNode)
323 SelectInstructionsForTree(kids[i], nts[i]);
327 // Finally, do any postprocessing on this node after its children
328 // have been translated
330 if (treeRoot->opLabel != VRegListOp)
331 PostprocessMachineCodeForTree((InstructionNode*)treeRoot, ruleForNode, nts);
334 //---------------------------------------------------------------------------
335 // Function PostprocessMachineCodeForTree
337 // Apply any final cleanups to machine code for the root of a subtree
338 // after selection for all its children has been completed.
341 InstructionSelection::PostprocessMachineCodeForTree(InstructionNode* instrNode,
345 // Fix up any constant operands in the machine instructions to either
346 // use an immediate field or to load the constant into a register
347 // Walk backwards and use direct indexes to allow insertion before current
349 Instruction* vmInstr = instrNode->getInstruction();
350 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
351 for (unsigned i = mvec.size(); i != 0; --i)
353 vector<MachineInstr*> loadConstVec =
354 FixConstantOperandsForInstr(vmInstr, mvec[i-1], Target);
356 mvec.insert(mvec.begin()+i-1, loadConstVec.begin(), loadConstVec.end());
362 //===----------------------------------------------------------------------===//
363 // createInstructionSelectionPass - Public entrypoint for instruction selection
364 // and this file as a whole...
366 Pass *createInstructionSelectionPass(TargetMachine &T) {
367 return new InstructionSelection(T);