blob: 6f17b52b0a033989bb9758e4887d57efcb4e6902 [file] [log] [blame]
Vikram S. Adveabf055c2002-09-20 00:29:28 +00001//===- PreSelection.cpp - Specialize LLVM code for target machine ---------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
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//===----------------------------------------------------------------------===//
Vikram S. Adveabf055c2002-09-20 00:29:28 +00009//
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
Chris Lattner67699ff2003-09-01 20:33:07 +000018#include "SparcInternals.h"
Vikram S. Adveabf055c2002-09-20 00:29:28 +000019#include "llvm/Target/TargetMachine.h"
Chris Lattner3501fea2003-01-14 22:00:31 +000020#include "llvm/Target/TargetInstrInfo.h"
Vikram S. Adveabf055c2002-09-20 00:29:28 +000021#include "llvm/Transforms/Scalar.h"
22#include "llvm/Support/InstVisitor.h"
23#include "llvm/Module.h"
24#include "llvm/Constants.h"
25#include "llvm/iMemory.h"
26#include "llvm/iPHINode.h"
27#include "llvm/iOther.h"
28#include "llvm/DerivedTypes.h"
29#include "llvm/Pass.h"
Vikram S. Adveabf055c2002-09-20 00:29:28 +000030#include "Support/CommandLine.h"
Vikram S. Adved0451a92002-10-13 00:01:57 +000031#include <algorithm>
Vikram S. Adveabf055c2002-09-20 00:29:28 +000032
33namespace {
34 //===--------------------------------------------------------------------===//
35 // SelectDebugLevel - Allow command line control over debugging.
36 //
37 enum PreSelectDebugLevel_t {
38 PreSelect_NoDebugInfo,
39 PreSelect_PrintOutput,
40 };
41
42 // Enable Debug Options to be specified on the command line
43 cl::opt<PreSelectDebugLevel_t>
44 PreSelectDebugLevel("dpreselect", cl::Hidden,
45 cl::desc("debug information for target-dependent pre-selection"),
46 cl::values(
47 clEnumValN(PreSelect_NoDebugInfo, "n", "disable debug output (default)"),
48 clEnumValN(PreSelect_PrintOutput, "y", "print generated machine code"),
49 /* default level = */ PreSelect_NoDebugInfo));
50
51
52 //===--------------------------------------------------------------------===//
53 // class ConstantPoolForModule:
54 //
55 // The pool of constants that must be emitted for a module.
56 // This is a single pool for the entire module and is shared by
57 // all invocations of the PreSelection pass for this module by putting
Vikram S. Adved0451a92002-10-13 00:01:57 +000058 // this as an annotation on the Module object.
Vikram S. Adveabf055c2002-09-20 00:29:28 +000059 // A single GlobalVariable is created for each constant in the pool
60 // representing the memory for that constant.
61 //
Chris Lattner5ff7ef52003-05-01 20:28:45 +000062 AnnotationID CPFM_AID(
Vikram S. Adveabf055c2002-09-20 00:29:28 +000063 AnnotationManager::getID("CodeGen::ConstantPoolForModule"));
64
Chris Lattner5ff7ef52003-05-01 20:28:45 +000065 class ConstantPoolForModule : private Annotation {
Vikram S. Adveabf055c2002-09-20 00:29:28 +000066 Module* myModule;
67 std::map<const Constant*, GlobalVariable*> gvars;
68 std::map<const Constant*, GlobalVariable*> origGVars;
69 ConstantPoolForModule(Module* M); // called only by annotation builder
Chris Lattner5ff7ef52003-05-01 20:28:45 +000070 ConstantPoolForModule(); // DO NOT IMPLEMENT
71 void operator=(const ConstantPoolForModule&); // DO NOT IMPLEMENT
Vikram S. Adveabf055c2002-09-20 00:29:28 +000072 public:
73 static ConstantPoolForModule& get(Module* M) {
74 ConstantPoolForModule* cpool =
75 (ConstantPoolForModule*) M->getAnnotation(CPFM_AID);
76 if (cpool == NULL) // create a new annotation and add it to the Module
77 M->addAnnotation(cpool = new ConstantPoolForModule(M));
78 return *cpool;
79 }
80
81 GlobalVariable* getGlobalForConstant(Constant* CV) {
82 std::map<const Constant*, GlobalVariable*>::iterator I = gvars.find(CV);
83 if (I != gvars.end())
84 return I->second; // global exists so return it
85 return addToConstantPool(CV); // create a new global and return it
86 }
87
88 GlobalVariable* addToConstantPool(Constant* CV) {
89 GlobalVariable*& GV = gvars[CV]; // handle to global var entry in map
90 if (GV == NULL)
91 { // check if a global constant already existed; otherwise create one
92 std::map<const Constant*, GlobalVariable*>::iterator PI =
93 origGVars.find(CV);
94 if (PI != origGVars.end())
95 GV = PI->second; // put in map
96 else
97 {
Chris Lattner4ad02e72003-04-16 20:28:45 +000098 GV = new GlobalVariable(CV->getType(), true, //put in map
99 GlobalValue::InternalLinkage, CV);
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000100 myModule->getGlobalList().push_back(GV); // GV owned by module now
101 }
102 }
103 return GV;
104 }
105 };
106
107 /* ctor */
108 ConstantPoolForModule::ConstantPoolForModule(Module* M)
109 : Annotation(CPFM_AID), myModule(M)
110 {
111 // Build reverse map for pre-existing global constants so we can find them
112 for (Module::giterator GI = M->gbegin(), GE = M->gend(); GI != GE; ++GI)
113 if (GI->hasInitializer() && GI->isConstant())
114 origGVars[GI->getInitializer()] = GI;
115 }
116
117 //===--------------------------------------------------------------------===//
118 // PreSelection Pass - Specialize LLVM code for the current target machine.
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000119 //
120 class PreSelection : public BasicBlockPass, public InstVisitor<PreSelection>
121 {
122 const TargetMachine &target;
Vikram S. Advecf819452003-06-05 21:12:56 +0000123 const TargetInstrInfo &instrInfo;
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000124 Function* function;
125
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000126 GlobalVariable* getGlobalForConstant(Constant* CV) {
127 Module* M = function->getParent();
128 return ConstantPoolForModule::get(M).getGlobalForConstant(CV);
129 }
130
131 public:
Vikram S. Advecf819452003-06-05 21:12:56 +0000132 PreSelection (const TargetMachine &T):
133 target(T), instrInfo(T.getInstrInfo()), function(NULL) {}
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000134
135 // runOnBasicBlock - apply this pass to each BB
136 bool runOnBasicBlock(BasicBlock &BB) {
137 function = BB.getParent();
138 this->visit(BB);
139 return true;
140 }
141
142 bool doFinalization(Function &F) {
143 if (PreSelectDebugLevel >= PreSelect_PrintOutput)
Chris Lattner64317fc2003-01-14 20:32:10 +0000144 std::cerr << "\n\n*** LLVM code after pre-selection for function "
145 << F.getName() << ":\n\n" << F;
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000146 return false;
147 }
148
149 // These methods do the actual work of specializing code
150 void visitInstruction(Instruction &I); // common work for every instr.
151 void visitGetElementPtrInst(GetElementPtrInst &I);
Vikram S. Adve96358672003-05-31 07:34:57 +0000152 void visitCallInst(CallInst &I);
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000153
154 // Helper functions for visiting operands of every instruction
Vikram S. Adve96358672003-05-31 07:34:57 +0000155 //
156 // visitOperands() works on every operand in [firstOp, lastOp-1].
157 // If lastOp==0, lastOp defaults to #operands or #incoming Phi values.
158 //
159 // visitOneOperand() does all the work for one operand.
160 //
161 void visitOperands(Instruction &I, int firstOp=0, int lastOp=0);
162 void visitOneOperand(Instruction &I, Value* Op, unsigned opNum,
163 Instruction& insertBefore);
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000164 };
Chris Lattnerec8aae32003-04-24 18:35:51 +0000165
166 // Register the pass...
167 RegisterOpt<PreSelection> X("preselect",
168 "Specialize LLVM code for a target machine",
169 createPreSelectionPass);
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000170} // end anonymous namespace
171
172
Vikram S. Adved0451a92002-10-13 00:01:57 +0000173//------------------------------------------------------------------------------
174// Helper functions used by methods of class PreSelection
175//------------------------------------------------------------------------------
176
177
178// getGlobalAddr(): Put address of a global into a v. register.
179static GetElementPtrInst* getGlobalAddr(Value* ptr, Instruction& insertBefore)
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000180{
Vikram S. Adved0451a92002-10-13 00:01:57 +0000181 if (isa<ConstantPointerRef>(ptr))
182 ptr = cast<ConstantPointerRef>(ptr)->getValue();
183
Chris Lattner2ab5e122003-06-04 01:24:40 +0000184 return (isa<GlobalVariable>(ptr))
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000185 ? new GetElementPtrInst(ptr,
186 std::vector<Value*>(1, ConstantSInt::get(Type::LongTy, 0U)),
Vikram S. Adved0451a92002-10-13 00:01:57 +0000187 "addrOfGlobal", &insertBefore)
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000188 : NULL;
189}
190
191
Vikram S. Adved0451a92002-10-13 00:01:57 +0000192// Wrapper on Constant::classof to use in find_if :-(
193inline static bool nonConstant(const Use& U)
194{
195 return ! isa<Constant>(U);
196}
197
198
199static Instruction* DecomposeConstantExpr(ConstantExpr* CE,
200 Instruction& insertBefore)
201{
202 Value *getArg1, *getArg2;
203
204 switch(CE->getOpcode())
205 {
206 case Instruction::Cast:
207 getArg1 = CE->getOperand(0);
208 if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1))
209 getArg1 = DecomposeConstantExpr(CEarg, insertBefore);
210 return new CastInst(getArg1, CE->getType(), "constantCast",&insertBefore);
211
212 case Instruction::GetElementPtr:
Chris Lattnerdc476b82002-10-27 19:09:51 +0000213 assert(find_if(CE->op_begin()+1, CE->op_end(),nonConstant) == CE->op_end()
Vikram S. Adved0451a92002-10-13 00:01:57 +0000214 && "All indices in ConstantExpr getelementptr must be constant!");
Vikram S. Adved0451a92002-10-13 00:01:57 +0000215 getArg1 = CE->getOperand(0);
216 if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1))
217 getArg1 = DecomposeConstantExpr(CEarg, insertBefore);
218 else if (GetElementPtrInst* gep = getGlobalAddr(getArg1, insertBefore))
219 getArg1 = gep;
220 return new GetElementPtrInst(getArg1,
Chris Lattnerdc476b82002-10-27 19:09:51 +0000221 std::vector<Value*>(CE->op_begin()+1, CE->op_end()),
Vikram S. Adved0451a92002-10-13 00:01:57 +0000222 "constantGEP", &insertBefore);
223
224 default: // must be a binary operator
Chris Lattner0b16ae22002-10-13 19:39:16 +0000225 assert(CE->getOpcode() >= Instruction::BinaryOpsBegin &&
226 CE->getOpcode() < Instruction::BinaryOpsEnd &&
Vikram S. Adved0451a92002-10-13 00:01:57 +0000227 "Unrecognized opcode in ConstantExpr");
228 getArg1 = CE->getOperand(0);
229 if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1))
230 getArg1 = DecomposeConstantExpr(CEarg, insertBefore);
231 getArg2 = CE->getOperand(1);
232 if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg2))
233 getArg2 = DecomposeConstantExpr(CEarg, insertBefore);
234 return BinaryOperator::create((Instruction::BinaryOps) CE->getOpcode(),
235 getArg1, getArg2,
236 "constantBinaryOp", &insertBefore);
237 }
238}
239
240
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000241//------------------------------------------------------------------------------
242// Instruction visitor methods to perform instruction-specific operations
243//------------------------------------------------------------------------------
Vikram S. Advecf819452003-06-05 21:12:56 +0000244inline void
245PreSelection::visitOneOperand(Instruction &I, Value* Op, unsigned opNum,
246 Instruction& insertBefore)
247{
Vikram S. Adve799ffee2003-07-02 01:23:15 +0000248 assert(&insertBefore != NULL && "Must have instruction to insert before.");
249
Vikram S. Advecf819452003-06-05 21:12:56 +0000250 if (GetElementPtrInst* gep = getGlobalAddr(Op, insertBefore)) {
251 I.setOperand(opNum, gep); // replace global operand
Vikram S. Adve799ffee2003-07-02 01:23:15 +0000252 return; // nothing more to do for this op.
Vikram S. Advecf819452003-06-05 21:12:56 +0000253 }
254
255 Constant* CV = dyn_cast<Constant>(Op);
256 if (CV == NULL)
257 return;
258
259 if (ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
260 { // load-time constant: factor it out so we optimize as best we can
261 Instruction* computeConst = DecomposeConstantExpr(CE, insertBefore);
262 I.setOperand(opNum, computeConst); // replace expr operand with result
263 }
264 else if (instrInfo.ConstantTypeMustBeLoaded(CV))
265 { // load address of constant into a register, then load the constant
266 GetElementPtrInst* gep = getGlobalAddr(getGlobalForConstant(CV),
267 insertBefore);
268 LoadInst* ldI = new LoadInst(gep, "loadConst", &insertBefore);
269 I.setOperand(opNum, ldI); // replace operand with copy in v.reg.
270 }
271 else if (instrInfo.ConstantMayNotFitInImmedField(CV, &I))
272 { // put the constant into a virtual register using a cast
273 CastInst* castI = new CastInst(CV, CV->getType(), "copyConst",
274 &insertBefore);
275 I.setOperand(opNum, castI); // replace operand with copy in v.reg.
276 }
277}
278
279// visitOperands() transforms individual operands of all instructions:
280// -- Load "large" int constants into a virtual register. What is large
281// depends on the type of instruction and on the target architecture.
282// -- For any constants that cannot be put in an immediate field,
283// load address into virtual register first, and then load the constant.
284//
285// firstOp and lastOp can be used to skip leading and trailing operands.
286// If lastOp is 0, it defaults to #operands or #incoming Phi values.
287//
288inline void
289PreSelection::visitOperands(Instruction &I, int firstOp, int lastOp)
290{
291 // For any instruction other than PHI, copies go just before the instr.
292 // For a PHI, operand copies must be before the terminator of the
293 // appropriate predecessor basic block. Remaining logic is simple
294 // so just handle PHIs and other instructions separately.
295 //
296 if (PHINode* phi = dyn_cast<PHINode>(&I))
297 {
298 if (lastOp == 0)
299 lastOp = phi->getNumIncomingValues();
300 for (unsigned i=firstOp, N=lastOp; i < N; ++i)
301 this->visitOneOperand(I, phi->getIncomingValue(i),
302 phi->getOperandNumForIncomingValue(i),
303 * phi->getIncomingBlock(i)->getTerminator());
304 }
305 else
306 {
307 if (lastOp == 0)
308 lastOp = I.getNumOperands();
309 for (unsigned i=firstOp, N=lastOp; i < N; ++i)
310 this->visitOneOperand(I, I.getOperand(i), i, I);
311 }
312}
313
314
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000315
316// Common work for *all* instructions. This needs to be called explicitly
317// by other visit<InstructionType> functions.
318inline void
319PreSelection::visitInstruction(Instruction &I)
320{
321 visitOperands(I); // Perform operand transformations
322}
323
324
325// GetElementPtr instructions: check if pointer is a global
326void
327PreSelection::visitGetElementPtrInst(GetElementPtrInst &I)
328{
Vikram S. Adve799ffee2003-07-02 01:23:15 +0000329 Instruction* curI = &I;
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000330
331 // Decompose multidimensional array references
Vikram S. Adve799ffee2003-07-02 01:23:15 +0000332 if (I.getNumIndices() >= 2) {
333 // DecomposeArrayRef() replaces I and deletes it, if successful,
334 // so remember predecessor in order to find the replacement instruction.
335 // Also remember the basic block in case there is no predecessor.
336 Instruction* prevI = I.getPrev();
337 BasicBlock* bb = I.getParent();
338 if (DecomposeArrayRef(&I))
339 // first instr. replacing I
340 curI = cast<GetElementPtrInst>(prevI? prevI->getNext() : &bb->front());
341 }
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000342
343 // Perform other transformations common to all instructions
Vikram S. Adve799ffee2003-07-02 01:23:15 +0000344 visitInstruction(*curI);
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000345}
346
347
Vikram S. Adve96358672003-05-31 07:34:57 +0000348void
349PreSelection::visitCallInst(CallInst &I)
350{
351 // Tell visitOperands to ignore the function name if this is a direct call.
352 visitOperands(I, (/*firstOp=*/ I.getCalledFunction()? 1 : 0));
353}
354
Vikram S. Advee9cb7352002-09-27 14:24:45 +0000355
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000356//===----------------------------------------------------------------------===//
357// createPreSelectionPass - Public entrypoint for pre-selection pass
358// and this file as a whole...
359//
360Pass*
361createPreSelectionPass(TargetMachine &T)
362{
363 return new PreSelection(T);
364}
365