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 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Transforms/Utils/Local.h"
18 #include "TransformInternals.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Pass.h"
21 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/ADT/Statistic.h"
25 #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"));
39 NumLoadStorePeepholes("raise", "Number of load/store peepholes");
42 NumGEPInstFormed("raise", "Number of other getelementptr's formed");
45 NumExprTreesConv("raise", "Number of expression trees converted");
48 NumCastOfCast("raise", "Number of cast-of-self removed");
51 NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
54 NumVarargCallChanges("raise", "Number of vararg call peepholes");
56 #define PRINT_PEEPHOLE(ID, NUM, I) \
57 DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
59 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
60 #define PRINT_PEEPHOLE2(ID, I1, I2) \
61 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
62 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
63 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
64 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
65 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
66 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
67 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
70 struct RPR
: public FunctionPass
{
71 virtual bool runOnFunction(Function
&F
);
73 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
75 AU
.addRequired
<TargetData
>();
79 bool DoRaisePass(Function
&F
);
80 bool PeepholeOptimize(BasicBlock
*BB
, BasicBlock::iterator
&BI
);
83 RegisterOpt
<RPR
> X("raise", "Raise Pointer References");
87 FunctionPass
*llvm::createRaisePointerReferencesPass() {
92 // isReinterpretingCast - Return true if the cast instruction specified will
93 // cause the operand to be "reinterpreted". A value is reinterpreted if the
94 // cast instruction would cause the underlying bits to change.
96 static inline bool isReinterpretingCast(const CastInst
*CI
) {
97 return!CI
->getOperand(0)->getType()->isLosslesslyConvertibleTo(CI
->getType());
100 bool RPR::PeepholeOptimize(BasicBlock
*BB
, BasicBlock::iterator
&BI
) {
102 const TargetData
&TD
= getAnalysis
<TargetData
>();
104 if (CastInst
*CI
= dyn_cast
<CastInst
>(I
)) {
105 Value
*Src
= CI
->getOperand(0);
106 const Type
*DestTy
= CI
->getType();
108 // Peephole optimize the following instruction:
109 // %V2 = cast <ty> %V to <ty>
113 if (DestTy
== Src
->getType()) { // Check for a cast to same type as src!!
114 PRINT_PEEPHOLE1("cast-of-self-ty", *CI
);
115 CI
->replaceAllUsesWith(Src
);
116 if (!Src
->hasName() && CI
->hasName()) {
117 std::string Name
= CI
->getName();
122 // DCE the instruction now, to avoid having the iterative version of DCE
123 // have to worry about it.
125 BI
= BB
->getInstList().erase(BI
);
131 // Check to see if it's a cast of an instruction that does not depend on the
132 // specific type of the operands to do it's job.
133 if (!isReinterpretingCast(CI
)) {
134 ValueTypeCache ConvertedTypes
;
136 // Check to see if we can convert the source of the cast to match the
137 // destination type of the cast...
139 ConvertedTypes
[CI
] = CI
->getType(); // Make sure the cast doesn't change
140 if (ExpressionConvertibleToType(Src
, DestTy
, ConvertedTypes
, TD
)) {
141 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", *Src
, *CI
, *BB
->getParent());
143 DEBUG(std::cerr
<< "\nCONVERTING SRC EXPR TYPE:\n");
144 { // ValueMap must be destroyed before function verified!
145 ValueMapCache ValueMap
;
146 Value
*E
= ConvertExpressionToType(Src
, DestTy
, ValueMap
, TD
);
148 if (Constant
*CPV
= dyn_cast
<Constant
>(E
))
149 CI
->replaceAllUsesWith(CPV
);
151 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", *E
);
152 DEBUG(std::cerr
<< "DONE CONVERTING SRC EXPR TYPE: \n"
153 << *BB
->getParent());
156 BI
= BB
->begin(); // Rescan basic block. BI might be invalidated.
161 // Check to see if we can convert the users of the cast value to match the
162 // source type of the cast...
164 ConvertedTypes
.clear();
165 // Make sure the source doesn't change type
166 ConvertedTypes
[Src
] = Src
->getType();
167 if (ValueConvertibleToType(CI
, Src
->getType(), ConvertedTypes
, TD
)) {
168 //PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", *Src, *CI,
169 // *BB->getParent());
171 DEBUG(std::cerr
<< "\nCONVERTING EXPR TYPE:\n");
172 { // ValueMap must be destroyed before function verified!
173 ValueMapCache ValueMap
;
174 ConvertValueToNewType(CI
, Src
, ValueMap
, TD
); // This will delete CI!
177 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", *Src
);
178 DEBUG(std::cerr
<< "DONE CONVERTING EXPR TYPE: \n\n" <<
181 BI
= BB
->begin(); // Rescan basic block. BI might be invalidated.
187 // Check to see if we are casting from a structure pointer to a pointer to
188 // the first element of the structure... to avoid munching other peepholes,
189 // we only let this happen if there are no add uses of the cast.
191 // Peephole optimize the following instructions:
192 // %t1 = cast {<...>} * %StructPtr to <ty> *
194 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
195 // %t1 = cast <eltype> * %t1 to <ty> *
197 if (const CompositeType
*CTy
= getPointedToComposite(Src
->getType()))
198 if (const PointerType
*DestPTy
= dyn_cast
<PointerType
>(DestTy
)) {
200 // Loop over uses of the cast, checking for add instructions. If an add
201 // exists, this is probably a part of a more complex GEP, so we don't
202 // want to mess around with the cast.
204 bool HasAddUse
= false;
205 for (Value::use_iterator I
= CI
->use_begin(), E
= CI
->use_end();
207 if (isa
<Instruction
>(*I
) &&
208 cast
<Instruction
>(*I
)->getOpcode() == Instruction::Add
) {
209 HasAddUse
= true; break;
212 // If it doesn't have an add use, check to see if the dest type is
213 // losslessly convertible to one of the types in the start of the struct
217 const Type
*DestPointedTy
= DestPTy
->getElementType();
219 const CompositeType
*CurCTy
= CTy
;
220 const Type
*ElTy
= 0;
222 // Build the index vector, full of all zeros
223 std::vector
<Value
*> Indices
;
225 Indices
.push_back(Constant::getNullValue(Type::UIntTy
));
226 while (CurCTy
&& !isa
<PointerType
>(CurCTy
)) {
227 if (const StructType
*CurSTy
= dyn_cast
<StructType
>(CurCTy
)) {
228 // Check for a zero element struct type... if we have one, bail.
229 if (CurSTy
->getNumElements() == 0) break;
231 // Grab the first element of the struct type, which must lie at
232 // offset zero in the struct.
234 ElTy
= CurSTy
->getElementType(0);
236 ElTy
= cast
<SequentialType
>(CurCTy
)->getElementType();
239 // Insert a zero to index through this type...
240 Indices
.push_back(Constant::getNullValue(Type::UIntTy
));
242 // Did we find what we're looking for?
243 if (ElTy
->isLosslesslyConvertibleTo(DestPointedTy
)) break;
245 // Nope, go a level deeper.
247 CurCTy
= dyn_cast
<CompositeType
>(ElTy
);
251 // Did we find what we were looking for? If so, do the transformation
253 PRINT_PEEPHOLE1("cast-for-first:in", *CI
);
255 std::string Name
= CI
->getName(); CI
->setName("");
257 // Insert the new T cast instruction... stealing old T's name
258 GetElementPtrInst
*GEP
= new GetElementPtrInst(Src
, Indices
,
261 // Make the old cast instruction reference the new GEP instead of
262 // the old src value.
264 CI
->setOperand(0, GEP
);
266 PRINT_PEEPHOLE2("cast-for-first:out", *GEP
, *CI
);
273 } else if (StoreInst
*SI
= dyn_cast
<StoreInst
>(I
)) {
274 Value
*Val
= SI
->getOperand(0);
275 Value
*Pointer
= SI
->getPointerOperand();
277 // Peephole optimize the following instructions:
278 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
279 // store <T2> %V, <T2>* %t
282 // %t = cast <T2> %V to <T1>
283 // store <T1> %t2, <T1>* %P
285 // Note: This is not taken care of by expr conversion because there might
286 // not be a cast available for the store to convert the incoming value of.
287 // This code is basically here to make sure that pointers don't have casts
290 if (CastInst
*CI
= dyn_cast
<CastInst
>(Pointer
))
291 if (Value
*CastSrc
= CI
->getOperand(0)) // CSPT = CastSrcPointerType
292 if (const PointerType
*CSPT
= dyn_cast
<PointerType
>(CastSrc
->getType()))
293 // convertible types?
294 if (Val
->getType()->isLosslesslyConvertibleTo(CSPT
->getElementType())) {
295 PRINT_PEEPHOLE3("st-src-cast:in ", *Pointer
, *Val
, *SI
);
297 // Insert the new T cast instruction... stealing old T's name
298 std::string
Name(CI
->getName()); CI
->setName("");
299 CastInst
*NCI
= new CastInst(Val
, CSPT
->getElementType(),
302 // Replace the old store with a new one!
303 ReplaceInstWithInst(BB
->getInstList(), BI
,
304 SI
= new StoreInst(NCI
, CastSrc
));
305 PRINT_PEEPHOLE3("st-src-cast:out", *NCI
, *CastSrc
, *SI
);
306 ++NumLoadStorePeepholes
;
310 } else if (LoadInst
*LI
= dyn_cast
<LoadInst
>(I
)) {
311 Value
*Pointer
= LI
->getOperand(0);
312 const Type
*PtrElType
=
313 cast
<PointerType
>(Pointer
->getType())->getElementType();
315 // Peephole optimize the following instructions:
316 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertible to T2
317 // %t = load <T2>* %P
320 // %t = load <T1>* %P
321 // %Val = cast <T1> to <T2>
323 // Note: This is not taken care of by expr conversion because there might
324 // not be a cast available for the store to convert the incoming value of.
325 // This code is basically here to make sure that pointers don't have casts
328 if (CastInst
*CI
= dyn_cast
<CastInst
>(Pointer
))
329 if (Value
*CastSrc
= CI
->getOperand(0)) // CSPT = CastSrcPointerType
330 if (const PointerType
*CSPT
= dyn_cast
<PointerType
>(CastSrc
->getType()))
331 // convertible types?
332 if (PtrElType
->isLosslesslyConvertibleTo(CSPT
->getElementType())) {
333 PRINT_PEEPHOLE2("load-src-cast:in ", *Pointer
, *LI
);
335 // Create the new load instruction... loading the pre-casted value
336 LoadInst
*NewLI
= new LoadInst(CastSrc
, LI
->getName(), BI
);
338 // Insert the new T cast instruction... stealing old T's name
339 CastInst
*NCI
= new CastInst(NewLI
, LI
->getType(), CI
->getName());
341 // Replace the old store with a new one!
342 ReplaceInstWithInst(BB
->getInstList(), BI
, NCI
);
343 PRINT_PEEPHOLE3("load-src-cast:out", *NCI
, *CastSrc
, *NewLI
);
344 ++NumLoadStorePeepholes
;
348 } else if (CallInst
*CI
= dyn_cast
<CallInst
>(I
)) {
349 // If we have a call with all varargs arguments, convert the call to use the
350 // actual argument types present...
352 const PointerType
*PTy
= cast
<PointerType
>(CI
->getCalledValue()->getType());
353 const FunctionType
*FTy
= cast
<FunctionType
>(PTy
->getElementType());
355 // Is the call to a vararg variable with no real parameters?
356 if (FTy
->isVarArg() && FTy
->getNumParams() == 0 &&
357 !CI
->getCalledFunction()) {
358 // If so, insert a new cast instruction, casting it to a function type
359 // that matches the current arguments...
361 std::vector
<const Type
*> Params
; // Parameter types...
362 for (unsigned i
= 1, e
= CI
->getNumOperands(); i
!= e
; ++i
)
363 Params
.push_back(CI
->getOperand(i
)->getType());
365 FunctionType
*NewFT
= FunctionType::get(FTy
->getReturnType(),
367 PointerType
*NewPFunTy
= PointerType::get(NewFT
);
369 // Create a new cast, inserting it right before the function call...
371 Constant
*ConstantCallSrc
= 0;
372 if (Constant
*CS
= dyn_cast
<Constant
>(CI
->getCalledValue()))
373 ConstantCallSrc
= CS
;
376 NewCast
= ConstantExpr::getCast(ConstantCallSrc
, NewPFunTy
);
378 NewCast
= new CastInst(CI
->getCalledValue(), NewPFunTy
,
379 CI
->getCalledValue()->getName()+"_c",CI
);
381 // Create a new call instruction...
382 CallInst
*NewCall
= new CallInst(NewCast
,
383 std::vector
<Value
*>(CI
->op_begin()+1, CI
->op_end()));
384 if (CI
->isTailCall()) NewCall
->setTailCall();
385 NewCall
->setCallingConv(CI
->getCallingConv());
387 ReplaceInstWithInst(CI
, NewCall
);
389 ++NumVarargCallChanges
;
401 bool RPR::DoRaisePass(Function
&F
) {
402 bool Changed
= false;
403 for (Function::iterator BB
= F
.begin(), BBE
= F
.end(); BB
!= BBE
; ++BB
)
404 for (BasicBlock::iterator BI
= BB
->begin(); BI
!= BB
->end();) {
405 DEBUG(std::cerr
<< "LevelRaising: " << *BI
);
406 if (dceInstruction(BI
) || doConstantPropagation(BI
)) {
409 DEBUG(std::cerr
<< "***\t\t^^-- Dead code eliminated!\n");
410 } else if (PeepholeOptimize(BB
, BI
)) {
421 // runOnFunction - Raise a function representation to a higher level.
422 bool RPR::runOnFunction(Function
&F
) {
423 DEBUG(std::cerr
<< "\n\n\nStarting to work on Function '" << F
.getName()
426 // Insert casts for all incoming pointer pointer values that are treated as
429 bool Changed
= false, LocalChange
;
431 // If the StartInst option was specified, then Peephole optimize that
432 // instruction first if it occurs in this function.
434 if (!StartInst
.empty()) {
435 for (Function::iterator BB
= F
.begin(), BBE
= F
.end(); BB
!= BBE
; ++BB
)
436 for (BasicBlock::iterator BI
= BB
->begin(); BI
!= BB
->end(); ++BI
)
437 if (BI
->getName() == StartInst
) {
438 bool SavedDebug
= DebugFlag
; // Save the DEBUG() controlling flag.
439 DebugFlag
= true; // Turn on DEBUG's
440 Changed
|= PeepholeOptimize(BB
, BI
);
441 DebugFlag
= SavedDebug
; // Restore DebugFlag to previous state
446 DEBUG(std::cerr
<< "Looping: \n" << F
);
448 // Iterate over the function, refining it, until it converges on a stable
451 while (DoRaisePass(F
)) LocalChange
= true;
452 Changed
|= LocalChange
;
454 } while (LocalChange
);