5bb9b2b361996ffcdb5bf7ad82ddd1b2c647d5cc
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9PreSelection.cpp
1 //===- PreSelection.cpp - Specialize LLVM code for target machine ---------===//
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 a
11 // target machine, while remaining in legal portable LLVM form and
12 // preserving type information and type safety.  This is meant to enable
13 // dataflow optimizations on target-specific operations such as accesses to
14 // constants, globals, and array indexing.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "SparcInternals.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/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Transforms/Scalar.h"
30 #include <algorithm>
31
32 namespace llvm {
33
34 namespace {
35
36   //===--------------------------------------------------------------------===//
37   // PreSelection Pass - Specialize LLVM code for the current target machine.
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
52     // These methods do the actual work of specializing code
53     void visitInstruction(Instruction &I);   // common work for every instr. 
54     void visitGetElementPtrInst(GetElementPtrInst &I);
55     void visitCallInst(CallInst &I);
56     void visitPHINode(PHINode &PN);
57
58     // Helper functions for visiting operands of every instruction
59     // 
60     // visitOperands() works on every operand in [firstOp, lastOp-1].
61     // If lastOp==0, lastOp defaults to #operands or #incoming Phi values.
62     // 
63     // visitOneOperand() does all the work for one operand.
64     // 
65     void visitOperands(Instruction &I, int firstOp=0);
66     void visitOneOperand(Instruction &I, Value* Op, unsigned opNum,
67                          Instruction& insertBefore);
68   };
69
70 #if 0
71   // Register the pass...
72   RegisterPass<PreSelection> X("preselect",
73                                "Specialize LLVM code for a target machine"
74                                createPreselectionPass);
75 #endif
76
77 }  // end anonymous namespace
78
79
80 //------------------------------------------------------------------------------
81 // Helper functions used by methods of class PreSelection
82 //------------------------------------------------------------------------------
83
84
85 // getGlobalAddr(): Put address of a global into a v. register.
86 static GetElementPtrInst* getGlobalAddr(Value* ptr, Instruction& insertBefore) {
87   if (isa<ConstantPointerRef>(ptr))
88     ptr = cast<ConstantPointerRef>(ptr)->getValue();
89
90   return (isa<GlobalVariable>(ptr))
91     ? new GetElementPtrInst(ptr,
92                     std::vector<Value*>(1, ConstantSInt::get(Type::LongTy, 0U)),
93                     "addrOfGlobal", &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", &insertBefore);
126
127     default:                            // must be a binary operator
128       assert(CE->getOpcode() >= Instruction::BinaryOpsBegin &&
129              CE->getOpcode() <  Instruction::BinaryOpsEnd &&
130              "Unrecognized opcode in ConstantExpr");
131       getArg1 = CE->getOperand(0);
132       if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1))
133         getArg1 = DecomposeConstantExpr(CEarg, insertBefore);
134       getArg2 = CE->getOperand(1);
135       if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg2))
136         getArg2 = DecomposeConstantExpr(CEarg, insertBefore);
137       return BinaryOperator::create((Instruction::BinaryOps) CE->getOpcode(),
138                                     getArg1, getArg2,
139                                     "constantBinaryOp", &insertBefore);
140     }
141 }
142
143
144 //------------------------------------------------------------------------------
145 // Instruction visitor methods to perform instruction-specific operations
146 //------------------------------------------------------------------------------
147 inline void
148 PreSelection::visitOneOperand(Instruction &I, Value* Op, unsigned opNum,
149                               Instruction& insertBefore)
150 {
151   assert(&insertBefore != NULL && "Must have instruction to insert before.");
152
153   if (GetElementPtrInst* gep = getGlobalAddr(Op, insertBefore)) {
154     I.setOperand(opNum, gep);           // replace global operand
155     return;                             // nothing more to do for this op.
156   }
157
158   Constant* CV  = dyn_cast<Constant>(Op);
159   if (CV == NULL)
160     return;
161
162   if (ConstantExpr* CE = dyn_cast<ConstantExpr>(CV)) {
163     // load-time constant: factor it out so we optimize as best we can
164     Instruction* computeConst = DecomposeConstantExpr(CE, insertBefore);
165     I.setOperand(opNum, computeConst); // replace expr operand with result
166   } else if (instrInfo.ConstantTypeMustBeLoaded(CV)) {
167     // load address of constant into a register, then load the constant
168     // this is now done during instruction selection
169     // the constant will live in the MachineConstantPool later on
170   } else if (instrInfo.ConstantMayNotFitInImmedField(CV, &I)) {
171     // put the constant into a virtual register using a cast
172     CastInst* castI = new CastInst(CV, CV->getType(), "copyConst",
173                                    &insertBefore);
174     I.setOperand(opNum, castI);      // replace operand with copy in v.reg.
175   }
176 }
177
178 /// visitOperands - transform individual operands of all instructions:
179 /// -- Load "large" int constants into a virtual register.  What is large
180 ///    depends on the type of instruction and on the target architecture.
181 /// -- For any constants that cannot be put in an immediate field,
182 ///    load address into virtual register first, and then load the constant.
183 /// 
184 /// firstOp and lastOp can be used to skip leading and trailing operands.
185 /// If lastOp is 0, it defaults to #operands or #incoming Phi values.
186 ///  
187 inline void PreSelection::visitOperands(Instruction &I, int firstOp) {
188   // For any instruction other than PHI, copies go just before the instr.
189   for (unsigned i = firstOp, e = I.getNumOperands(); i != e; ++i)
190     visitOneOperand(I, I.getOperand(i), i, I);
191 }
192
193
194 void PreSelection::visitPHINode(PHINode &PN) {
195   // For a PHI, operand copies must be before the terminator of the
196   // appropriate predecessor basic block.  Remaining logic is simple
197   // so just handle PHIs and other instructions separately.
198   // 
199   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
200     visitOneOperand(PN, PN.getIncomingValue(i),
201                     PN.getOperandNumForIncomingValue(i),
202                     *PN.getIncomingBlock(i)->getTerminator());
203   // do not call visitOperands!
204 }
205
206 // Common work for *all* instructions.  This needs to be called explicitly
207 // by other visit<InstructionType> functions.
208 inline void PreSelection::visitInstruction(Instruction &I) { 
209   visitOperands(I);              // Perform operand transformations
210 }
211
212 // GetElementPtr instructions: check if pointer is a global
213 void PreSelection::visitGetElementPtrInst(GetElementPtrInst &I) { 
214   Instruction* curI = &I;
215
216   // Decompose multidimensional array references
217   if (I.getNumIndices() >= 2) {
218     // DecomposeArrayRef() replaces I and deletes it, if successful,
219     // so remember predecessor in order to find the replacement instruction.
220     // Also remember the basic block in case there is no predecessor.
221     Instruction* prevI = I.getPrev();
222     BasicBlock* bb = I.getParent();
223     if (DecomposeArrayRef(&I))
224       // first instr. replacing I
225       curI = cast<GetElementPtrInst>(prevI? prevI->getNext() : &bb->front());
226   }
227
228   // Perform other transformations common to all instructions
229   visitInstruction(*curI);
230 }
231
232 void PreSelection::visitCallInst(CallInst &I) {
233   // Tell visitOperands to ignore the function name if this is a direct call.
234   visitOperands(I, (/*firstOp=*/ I.getCalledFunction()? 1 : 0));
235 }
236
237 /// createPreSelectionPass - Public entry point for the PreSelection pass
238 ///
239 FunctionPass* createPreSelectionPass(const TargetMachine &TM) {
240   return new PreSelection(TM);
241 }
242
243 } // End llvm namespace