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