1 //===- LevelRaise.cpp - Code to change LLVM to higher level ---------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the 'raising' part of the LevelChange API. This is
11 // useful because, in general, it makes the LLVM code terser and easier to
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "raise"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Transforms/Utils/Local.h"
19 #include "TransformInternals.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/STLExtras.h"
30 // StartInst - This enables the -raise-start-inst=foo option to cause the level
31 // raising pass to start at instruction "foo", which is immensely useful for
34 static cl::opt<std::string>
35 StartInst("raise-start-inst", cl::Hidden, cl::value_desc("inst name"),
36 cl::desc("Start raise pass at the instruction with the specified name"));
38 STATISTIC(NumLoadStorePeepholes, "Number of load/store peepholes");
40 STATISTIC(NumGEPInstFormed, "Number of other getelementptr's formed");
42 STATISTIC(NumExprTreesConv, "Number of expression trees converted");
44 STATISTIC(NumCastOfCast, "Number of cast-of-self removed");
46 STATISTIC(NumDCEorCP, "Number of insts DCEd or constprop'd");
48 STATISTIC(NumVarargCallChanges, "Number of vararg call peepholes");
50 #define PRINT_PEEPHOLE(ID, NUM, I) \
51 DOUT << "Inst P/H " << ID << "[" << NUM << "] " << I
53 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
54 #define PRINT_PEEPHOLE2(ID, I1, I2) \
55 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
56 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
57 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
58 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
59 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
60 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
61 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
64 struct RPR : public FunctionPass {
65 virtual bool runOnFunction(Function &F);
67 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 AU.addRequired<TargetData>();
73 bool DoRaisePass(Function &F);
74 bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI);
77 RegisterPass<RPR> X("raise", "Raise Pointer References");
81 FunctionPass *llvm::createRaisePointerReferencesPass() {
85 bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
87 const TargetData &TD = getAnalysis<TargetData>();
89 if (CastInst *CI = dyn_cast<CastInst>(I)) {
90 Value *Src = CI->getOperand(0);
91 const Type *DestTy = CI->getType();
93 // Peephole optimize the following instruction:
94 // %V2 = cast <ty> %V to <ty>
98 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
99 PRINT_PEEPHOLE1("cast-of-self-ty", *CI);
100 CI->replaceAllUsesWith(Src);
101 if (!Src->hasName() && CI->hasName()) {
102 std::string Name = CI->getName();
107 // DCE the instruction now, to avoid having the iterative version of DCE
108 // have to worry about it.
110 BI = BB->getInstList().erase(BI);
116 // Check to see if it's a cast of an instruction that does not depend on the
117 // specific type of the operands to do it's job.
118 if (CI->isLosslessCast()) {
119 ValueTypeCache ConvertedTypes;
121 // Check to see if we can convert the source of the cast to match the
122 // destination type of the cast...
124 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
125 if (ExpressionConvertibleToType(Src, DestTy, ConvertedTypes, TD)) {
126 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", *Src, *CI, *BB->getParent());
128 DOUT << "\nCONVERTING SRC EXPR TYPE:\n";
129 { // ValueMap must be destroyed before function verified!
130 ValueMapCache ValueMap;
131 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
133 if (Constant *CPV = dyn_cast<Constant>(E))
134 CI->replaceAllUsesWith(CPV);
136 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", *E);
137 DOUT << "DONE CONVERTING SRC EXPR TYPE: \n"
141 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
146 // Check to see if we can convert the users of the cast value to match the
147 // source type of the cast...
149 ConvertedTypes.clear();
150 // Make sure the source doesn't change type
151 ConvertedTypes[Src] = Src->getType();
152 if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
153 //PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", *Src, *CI,
154 // *BB->getParent());
156 DOUT << "\nCONVERTING EXPR TYPE:\n";
157 { // ValueMap must be destroyed before function verified!
158 ValueMapCache ValueMap;
159 ConvertValueToNewType(CI, Src, ValueMap, TD); // This will delete CI!
162 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", *Src);
163 DOUT << "DONE CONVERTING EXPR TYPE: \n\n" << *BB->getParent();
165 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
171 // Check to see if we are casting from a structure pointer to a pointer to
172 // the first element of the structure... to avoid munching other peepholes,
173 // we only let this happen if there are no add uses of the cast.
175 // Peephole optimize the following instructions:
176 // %t1 = cast {<...>} * %StructPtr to <ty> *
178 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
179 // %t1 = cast <eltype> * %t1 to <ty> *
181 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
182 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
184 // Loop over uses of the cast, checking for add instructions. If an add
185 // exists, this is probably a part of a more complex GEP, so we don't
186 // want to mess around with the cast.
188 bool HasAddUse = false;
189 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
191 if (isa<Instruction>(*I) &&
192 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
193 HasAddUse = true; break;
196 // If it doesn't have an add use, check to see if the dest type is
197 // losslessly convertible to one of the types in the start of the struct
201 const Type *DestPointedTy = DestPTy->getElementType();
203 const CompositeType *CurCTy = CTy;
204 const Type *ElTy = 0;
206 // Build the index vector, full of all zeros
207 std::vector<Value*> Indices;
209 Indices.push_back(Constant::getNullValue(Type::Int32Ty));
210 while (CurCTy && !isa<PointerType>(CurCTy)) {
211 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
212 // Check for a zero element struct type... if we have one, bail.
213 if (CurSTy->getNumElements() == 0) break;
215 // Grab the first element of the struct type, which must lie at
216 // offset zero in the struct.
218 ElTy = CurSTy->getElementType(0);
220 ElTy = cast<SequentialType>(CurCTy)->getElementType();
223 // Insert a zero to index through this type...
224 Indices.push_back(Constant::getNullValue(Type::Int32Ty));
226 // Did we find what we're looking for?
227 if (ElTy->canLosslesslyBitCastTo(DestPointedTy)) break;
229 // Nope, go a level deeper.
231 CurCTy = dyn_cast<CompositeType>(ElTy);
235 // Did we find what we were looking for? If so, do the transformation
237 PRINT_PEEPHOLE1("cast-for-first:in", *CI);
239 std::string Name = CI->getName(); CI->setName("");
241 // Insert the new T cast instruction... stealing old T's name
242 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
245 // Make the old cast instruction reference the new GEP instead of
246 // the old src value.
247 if (CI->getOperand(0)->getType() == GEP->getType()) {
248 // If the source types are the same we can safely replace the
249 // first operand of the CastInst because the opcode won't
250 // change as a result.
251 CI->setOperand(0, GEP);
253 // The existing and new operand 0 types are different so we must
254 // replace CI with a new CastInst so that we are assured to
255 // get the correct cast opcode.
256 CastInst *NewCI = new BitCastInst(GEP, CI->getType(),
258 CI->replaceAllUsesWith(NewCI);
259 CI->eraseFromParent();
261 BI = NewCI; // Don't let the iterator invalidate
264 PRINT_PEEPHOLE2("cast-for-first:out", *GEP, *CI);
271 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
272 Value *Val = SI->getOperand(0);
273 Value *Pointer = SI->getPointerOperand();
275 // Peephole optimize the following instructions:
276 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly castable to T2
277 // store <T2> %V, <T2>* %t
280 // %t = cast <T2> %V to <T1>
281 // store <T1> %t2, <T1>* %P
283 // Note: This is not taken care of by expr conversion because there might
284 // not be a cast available for the store to convert the incoming value of.
285 // This code is basically here to make sure that pointers don't have casts
288 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
289 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
290 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
291 // convertible types?
292 if (Val->getType()->canLosslesslyBitCastTo(CSPT->getElementType()))
294 PRINT_PEEPHOLE3("st-src-cast:in ", *Pointer, *Val, *SI);
296 // Insert the new T cast instruction... stealing old T's name
297 std::string Name(CI->getName()); CI->setName("");
298 CastInst *NCI = CastInst::create(Instruction::BitCast, Val,
299 CSPT->getElementType(), Name, BI);
301 // Replace the old store with a new one!
302 ReplaceInstWithInst(BB->getInstList(), BI,
303 SI = new StoreInst(NCI, CastSrc));
304 PRINT_PEEPHOLE3("st-src-cast:out", *NCI, *CastSrc, *SI);
305 ++NumLoadStorePeepholes;
309 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
310 Value *Pointer = LI->getOperand(0);
311 const Type *PtrElType =
312 cast<PointerType>(Pointer->getType())->getElementType();
314 // Peephole optimize the following instructions:
315 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertible to T2
316 // %t = load <T2>* %P
319 // %t = load <T1>* %P
320 // %Val = cast <T1> to <T2>
322 // Note: This is not taken care of by expr conversion because there might
323 // not be a cast available for the store to convert the incoming value of.
324 // This code is basically here to make sure that pointers don't have casts
327 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
328 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
329 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
330 // convertible types?
331 if (PtrElType->canLosslesslyBitCastTo(CSPT->getElementType())) {
332 PRINT_PEEPHOLE2("load-src-cast:in ", *Pointer, *LI);
334 // Create the new load instruction... loading the pre-casted value
335 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
337 // Insert the new T cast instruction... stealing old T's name
339 CastInst::create(Instruction::BitCast, NewLI, LI->getType(),
342 // Replace the old store with a new one!
343 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
344 PRINT_PEEPHOLE3("load-src-cast:out", *NCI, *CastSrc, *NewLI);
345 ++NumLoadStorePeepholes;
349 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
350 // If we have a call with all varargs arguments, convert the call to use the
351 // actual argument types present...
353 const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
354 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
356 // Is the call to a vararg variable with no real parameters?
357 if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
358 !CI->getCalledFunction()) {
359 // If so, insert a new cast instruction, casting it to a function type
360 // that matches the current arguments...
362 std::vector<const Type *> Params; // Parameter types...
363 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
364 Params.push_back(CI->getOperand(i)->getType());
366 FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
368 PointerType *NewPFunTy = PointerType::get(NewFT);
370 // Create a new cast, inserting it right before the function call...
372 if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
373 NewCast = ConstantExpr::getBitCast(CS, NewPFunTy);
375 NewCast = CastInst::create(Instruction::BitCast, CI->getCalledValue(),
377 CI->getCalledValue()->getName()+"_c", CI);
379 // Create a new call instruction...
380 CallInst *NewCall = new CallInst(NewCast,
381 std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
382 if (CI->isTailCall()) NewCall->setTailCall();
383 NewCall->setCallingConv(CI->getCallingConv());
385 ReplaceInstWithInst(CI, NewCall);
387 ++NumVarargCallChanges;
396 bool RPR::DoRaisePass(Function &F) {
397 bool Changed = false;
398 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
399 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
400 DOUT << "LevelRaising: " << *BI;
401 if (dceInstruction(BI) || doConstantPropagation(BI)) {
404 DOUT << "***\t\t^^-- Dead code eliminated!\n";
405 } else if (PeepholeOptimize(BB, BI)) {
416 // runOnFunction - Raise a function representation to a higher level.
417 bool RPR::runOnFunction(Function &F) {
418 DOUT << "\n\n\nStarting to work on Function '" << F.getName() << "'\n";
420 // Insert casts for all incoming pointer pointer values that are treated as
423 bool Changed = false, LocalChange;
425 // If the StartInst option was specified, then Peephole optimize that
426 // instruction first if it occurs in this function.
428 if (!StartInst.empty()) {
429 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
430 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
431 if (BI->getName() == StartInst) {
432 bool SavedDebug = DebugFlag; // Save the DEBUG() controlling flag.
433 DebugFlag = true; // Turn on DEBUG's
434 Changed |= PeepholeOptimize(BB, BI);
435 DebugFlag = SavedDebug; // Restore DebugFlag to previous state
440 DOUT << "Looping: \n" << F;
442 // Iterate over the function, refining it, until it converges on a stable
445 while (DoRaisePass(F)) LocalChange = true;
446 Changed |= LocalChange;
448 } while (LocalChange);