Convert many of the virtual TargetInstrInfo methods used as helper
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9PreSelection.cpp
1 //===- SparcV9PreSelection.cpp - Specialize LLVM code for SparcV9 ---------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the PreSelection pass which specializes LLVM code for
11 // the SparcV9 instruction selector, while remaining in legal portable LLVM
12 // form and preserving type information and type safety. This is meant to enable
13 // dataflow optimizations on SparcV9-specific operations such as accesses to
14 // constants, globals, and array indexing.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "SparcV9Internals.h"
19 #include "SparcV9InstrSelectionSupport.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/iMemory.h"
23 #include "llvm/iPHINode.h"
24 #include "llvm/iOther.h"
25 #include "llvm/Module.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/InstVisitor.h"
28 #include "llvm/Support/GetElementPtrTypeIterator.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Transforms/Scalar.h"
32 #include <algorithm>
33 using namespace llvm;
34
35 namespace {
36
37   //===--------------------------------------------------------------------===//
38   // PreSelection Pass - Specialize LLVM code for the SparcV9 instr. selector.
39   // 
40   class PreSelection : public FunctionPass, public InstVisitor<PreSelection> {
41     const TargetInstrInfo &instrInfo;
42
43   public:
44     PreSelection(const TargetMachine &T)
45       : instrInfo(*T.getInstrInfo()) {}
46
47     // runOnFunction - apply this pass to each Function
48     bool runOnFunction(Function &F) {
49       visit(F);
50       return true;
51     }
52     const char *getPassName() const { return "SparcV9 Instr. Pre-selection"; }
53
54     // These methods do the actual work of specializing code
55     void visitInstruction(Instruction &I);   // common work for every instr. 
56     void visitGetElementPtrInst(GetElementPtrInst &I);
57     void visitCallInst(CallInst &I);
58     void visitPHINode(PHINode &PN);
59
60     // Helper functions for visiting operands of every instruction
61     // 
62     // visitOperands() works on every operand in [firstOp, lastOp-1].
63     // If lastOp==0, lastOp defaults to #operands or #incoming Phi values.
64     // 
65     // visitOneOperand() does all the work for one operand.
66     // 
67     void visitOperands(Instruction &I, int firstOp=0);
68     void visitOneOperand(Instruction &I, Value* Op, unsigned opNum,
69                          Instruction& insertBefore);
70   };
71
72 #if 0
73   // Register the pass...
74   RegisterPass<PreSelection> X("preselect",
75                                "Specialize LLVM code for a target machine"
76                                createPreselectionPass);
77 #endif
78
79 }  // end anonymous namespace
80
81
82 //------------------------------------------------------------------------------
83 // Helper functions used by methods of class PreSelection
84 //------------------------------------------------------------------------------
85
86
87 // getGlobalAddr(): Put address of a global into a v. register.
88 static GetElementPtrInst* getGlobalAddr(Value* ptr, Instruction& insertBefore) {
89
90   return (isa<GlobalVariable>(ptr))
91     ? new GetElementPtrInst(ptr,
92                     std::vector<Value*>(1, ConstantSInt::get(Type::LongTy, 0U)),
93                     "addrOfGlobal:" + ptr->getName(), &insertBefore)
94     : NULL;
95 }
96
97 // Wrapper on Constant::classof to use in find_if
98 inline static bool nonConstant(const Use& U) {
99   return ! isa<Constant>(U);
100 }
101
102 static Instruction* DecomposeConstantExpr(ConstantExpr* CE,
103                                           Instruction& insertBefore)
104 {
105   Value *getArg1, *getArg2;
106   
107   switch(CE->getOpcode())
108     {
109     case Instruction::Cast:
110       getArg1 = CE->getOperand(0);
111       if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1))
112         getArg1 = DecomposeConstantExpr(CEarg, insertBefore);
113       return new CastInst(getArg1, CE->getType(), "constantCast",&insertBefore);
114
115     case Instruction::GetElementPtr:
116       assert(find_if(CE->op_begin()+1, CE->op_end(),nonConstant) == CE->op_end()
117              && "All indices in ConstantExpr getelementptr must be constant!");
118       getArg1 = CE->getOperand(0);
119       if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1))
120         getArg1 = DecomposeConstantExpr(CEarg, insertBefore);
121       else if (GetElementPtrInst* gep = getGlobalAddr(getArg1, insertBefore))
122         getArg1 = gep;
123       return new GetElementPtrInst(getArg1,
124                           std::vector<Value*>(CE->op_begin()+1, CE->op_end()),
125                           "constantGEP:" + getArg1->getName(), &insertBefore);
126                           
127     case Instruction::Select: {
128       Value *C, *S1, *S2;
129       C = CE->getOperand (0);
130       if (ConstantExpr* CEarg = dyn_cast<ConstantExpr> (C))
131         C = DecomposeConstantExpr (CEarg, insertBefore);
132       S1 = CE->getOperand (1);
133       if (ConstantExpr* CEarg = dyn_cast<ConstantExpr> (S1))
134         S1 = DecomposeConstantExpr (CEarg, insertBefore);
135       S2 = CE->getOperand (2);
136       if (ConstantExpr* CEarg = dyn_cast<ConstantExpr> (S2))
137         S2 = DecomposeConstantExpr (CEarg, insertBefore);
138       return new SelectInst (C, S1, S2, "constantSelect", &insertBefore);
139     }
140     
141     default:                            // must be a binary operator
142       assert(CE->getOpcode() >= Instruction::BinaryOpsBegin &&
143              CE->getOpcode() <  Instruction::BinaryOpsEnd &&
144              "Unhandled opcode in ConstantExpr");
145       getArg1 = CE->getOperand(0);
146       if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1))
147         getArg1 = DecomposeConstantExpr(CEarg, insertBefore);
148       getArg2 = CE->getOperand(1);
149       if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg2))
150         getArg2 = DecomposeConstantExpr(CEarg, insertBefore);
151       return BinaryOperator::create((Instruction::BinaryOps) CE->getOpcode(),
152                                     getArg1, getArg2,
153                                     "constantBinaryOp", &insertBefore);
154     }
155 }
156
157
158 //------------------------------------------------------------------------------
159 // Instruction visitor methods to perform instruction-specific operations
160 //------------------------------------------------------------------------------
161 inline void
162 PreSelection::visitOneOperand(Instruction &I, Value* Op, unsigned opNum,
163                               Instruction& insertBefore)
164 {
165   assert(&insertBefore != NULL && "Must have instruction to insert before.");
166
167   if (GetElementPtrInst* gep = getGlobalAddr(Op, insertBefore)) {
168     I.setOperand(opNum, gep);           // replace global operand
169     return;                             // nothing more to do for this op.
170   }
171
172   Constant* CV  = dyn_cast<Constant>(Op);
173   if (CV == NULL)
174     return;
175
176   if (ConstantExpr* CE = dyn_cast<ConstantExpr>(CV)) {
177     // load-time constant: factor it out so we optimize as best we can
178     Instruction* computeConst = DecomposeConstantExpr(CE, insertBefore);
179     I.setOperand(opNum, computeConst); // replace expr operand with result
180   } else if (instrInfo.ConstantTypeMustBeLoaded(CV)) {
181     // load address of constant into a register, then load the constant
182     // this is now done during instruction selection
183     // the constant will live in the MachineConstantPool later on
184   } else if (ConstantMayNotFitInImmedField(CV, &I)) {
185     // put the constant into a virtual register using a cast
186     CastInst* castI = new CastInst(CV, CV->getType(), "copyConst",
187                                    &insertBefore);
188     I.setOperand(opNum, castI);      // replace operand with copy in v.reg.
189   }
190 }
191
192 /// visitOperands - transform individual operands of all instructions:
193 /// -- Load "large" int constants into a virtual register.  What is large
194 ///    depends on the type of instruction and on the target architecture.
195 /// -- For any constants that cannot be put in an immediate field,
196 ///    load address into virtual register first, and then load the constant.
197 /// 
198 /// firstOp and lastOp can be used to skip leading and trailing operands.
199 /// If lastOp is 0, it defaults to #operands or #incoming Phi values.
200 ///  
201 inline void PreSelection::visitOperands(Instruction &I, int firstOp) {
202   // For any instruction other than PHI, copies go just before the instr.
203   for (unsigned i = firstOp, e = I.getNumOperands(); i != e; ++i)
204     visitOneOperand(I, I.getOperand(i), i, I);
205 }
206
207
208 void PreSelection::visitPHINode(PHINode &PN) {
209   // For a PHI, operand copies must be before the terminator of the
210   // appropriate predecessor basic block.  Remaining logic is simple
211   // so just handle PHIs and other instructions separately.
212   // 
213   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
214     visitOneOperand(PN, PN.getIncomingValue(i),
215                     PN.getOperandNumForIncomingValue(i),
216                     *PN.getIncomingBlock(i)->getTerminator());
217   // do not call visitOperands!
218 }
219
220 // Common work for *all* instructions.  This needs to be called explicitly
221 // by other visit<InstructionType> functions.
222 inline void PreSelection::visitInstruction(Instruction &I) { 
223   visitOperands(I);              // Perform operand transformations
224 }
225
226 // GetElementPtr instructions: check if pointer is a global
227 void PreSelection::visitGetElementPtrInst(GetElementPtrInst &I) { 
228   Instruction* curI = &I;
229
230   // The Sparc backend doesn't handle array indexes that are not long types, so
231   // insert a cast from whatever it is to long, if the sequential type index is
232   // not a long already.
233   unsigned Idx = 1;
234   for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I); TI != E;
235        ++TI, ++Idx)
236     if (isa<SequentialType>(*TI) &&
237         I.getOperand(Idx)->getType() != Type::LongTy) {
238       Value *Op = I.getOperand(Idx);
239       if (Op->getType()->isUnsigned())    // Must sign extend!
240         Op = new CastInst(Op, Op->getType()->getSignedVersion(), "v9", &I);
241       if (Op->getType() != Type::LongTy)
242         Op = new CastInst(Op, Type::LongTy, "v9", &I);
243       I.setOperand(Idx, Op);
244     }
245
246
247   // Decompose multidimensional array references
248   if (I.getNumIndices() >= 2) {
249     // DecomposeArrayRef() replaces I and deletes it, if successful,
250     // so remember predecessor in order to find the replacement instruction.
251     // Also remember the basic block in case there is no predecessor.
252     Instruction* prevI = I.getPrev();
253     BasicBlock* bb = I.getParent();
254     if (DecomposeArrayRef(&I))
255       // first instr. replacing I
256       curI = cast<GetElementPtrInst>(prevI? prevI->getNext() : &bb->front());
257   }
258
259   // Perform other transformations common to all instructions
260   visitInstruction(*curI);
261 }
262
263 void PreSelection::visitCallInst(CallInst &I) {
264   // Tell visitOperands to ignore the function name if this is a direct call.
265   visitOperands(I, (/*firstOp=*/ I.getCalledFunction()? 1 : 0));
266 }
267
268 /// createPreSelectionPass - Public entry point for the PreSelection pass
269 ///
270 FunctionPass* llvm::createPreSelectionPass(const TargetMachine &TM) {
271   return new PreSelection(TM);
272 }