blob: 216091787f1095b6c0d1d71d51994bda1f3f39cc [file] [log] [blame]
Vikram S. Adveabf055c2002-09-20 00:29:28 +00001//===- PreSelection.cpp - Specialize LLVM code for target machine ---------===//
2//
3// This file defines the PreSelection pass which specializes LLVM code for a
4// target machine, while remaining in legal portable LLVM form and
5// preserving type information and type safety. This is meant to enable
6// dataflow optimizations on target-specific operations such as accesses to
7// constants, globals, and array indexing.
8//
9//===----------------------------------------------------------------------===//
10
11#include "llvm/CodeGen/PreSelection.h"
12#include "llvm/Target/TargetMachine.h"
Chris Lattner3501fea2003-01-14 22:00:31 +000013#include "llvm/Target/TargetInstrInfo.h"
Vikram S. Adveabf055c2002-09-20 00:29:28 +000014#include "llvm/Transforms/Scalar.h"
15#include "llvm/Support/InstVisitor.h"
16#include "llvm/Module.h"
17#include "llvm/Constants.h"
18#include "llvm/iMemory.h"
19#include "llvm/iPHINode.h"
20#include "llvm/iOther.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Pass.h"
Vikram S. Adveabf055c2002-09-20 00:29:28 +000023#include "Support/CommandLine.h"
Vikram S. Adved0451a92002-10-13 00:01:57 +000024#include <algorithm>
Vikram S. Adveabf055c2002-09-20 00:29:28 +000025
26namespace {
27 //===--------------------------------------------------------------------===//
28 // SelectDebugLevel - Allow command line control over debugging.
29 //
30 enum PreSelectDebugLevel_t {
31 PreSelect_NoDebugInfo,
32 PreSelect_PrintOutput,
33 };
34
35 // Enable Debug Options to be specified on the command line
36 cl::opt<PreSelectDebugLevel_t>
37 PreSelectDebugLevel("dpreselect", cl::Hidden,
38 cl::desc("debug information for target-dependent pre-selection"),
39 cl::values(
40 clEnumValN(PreSelect_NoDebugInfo, "n", "disable debug output (default)"),
41 clEnumValN(PreSelect_PrintOutput, "y", "print generated machine code"),
42 /* default level = */ PreSelect_NoDebugInfo));
43
44
45 //===--------------------------------------------------------------------===//
46 // class ConstantPoolForModule:
47 //
48 // The pool of constants that must be emitted for a module.
49 // This is a single pool for the entire module and is shared by
50 // all invocations of the PreSelection pass for this module by putting
Vikram S. Adved0451a92002-10-13 00:01:57 +000051 // this as an annotation on the Module object.
Vikram S. Adveabf055c2002-09-20 00:29:28 +000052 // A single GlobalVariable is created for each constant in the pool
53 // representing the memory for that constant.
54 //
55 static AnnotationID CPFM_AID(
56 AnnotationManager::getID("CodeGen::ConstantPoolForModule"));
57
58 class ConstantPoolForModule: private Annotation, public NonCopyable {
59 Module* myModule;
60 std::map<const Constant*, GlobalVariable*> gvars;
61 std::map<const Constant*, GlobalVariable*> origGVars;
62 ConstantPoolForModule(Module* M); // called only by annotation builder
63 ConstantPoolForModule(); // do not implement
64 public:
65 static ConstantPoolForModule& get(Module* M) {
66 ConstantPoolForModule* cpool =
67 (ConstantPoolForModule*) M->getAnnotation(CPFM_AID);
68 if (cpool == NULL) // create a new annotation and add it to the Module
69 M->addAnnotation(cpool = new ConstantPoolForModule(M));
70 return *cpool;
71 }
72
73 GlobalVariable* getGlobalForConstant(Constant* CV) {
74 std::map<const Constant*, GlobalVariable*>::iterator I = gvars.find(CV);
75 if (I != gvars.end())
76 return I->second; // global exists so return it
77 return addToConstantPool(CV); // create a new global and return it
78 }
79
80 GlobalVariable* addToConstantPool(Constant* CV) {
81 GlobalVariable*& GV = gvars[CV]; // handle to global var entry in map
82 if (GV == NULL)
83 { // check if a global constant already existed; otherwise create one
84 std::map<const Constant*, GlobalVariable*>::iterator PI =
85 origGVars.find(CV);
86 if (PI != origGVars.end())
87 GV = PI->second; // put in map
88 else
89 {
Chris Lattner4ad02e72003-04-16 20:28:45 +000090 GV = new GlobalVariable(CV->getType(), true, //put in map
91 GlobalValue::InternalLinkage, CV);
Vikram S. Adveabf055c2002-09-20 00:29:28 +000092 myModule->getGlobalList().push_back(GV); // GV owned by module now
93 }
94 }
95 return GV;
96 }
97 };
98
99 /* ctor */
100 ConstantPoolForModule::ConstantPoolForModule(Module* M)
101 : Annotation(CPFM_AID), myModule(M)
102 {
103 // Build reverse map for pre-existing global constants so we can find them
104 for (Module::giterator GI = M->gbegin(), GE = M->gend(); GI != GE; ++GI)
105 if (GI->hasInitializer() && GI->isConstant())
106 origGVars[GI->getInitializer()] = GI;
107 }
108
109 //===--------------------------------------------------------------------===//
110 // PreSelection Pass - Specialize LLVM code for the current target machine.
111 // This was and will be a basicblock pass, but make it a FunctionPass until
112 // BasicBlockPass ::doFinalization(Function&) is available.
113 //
114 class PreSelection : public BasicBlockPass, public InstVisitor<PreSelection>
115 {
116 const TargetMachine &target;
117 Function* function;
118
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000119 GlobalVariable* getGlobalForConstant(Constant* CV) {
120 Module* M = function->getParent();
121 return ConstantPoolForModule::get(M).getGlobalForConstant(CV);
122 }
123
124 public:
125 PreSelection (const TargetMachine &T): target(T), function(NULL) {}
126
127 // runOnBasicBlock - apply this pass to each BB
128 bool runOnBasicBlock(BasicBlock &BB) {
129 function = BB.getParent();
130 this->visit(BB);
131 return true;
132 }
133
134 bool doFinalization(Function &F) {
135 if (PreSelectDebugLevel >= PreSelect_PrintOutput)
Chris Lattner64317fc2003-01-14 20:32:10 +0000136 std::cerr << "\n\n*** LLVM code after pre-selection for function "
137 << F.getName() << ":\n\n" << F;
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000138 return false;
139 }
140
141 // These methods do the actual work of specializing code
142 void visitInstruction(Instruction &I); // common work for every instr.
143 void visitGetElementPtrInst(GetElementPtrInst &I);
144 void visitLoadInst(LoadInst &I);
Vikram S. Advee9cb7352002-09-27 14:24:45 +0000145 void visitCastInst(CastInst &I);
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000146 void visitStoreInst(StoreInst &I);
147
148 // Helper functions for visiting operands of every instruction
149 void visitOperands(Instruction &I); // work on all operands of instr.
150 void visitOneOperand(Instruction &I, Constant* CV, unsigned opNum,
151 Instruction& insertBefore); // iworks on one operand
152 };
Chris Lattnerec8aae32003-04-24 18:35:51 +0000153
154 // Register the pass...
155 RegisterOpt<PreSelection> X("preselect",
156 "Specialize LLVM code for a target machine",
157 createPreSelectionPass);
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000158} // end anonymous namespace
159
160
Vikram S. Adved0451a92002-10-13 00:01:57 +0000161//------------------------------------------------------------------------------
162// Helper functions used by methods of class PreSelection
163//------------------------------------------------------------------------------
164
165
166// getGlobalAddr(): Put address of a global into a v. register.
167static GetElementPtrInst* getGlobalAddr(Value* ptr, Instruction& insertBefore)
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000168{
Vikram S. Adved0451a92002-10-13 00:01:57 +0000169 if (isa<ConstantPointerRef>(ptr))
170 ptr = cast<ConstantPointerRef>(ptr)->getValue();
171
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000172 return (isa<GlobalValue>(ptr))
173 ? new GetElementPtrInst(ptr,
174 std::vector<Value*>(1, ConstantSInt::get(Type::LongTy, 0U)),
Vikram S. Adved0451a92002-10-13 00:01:57 +0000175 "addrOfGlobal", &insertBefore)
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000176 : NULL;
177}
178
179
Vikram S. Adved0451a92002-10-13 00:01:57 +0000180// Wrapper on Constant::classof to use in find_if :-(
181inline static bool nonConstant(const Use& U)
182{
183 return ! isa<Constant>(U);
184}
185
186
187static Instruction* DecomposeConstantExpr(ConstantExpr* CE,
188 Instruction& insertBefore)
189{
190 Value *getArg1, *getArg2;
191
192 switch(CE->getOpcode())
193 {
194 case Instruction::Cast:
195 getArg1 = CE->getOperand(0);
196 if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1))
197 getArg1 = DecomposeConstantExpr(CEarg, insertBefore);
198 return new CastInst(getArg1, CE->getType(), "constantCast",&insertBefore);
199
200 case Instruction::GetElementPtr:
Chris Lattnerdc476b82002-10-27 19:09:51 +0000201 assert(find_if(CE->op_begin()+1, CE->op_end(),nonConstant) == CE->op_end()
Vikram S. Adved0451a92002-10-13 00:01:57 +0000202 && "All indices in ConstantExpr getelementptr must be constant!");
Vikram S. Adved0451a92002-10-13 00:01:57 +0000203 getArg1 = CE->getOperand(0);
204 if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1))
205 getArg1 = DecomposeConstantExpr(CEarg, insertBefore);
206 else if (GetElementPtrInst* gep = getGlobalAddr(getArg1, insertBefore))
207 getArg1 = gep;
208 return new GetElementPtrInst(getArg1,
Chris Lattnerdc476b82002-10-27 19:09:51 +0000209 std::vector<Value*>(CE->op_begin()+1, CE->op_end()),
Vikram S. Adved0451a92002-10-13 00:01:57 +0000210 "constantGEP", &insertBefore);
211
212 default: // must be a binary operator
Chris Lattner0b16ae22002-10-13 19:39:16 +0000213 assert(CE->getOpcode() >= Instruction::BinaryOpsBegin &&
214 CE->getOpcode() < Instruction::BinaryOpsEnd &&
Vikram S. Adved0451a92002-10-13 00:01:57 +0000215 "Unrecognized opcode in ConstantExpr");
216 getArg1 = CE->getOperand(0);
217 if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1))
218 getArg1 = DecomposeConstantExpr(CEarg, insertBefore);
219 getArg2 = CE->getOperand(1);
220 if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg2))
221 getArg2 = DecomposeConstantExpr(CEarg, insertBefore);
222 return BinaryOperator::create((Instruction::BinaryOps) CE->getOpcode(),
223 getArg1, getArg2,
224 "constantBinaryOp", &insertBefore);
225 }
226}
227
228
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000229//------------------------------------------------------------------------------
230// Instruction visitor methods to perform instruction-specific operations
231//------------------------------------------------------------------------------
232
233// Common work for *all* instructions. This needs to be called explicitly
234// by other visit<InstructionType> functions.
235inline void
236PreSelection::visitInstruction(Instruction &I)
237{
238 visitOperands(I); // Perform operand transformations
239}
240
241
242// GetElementPtr instructions: check if pointer is a global
243void
244PreSelection::visitGetElementPtrInst(GetElementPtrInst &I)
245{
246 // Check for a global and put its address into a register before this instr
Vikram S. Adved0451a92002-10-13 00:01:57 +0000247 if (GetElementPtrInst* gep = getGlobalAddr(I.getPointerOperand(), I))
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000248 I.setOperand(I.getPointerOperandIndex(), gep); // replace pointer operand
249
250 // Decompose multidimensional array references
251 DecomposeArrayRef(&I);
252
253 // Perform other transformations common to all instructions
254 visitInstruction(I);
255}
256
257
258// Load instructions: check if pointer is a global
259void
260PreSelection::visitLoadInst(LoadInst &I)
261{
262 // Check for a global and put its address into a register before this instr
Vikram S. Adved0451a92002-10-13 00:01:57 +0000263 if (GetElementPtrInst* gep = getGlobalAddr(I.getPointerOperand(), I))
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000264 I.setOperand(I.getPointerOperandIndex(), gep); // replace pointer operand
265
266 // Perform other transformations common to all instructions
267 visitInstruction(I);
268}
269
270
271// Store instructions: check if pointer is a global
272void
273PreSelection::visitStoreInst(StoreInst &I)
274{
275 // Check for a global and put its address into a register before this instr
Vikram S. Adved0451a92002-10-13 00:01:57 +0000276 if (GetElementPtrInst* gep = getGlobalAddr(I.getPointerOperand(), I))
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000277 I.setOperand(I.getPointerOperandIndex(), gep); // replace pointer operand
278
279 // Perform other transformations common to all instructions
280 visitInstruction(I);
281}
282
283
Vikram S. Adved0451a92002-10-13 00:01:57 +0000284// Cast instructions:
285// -- check if argument is a global
286// -- make multi-step casts explicit:
287// -- float/double to uint32_t:
288// If target does not have a float-to-unsigned instruction, we
289// need to convert to uint64_t and then to uint32_t, or we may
290// overflow the signed int representation for legal uint32_t
291// values. Expand this without checking target.
Vikram S. Advee9cb7352002-09-27 14:24:45 +0000292//
293void
294PreSelection::visitCastInst(CastInst &I)
295{
296 CastInst* castI = NULL;
297
298 // Check for a global and put its address into a register before this instr
Vikram S. Adved0451a92002-10-13 00:01:57 +0000299 if (GetElementPtrInst* gep = getGlobalAddr(I.getOperand(0), I))
300 {
301 I.setOperand(0, gep); // replace pointer operand
302 }
303 else if (I.getType() == Type::UIntTy &&
304 I.getOperand(0)->getType()->isFloatingPoint())
Vikram S. Advee9cb7352002-09-27 14:24:45 +0000305 { // insert a cast-fp-to-long before I, and then replace the operand of I
306 castI = new CastInst(I.getOperand(0), Type::LongTy, "fp2Long2Uint", &I);
307 I.setOperand(0, castI); // replace fp operand with long
308 }
309
310 // Perform other transformations common to all instructions
311 visitInstruction(I);
312 if (castI)
313 visitInstruction(*castI);
314}
315
316
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000317// visitOperands() transforms individual operands of all instructions:
318// -- Load "large" int constants into a virtual register. What is large
319// depends on the type of instruction and on the target architecture.
320// -- For any constants that cannot be put in an immediate field,
321// load address into virtual register first, and then load the constant.
322//
323void
324PreSelection::visitOperands(Instruction &I)
325{
326 // For any instruction other than PHI, copies go just before the instr.
327 // For a PHI, operand copies must be before the terminator of the
328 // appropriate predecessor basic block. Remaining logic is simple
329 // so just handle PHIs and other instructions separately.
330 //
331 if (PHINode* phi = dyn_cast<PHINode>(&I))
332 {
333 for (unsigned i=0, N=phi->getNumIncomingValues(); i < N; ++i)
334 if (Constant* CV = dyn_cast<Constant>(phi->getIncomingValue(i)))
335 this->visitOneOperand(I, CV, phi->getOperandNumForIncomingValue(i),
336 * phi->getIncomingBlock(i)->getTerminator());
337 }
338 else
339 for (unsigned i=0, N=I.getNumOperands(); i < N; ++i)
340 if (Constant* CV = dyn_cast<Constant>(I.getOperand(i)))
341 this->visitOneOperand(I, CV, i, I);
342}
343
344void
345PreSelection::visitOneOperand(Instruction &I, Constant* CV, unsigned opNum,
346 Instruction& insertBefore)
347{
Vikram S. Adved0451a92002-10-13 00:01:57 +0000348 if (ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
349 { // load-time constant: factor it out so we optimize as best we can
350 Instruction* computeConst = DecomposeConstantExpr(CE, insertBefore);
351 I.setOperand(opNum, computeConst); // replace expr operand with result
352 }
353 else if (target.getInstrInfo().ConstantTypeMustBeLoaded(CV))
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000354 { // load address of constant into a register, then load the constant
355 GetElementPtrInst* gep = getGlobalAddr(getGlobalForConstant(CV),
Vikram S. Adved0451a92002-10-13 00:01:57 +0000356 insertBefore);
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000357 LoadInst* ldI = new LoadInst(gep, "loadConst", &insertBefore);
358 I.setOperand(opNum, ldI); // replace operand with copy in v.reg.
359 }
360 else if (target.getInstrInfo().ConstantMayNotFitInImmedField(CV, &I))
361 { // put the constant into a virtual register using a cast
362 CastInst* castI = new CastInst(CV, CV->getType(), "copyConst",
363 &insertBefore);
364 I.setOperand(opNum, castI); // replace operand with copy in v.reg.
365 }
366}
367
Vikram S. Adved0451a92002-10-13 00:01:57 +0000368
Vikram S. Adveabf055c2002-09-20 00:29:28 +0000369//===----------------------------------------------------------------------===//
370// createPreSelectionPass - Public entrypoint for pre-selection pass
371// and this file as a whole...
372//
373Pass*
374createPreSelectionPass(TargetMachine &T)
375{
376 return new PreSelection(T);
377}
378