1 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass transforms simple global variables that never have their address
11 // taken. If obviously true, it marks read/write globals as constant, deletes
12 // variables only stored to, etc.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "globalopt"
17 #include "llvm/Transforms/IPO.h"
18 #include "llvm/CallingConv.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/IntrinsicInst.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Support/CallSite.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/STLExtras.h"
42 STATISTIC(NumMarked , "Number of globals marked constant");
43 STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
44 STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
45 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
46 STATISTIC(NumDeleted , "Number of globals deleted");
47 STATISTIC(NumFnDeleted , "Number of functions deleted");
48 STATISTIC(NumGlobUses , "Number of global uses devirtualized");
49 STATISTIC(NumLocalized , "Number of globals localized");
50 STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
51 STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
52 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
53 STATISTIC(NumNestRemoved , "Number of nest attributes removed");
54 STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
55 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
58 struct GlobalOpt : public ModulePass {
59 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61 static char ID; // Pass identification, replacement for typeid
62 GlobalOpt() : ModulePass(ID) {
63 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
66 bool runOnModule(Module &M);
69 GlobalVariable *FindGlobalCtors(Module &M);
70 bool OptimizeFunctions(Module &M);
71 bool OptimizeGlobalVars(Module &M);
72 bool OptimizeGlobalAliases(Module &M);
73 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
74 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
78 char GlobalOpt::ID = 0;
79 INITIALIZE_PASS(GlobalOpt, "globalopt",
80 "Global Variable Optimizer", false, false)
82 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
86 /// GlobalStatus - As we analyze each global, keep track of some information
87 /// about it. If we find out that the address of the global is taken, none of
88 /// this info will be accurate.
90 /// isLoaded - True if the global is ever loaded. If the global isn't ever
91 /// loaded it can be deleted.
94 /// StoredType - Keep track of what stores to the global look like.
97 /// NotStored - There is no store to this global. It can thus be marked
101 /// isInitializerStored - This global is stored to, but the only thing
102 /// stored is the constant it was initialized with. This is only tracked
103 /// for scalar globals.
106 /// isStoredOnce - This global is stored to, but only its initializer and
107 /// one other value is ever stored to it. If this global isStoredOnce, we
108 /// track the value stored to it in StoredOnceValue below. This is only
109 /// tracked for scalar globals.
112 /// isStored - This global is stored to by multiple values or something else
113 /// that we cannot track.
117 /// StoredOnceValue - If only one value (besides the initializer constant) is
118 /// ever stored to this global, keep track of what value it is.
119 Value *StoredOnceValue;
121 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
122 /// null/false. When the first accessing function is noticed, it is recorded.
123 /// When a second different accessing function is noticed,
124 /// HasMultipleAccessingFunctions is set to true.
125 const Function *AccessingFunction;
126 bool HasMultipleAccessingFunctions;
128 /// HasNonInstructionUser - Set to true if this global has a user that is not
129 /// an instruction (e.g. a constant expr or GV initializer).
130 bool HasNonInstructionUser;
132 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
135 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
136 AccessingFunction(0), HasMultipleAccessingFunctions(false),
137 HasNonInstructionUser(false), HasPHIUser(false) {}
142 // SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
143 // by constants itself. Note that constants cannot be cyclic, so this test is
144 // pretty easy to implement recursively.
146 static bool SafeToDestroyConstant(const Constant *C) {
147 if (isa<GlobalValue>(C)) return false;
149 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
151 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
152 if (!SafeToDestroyConstant(CU)) return false;
159 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
160 /// structure. If the global has its address taken, return true to indicate we
161 /// can't do anything with it.
163 static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
164 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
165 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
168 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
169 GS.HasNonInstructionUser = true;
171 // If the result of the constantexpr isn't pointer type, then we won't
172 // know to expect it in various places. Just reject early.
173 if (!isa<PointerType>(CE->getType())) return true;
175 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
176 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
177 if (!GS.HasMultipleAccessingFunctions) {
178 const Function *F = I->getParent()->getParent();
179 if (GS.AccessingFunction == 0)
180 GS.AccessingFunction = F;
181 else if (GS.AccessingFunction != F)
182 GS.HasMultipleAccessingFunctions = true;
184 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
186 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
187 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
188 // Don't allow a store OF the address, only stores TO the address.
189 if (SI->getOperand(0) == V) return true;
191 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
193 // If this is a direct store to the global (i.e., the global is a scalar
194 // value, not an aggregate), keep more specific information about
196 if (GS.StoredType != GlobalStatus::isStored) {
197 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
198 SI->getOperand(1))) {
199 Value *StoredVal = SI->getOperand(0);
200 if (StoredVal == GV->getInitializer()) {
201 if (GS.StoredType < GlobalStatus::isInitializerStored)
202 GS.StoredType = GlobalStatus::isInitializerStored;
203 } else if (isa<LoadInst>(StoredVal) &&
204 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
205 if (GS.StoredType < GlobalStatus::isInitializerStored)
206 GS.StoredType = GlobalStatus::isInitializerStored;
207 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
208 GS.StoredType = GlobalStatus::isStoredOnce;
209 GS.StoredOnceValue = StoredVal;
210 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
211 GS.StoredOnceValue == StoredVal) {
214 GS.StoredType = GlobalStatus::isStored;
217 GS.StoredType = GlobalStatus::isStored;
220 } else if (isa<GetElementPtrInst>(I)) {
221 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
222 } else if (isa<SelectInst>(I)) {
223 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
224 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
225 // PHI nodes we can check just like select or GEP instructions, but we
226 // have to be careful about infinite recursion.
227 if (PHIUsers.insert(PN)) // Not already visited.
228 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
229 GS.HasPHIUser = true;
230 } else if (isa<CmpInst>(I)) {
231 // Nothing to analyse.
232 } else if (isa<MemTransferInst>(I)) {
233 const MemTransferInst *MTI = cast<MemTransferInst>(I);
234 if (MTI->getArgOperand(0) == V)
235 GS.StoredType = GlobalStatus::isStored;
236 if (MTI->getArgOperand(1) == V)
238 } else if (isa<MemSetInst>(I)) {
239 assert(cast<MemSetInst>(I)->getArgOperand(0) == V &&
240 "Memset only takes one pointer!");
241 GS.StoredType = GlobalStatus::isStored;
243 return true; // Any other non-load instruction might take address!
245 } else if (const Constant *C = dyn_cast<Constant>(U)) {
246 GS.HasNonInstructionUser = true;
247 // We might have a dead and dangling constant hanging off of here.
248 if (!SafeToDestroyConstant(C))
251 GS.HasNonInstructionUser = true;
252 // Otherwise must be some other user.
260 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
261 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
263 unsigned IdxV = CI->getZExtValue();
265 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
266 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
267 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
268 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
269 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
270 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
271 } else if (isa<ConstantAggregateZero>(Agg)) {
272 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
273 if (IdxV < STy->getNumElements())
274 return Constant::getNullValue(STy->getElementType(IdxV));
275 } else if (const SequentialType *STy =
276 dyn_cast<SequentialType>(Agg->getType())) {
277 return Constant::getNullValue(STy->getElementType());
279 } else if (isa<UndefValue>(Agg)) {
280 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
281 if (IdxV < STy->getNumElements())
282 return UndefValue::get(STy->getElementType(IdxV));
283 } else if (const SequentialType *STy =
284 dyn_cast<SequentialType>(Agg->getType())) {
285 return UndefValue::get(STy->getElementType());
292 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
293 /// users of the global, cleaning up the obvious ones. This is largely just a
294 /// quick scan over the use list to clean up the easy and obvious cruft. This
295 /// returns true if it made a change.
296 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
297 bool Changed = false;
298 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
301 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
303 // Replace the load with the initializer.
304 LI->replaceAllUsesWith(Init);
305 LI->eraseFromParent();
308 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
309 // Store must be unreachable or storing Init into the global.
310 SI->eraseFromParent();
312 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
313 if (CE->getOpcode() == Instruction::GetElementPtr) {
314 Constant *SubInit = 0;
316 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
317 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
318 } else if (CE->getOpcode() == Instruction::BitCast &&
319 CE->getType()->isPointerTy()) {
320 // Pointer cast, delete any stores and memsets to the global.
321 Changed |= CleanupConstantGlobalUsers(CE, 0);
324 if (CE->use_empty()) {
325 CE->destroyConstant();
328 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
329 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
330 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
331 // and will invalidate our notion of what Init is.
332 Constant *SubInit = 0;
333 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
335 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
336 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
337 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
339 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
341 if (GEP->use_empty()) {
342 GEP->eraseFromParent();
345 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
346 if (MI->getRawDest() == V) {
347 MI->eraseFromParent();
351 } else if (Constant *C = dyn_cast<Constant>(U)) {
352 // If we have a chain of dead constantexprs or other things dangling from
353 // us, and if they are all dead, nuke them without remorse.
354 if (SafeToDestroyConstant(C)) {
355 C->destroyConstant();
356 // This could have invalidated UI, start over from scratch.
357 CleanupConstantGlobalUsers(V, Init);
365 /// isSafeSROAElementUse - Return true if the specified instruction is a safe
366 /// user of a derived expression from a global that we want to SROA.
367 static bool isSafeSROAElementUse(Value *V) {
368 // We might have a dead and dangling constant hanging off of here.
369 if (Constant *C = dyn_cast<Constant>(V))
370 return SafeToDestroyConstant(C);
372 Instruction *I = dyn_cast<Instruction>(V);
373 if (!I) return false;
376 if (isa<LoadInst>(I)) return true;
378 // Stores *to* the pointer are ok.
379 if (StoreInst *SI = dyn_cast<StoreInst>(I))
380 return SI->getOperand(0) != V;
382 // Otherwise, it must be a GEP.
383 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
384 if (GEPI == 0) return false;
386 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
387 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
390 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
392 if (!isSafeSROAElementUse(*I))
398 /// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
399 /// Look at it and its uses and decide whether it is safe to SROA this global.
401 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
402 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
403 if (!isa<GetElementPtrInst>(U) &&
404 (!isa<ConstantExpr>(U) ||
405 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
408 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
409 // don't like < 3 operand CE's, and we don't like non-constant integer
410 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
412 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
413 !cast<Constant>(U->getOperand(1))->isNullValue() ||
414 !isa<ConstantInt>(U->getOperand(2)))
417 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
418 ++GEPI; // Skip over the pointer index.
420 // If this is a use of an array allocation, do a bit more checking for sanity.
421 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
422 uint64_t NumElements = AT->getNumElements();
423 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
425 // Check to make sure that index falls within the array. If not,
426 // something funny is going on, so we won't do the optimization.
428 if (Idx->getZExtValue() >= NumElements)
431 // We cannot scalar repl this level of the array unless any array
432 // sub-indices are in-range constants. In particular, consider:
433 // A[0][i]. We cannot know that the user isn't doing invalid things like
434 // allowing i to index an out-of-range subscript that accesses A[1].
436 // Scalar replacing *just* the outer index of the array is probably not
437 // going to be a win anyway, so just give up.
438 for (++GEPI; // Skip array index.
441 uint64_t NumElements;
442 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
443 NumElements = SubArrayTy->getNumElements();
444 else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
445 NumElements = SubVectorTy->getNumElements();
447 assert((*GEPI)->isStructTy() &&
448 "Indexed GEP type is not array, vector, or struct!");
452 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
453 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
458 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
459 if (!isSafeSROAElementUse(*I))
464 /// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
465 /// is safe for us to perform this transformation.
467 static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
468 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
470 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
477 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
478 /// variable. This opens the door for other optimizations by exposing the
479 /// behavior of the program in a more fine-grained way. We have determined that
480 /// this transformation is safe already. We return the first global variable we
481 /// insert so that the caller can reprocess it.
482 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
483 // Make sure this global only has simple uses that we can SRA.
484 if (!GlobalUsersSafeToSRA(GV))
487 assert(GV->hasLocalLinkage() && !GV->isConstant());
488 Constant *Init = GV->getInitializer();
489 const Type *Ty = Init->getType();
491 std::vector<GlobalVariable*> NewGlobals;
492 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
494 // Get the alignment of the global, either explicit or target-specific.
495 unsigned StartAlignment = GV->getAlignment();
496 if (StartAlignment == 0)
497 StartAlignment = TD.getABITypeAlignment(GV->getType());
499 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
500 NewGlobals.reserve(STy->getNumElements());
501 const StructLayout &Layout = *TD.getStructLayout(STy);
502 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
503 Constant *In = getAggregateConstantElement(Init,
504 ConstantInt::get(Type::getInt32Ty(STy->getContext()), i));
505 assert(In && "Couldn't get element of initializer?");
506 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
507 GlobalVariable::InternalLinkage,
508 In, GV->getName()+"."+Twine(i),
510 GV->getType()->getAddressSpace());
511 Globals.insert(GV, NGV);
512 NewGlobals.push_back(NGV);
514 // Calculate the known alignment of the field. If the original aggregate
515 // had 256 byte alignment for example, something might depend on that:
516 // propagate info to each field.
517 uint64_t FieldOffset = Layout.getElementOffset(i);
518 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
519 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
520 NGV->setAlignment(NewAlign);
522 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
523 unsigned NumElements = 0;
524 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
525 NumElements = ATy->getNumElements();
527 NumElements = cast<VectorType>(STy)->getNumElements();
529 if (NumElements > 16 && GV->hasNUsesOrMore(16))
530 return 0; // It's not worth it.
531 NewGlobals.reserve(NumElements);
533 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
534 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
535 for (unsigned i = 0, e = NumElements; i != e; ++i) {
536 Constant *In = getAggregateConstantElement(Init,
537 ConstantInt::get(Type::getInt32Ty(Init->getContext()), i));
538 assert(In && "Couldn't get element of initializer?");
540 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
541 GlobalVariable::InternalLinkage,
542 In, GV->getName()+"."+Twine(i),
544 GV->getType()->getAddressSpace());
545 Globals.insert(GV, NGV);
546 NewGlobals.push_back(NGV);
548 // Calculate the known alignment of the field. If the original aggregate
549 // had 256 byte alignment for example, something might depend on that:
550 // propagate info to each field.
551 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
552 if (NewAlign > EltAlign)
553 NGV->setAlignment(NewAlign);
557 if (NewGlobals.empty())
560 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
562 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
564 // Loop over all of the uses of the global, replacing the constantexpr geps,
565 // with smaller constantexpr geps or direct references.
566 while (!GV->use_empty()) {
567 User *GEP = GV->use_back();
568 assert(((isa<ConstantExpr>(GEP) &&
569 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
570 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
572 // Ignore the 1th operand, which has to be zero or else the program is quite
573 // broken (undefined). Get the 2nd operand, which is the structure or array
575 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
576 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
578 Value *NewPtr = NewGlobals[Val];
580 // Form a shorter GEP if needed.
581 if (GEP->getNumOperands() > 3) {
582 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
583 SmallVector<Constant*, 8> Idxs;
584 Idxs.push_back(NullInt);
585 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
586 Idxs.push_back(CE->getOperand(i));
587 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
588 &Idxs[0], Idxs.size());
590 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
591 SmallVector<Value*, 8> Idxs;
592 Idxs.push_back(NullInt);
593 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
594 Idxs.push_back(GEPI->getOperand(i));
595 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
596 GEPI->getName()+"."+Twine(Val),GEPI);
599 GEP->replaceAllUsesWith(NewPtr);
601 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
602 GEPI->eraseFromParent();
604 cast<ConstantExpr>(GEP)->destroyConstant();
607 // Delete the old global, now that it is dead.
611 // Loop over the new globals array deleting any globals that are obviously
612 // dead. This can arise due to scalarization of a structure or an array that
613 // has elements that are dead.
614 unsigned FirstGlobal = 0;
615 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
616 if (NewGlobals[i]->use_empty()) {
617 Globals.erase(NewGlobals[i]);
618 if (FirstGlobal == i) ++FirstGlobal;
621 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
624 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
625 /// value will trap if the value is dynamically null. PHIs keeps track of any
626 /// phi nodes we've seen to avoid reprocessing them.
627 static bool AllUsesOfValueWillTrapIfNull(const Value *V,
628 SmallPtrSet<const PHINode*, 8> &PHIs) {
629 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
633 if (isa<LoadInst>(U)) {
635 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
636 if (SI->getOperand(0) == V) {
637 //cerr << "NONTRAPPING USE: " << *U;
638 return false; // Storing the value.
640 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
641 if (CI->getCalledValue() != V) {
642 //cerr << "NONTRAPPING USE: " << *U;
643 return false; // Not calling the ptr
645 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
646 if (II->getCalledValue() != V) {
647 //cerr << "NONTRAPPING USE: " << *U;
648 return false; // Not calling the ptr
650 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
651 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
652 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
653 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
654 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
655 // If we've already seen this phi node, ignore it, it has already been
657 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
659 } else if (isa<ICmpInst>(U) &&
660 isa<ConstantPointerNull>(UI->getOperand(1))) {
661 // Ignore icmp X, null
663 //cerr << "NONTRAPPING USE: " << *U;
670 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
671 /// from GV will trap if the loaded value is null. Note that this also permits
672 /// comparisons of the loaded value against null, as a special case.
673 static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
674 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
678 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
679 SmallPtrSet<const PHINode*, 8> PHIs;
680 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
682 } else if (isa<StoreInst>(U)) {
683 // Ignore stores to the global.
685 // We don't know or understand this user, bail out.
686 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
693 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
694 bool Changed = false;
695 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
696 Instruction *I = cast<Instruction>(*UI++);
697 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
698 LI->setOperand(0, NewV);
700 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
701 if (SI->getOperand(1) == V) {
702 SI->setOperand(1, NewV);
705 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
707 if (CS.getCalledValue() == V) {
708 // Calling through the pointer! Turn into a direct call, but be careful
709 // that the pointer is not also being passed as an argument.
710 CS.setCalledFunction(NewV);
712 bool PassedAsArg = false;
713 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
714 if (CS.getArgument(i) == V) {
716 CS.setArgument(i, NewV);
720 // Being passed as an argument also. Be careful to not invalidate UI!
724 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
725 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
726 ConstantExpr::getCast(CI->getOpcode(),
727 NewV, CI->getType()));
728 if (CI->use_empty()) {
730 CI->eraseFromParent();
732 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
733 // Should handle GEP here.
734 SmallVector<Constant*, 8> Idxs;
735 Idxs.reserve(GEPI->getNumOperands()-1);
736 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
738 if (Constant *C = dyn_cast<Constant>(*i))
742 if (Idxs.size() == GEPI->getNumOperands()-1)
743 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
744 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
746 if (GEPI->use_empty()) {
748 GEPI->eraseFromParent();
757 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
758 /// value stored into it. If there are uses of the loaded value that would trap
759 /// if the loaded value is dynamically null, then we know that they cannot be
760 /// reachable with a null optimize away the load.
761 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
762 bool Changed = false;
764 // Keep track of whether we are able to remove all the uses of the global
765 // other than the store that defines it.
766 bool AllNonStoreUsesGone = true;
768 // Replace all uses of loads with uses of uses of the stored value.
769 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
770 User *GlobalUser = *GUI++;
771 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
772 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
773 // If we were able to delete all uses of the loads
774 if (LI->use_empty()) {
775 LI->eraseFromParent();
778 AllNonStoreUsesGone = false;
780 } else if (isa<StoreInst>(GlobalUser)) {
781 // Ignore the store that stores "LV" to the global.
782 assert(GlobalUser->getOperand(1) == GV &&
783 "Must be storing *to* the global");
785 AllNonStoreUsesGone = false;
787 // If we get here we could have other crazy uses that are transitively
789 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
790 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
795 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
799 // If we nuked all of the loads, then none of the stores are needed either,
800 // nor is the global.
801 if (AllNonStoreUsesGone) {
802 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
803 CleanupConstantGlobalUsers(GV, 0);
804 if (GV->use_empty()) {
805 GV->eraseFromParent();
813 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
814 /// instructions that are foldable.
815 static void ConstantPropUsersOf(Value *V) {
816 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
817 if (Instruction *I = dyn_cast<Instruction>(*UI++))
818 if (Constant *NewC = ConstantFoldInstruction(I)) {
819 I->replaceAllUsesWith(NewC);
821 // Advance UI to the next non-I use to avoid invalidating it!
822 // Instructions could multiply use V.
823 while (UI != E && *UI == I)
825 I->eraseFromParent();
829 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
830 /// variable, and transforms the program as if it always contained the result of
831 /// the specified malloc. Because it is always the result of the specified
832 /// malloc, there is no reason to actually DO the malloc. Instead, turn the
833 /// malloc into a global, and any loads of GV as uses of the new global.
834 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
837 ConstantInt *NElements,
839 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
841 const Type *GlobalType;
842 if (NElements->getZExtValue() == 1)
843 GlobalType = AllocTy;
845 // If we have an array allocation, the global variable is of an array.
846 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
848 // Create the new global variable. The contents of the malloc'd memory is
849 // undefined, so initialize with an undef value.
850 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
852 GlobalValue::InternalLinkage,
853 UndefValue::get(GlobalType),
854 GV->getName()+".body",
856 GV->isThreadLocal());
858 // If there are bitcast users of the malloc (which is typical, usually we have
859 // a malloc + bitcast) then replace them with uses of the new global. Update
860 // other users to use the global as well.
861 BitCastInst *TheBC = 0;
862 while (!CI->use_empty()) {
863 Instruction *User = cast<Instruction>(CI->use_back());
864 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
865 if (BCI->getType() == NewGV->getType()) {
866 BCI->replaceAllUsesWith(NewGV);
867 BCI->eraseFromParent();
869 BCI->setOperand(0, NewGV);
873 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
874 User->replaceUsesOfWith(CI, TheBC);
878 Constant *RepValue = NewGV;
879 if (NewGV->getType() != GV->getType()->getElementType())
880 RepValue = ConstantExpr::getBitCast(RepValue,
881 GV->getType()->getElementType());
883 // If there is a comparison against null, we will insert a global bool to
884 // keep track of whether the global was initialized yet or not.
885 GlobalVariable *InitBool =
886 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
887 GlobalValue::InternalLinkage,
888 ConstantInt::getFalse(GV->getContext()),
889 GV->getName()+".init", GV->isThreadLocal());
890 bool InitBoolUsed = false;
892 // Loop over all uses of GV, processing them in turn.
893 while (!GV->use_empty()) {
894 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
895 // The global is initialized when the store to it occurs.
896 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
897 SI->eraseFromParent();
901 LoadInst *LI = cast<LoadInst>(GV->use_back());
902 while (!LI->use_empty()) {
903 Use &LoadUse = LI->use_begin().getUse();
904 if (!isa<ICmpInst>(LoadUse.getUser())) {
909 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
910 // Replace the cmp X, 0 with a use of the bool value.
911 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
913 switch (ICI->getPredicate()) {
914 default: llvm_unreachable("Unknown ICmp Predicate!");
915 case ICmpInst::ICMP_ULT:
916 case ICmpInst::ICMP_SLT: // X < null -> always false
917 LV = ConstantInt::getFalse(GV->getContext());
919 case ICmpInst::ICMP_ULE:
920 case ICmpInst::ICMP_SLE:
921 case ICmpInst::ICMP_EQ:
922 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
924 case ICmpInst::ICMP_NE:
925 case ICmpInst::ICMP_UGE:
926 case ICmpInst::ICMP_SGE:
927 case ICmpInst::ICMP_UGT:
928 case ICmpInst::ICMP_SGT:
931 ICI->replaceAllUsesWith(LV);
932 ICI->eraseFromParent();
934 LI->eraseFromParent();
937 // If the initialization boolean was used, insert it, otherwise delete it.
939 while (!InitBool->use_empty()) // Delete initializations
940 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
943 GV->getParent()->getGlobalList().insert(GV, InitBool);
945 // Now the GV is dead, nuke it and the malloc..
946 GV->eraseFromParent();
947 CI->eraseFromParent();
949 // To further other optimizations, loop over all users of NewGV and try to
950 // constant prop them. This will promote GEP instructions with constant
951 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
952 ConstantPropUsersOf(NewGV);
953 if (RepValue != NewGV)
954 ConstantPropUsersOf(RepValue);
959 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
960 /// to make sure that there are no complex uses of V. We permit simple things
961 /// like dereferencing the pointer, but not storing through the address, unless
962 /// it is to the specified global.
963 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
964 const GlobalVariable *GV,
965 SmallPtrSet<const PHINode*, 8> &PHIs) {
966 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
968 const Instruction *Inst = cast<Instruction>(*UI);
970 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
971 continue; // Fine, ignore.
974 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
975 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
976 return false; // Storing the pointer itself... bad.
977 continue; // Otherwise, storing through it, or storing into GV... fine.
980 // Must index into the array and into the struct.
981 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
982 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
987 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
988 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
991 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
996 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
997 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1007 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1008 /// somewhere. Transform all uses of the allocation into loads from the
1009 /// global and uses of the resultant pointer. Further, delete the store into
1010 /// GV. This assumes that these value pass the
1011 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
1012 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
1013 GlobalVariable *GV) {
1014 while (!Alloc->use_empty()) {
1015 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1016 Instruction *InsertPt = U;
1017 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1018 // If this is the store of the allocation into the global, remove it.
1019 if (SI->getOperand(1) == GV) {
1020 SI->eraseFromParent();
1023 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1024 // Insert the load in the corresponding predecessor, not right before the
1026 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
1027 } else if (isa<BitCastInst>(U)) {
1028 // Must be bitcast between the malloc and store to initialize the global.
1029 ReplaceUsesOfMallocWithGlobal(U, GV);
1030 U->eraseFromParent();
1032 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1033 // If this is a "GEP bitcast" and the user is a store to the global, then
1034 // just process it as a bitcast.
1035 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1036 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1037 if (SI->getOperand(1) == GV) {
1038 // Must be bitcast GEP between the malloc and store to initialize
1040 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1041 GEPI->eraseFromParent();
1046 // Insert a load from the global, and use it instead of the malloc.
1047 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
1048 U->replaceUsesOfWith(Alloc, NL);
1052 /// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1053 /// of a load) are simple enough to perform heap SRA on. This permits GEP's
1054 /// that index through the array and struct field, icmps of null, and PHIs.
1055 static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
1056 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1057 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
1058 // We permit two users of the load: setcc comparing against the null
1059 // pointer, and a getelementptr of a specific form.
1060 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1062 const Instruction *User = cast<Instruction>(*UI);
1064 // Comparison against null is ok.
1065 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1066 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1071 // getelementptr is also ok, but only a simple form.
1072 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1073 // Must index into the array and into the struct.
1074 if (GEPI->getNumOperands() < 3)
1077 // Otherwise the GEP is ok.
1081 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
1082 if (!LoadUsingPHIsPerLoad.insert(PN))
1083 // This means some phi nodes are dependent on each other.
1084 // Avoid infinite looping!
1086 if (!LoadUsingPHIs.insert(PN))
1087 // If we have already analyzed this PHI, then it is safe.
1090 // Make sure all uses of the PHI are simple enough to transform.
1091 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1092 LoadUsingPHIs, LoadUsingPHIsPerLoad))
1098 // Otherwise we don't know what this is, not ok.
1106 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1107 /// GV are simple enough to perform HeapSRA, return true.
1108 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
1109 Instruction *StoredVal) {
1110 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1111 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
1112 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1114 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1115 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1116 LoadUsingPHIsPerLoad))
1118 LoadUsingPHIsPerLoad.clear();
1121 // If we reach here, we know that all uses of the loads and transitive uses
1122 // (through PHI nodes) are simple enough to transform. However, we don't know
1123 // that all inputs the to the PHI nodes are in the same equivalence sets.
1124 // Check to verify that all operands of the PHIs are either PHIS that can be
1125 // transformed, loads from GV, or MI itself.
1126 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1127 , E = LoadUsingPHIs.end(); I != E; ++I) {
1128 const PHINode *PN = *I;
1129 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1130 Value *InVal = PN->getIncomingValue(op);
1132 // PHI of the stored value itself is ok.
1133 if (InVal == StoredVal) continue;
1135 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1136 // One of the PHIs in our set is (optimistically) ok.
1137 if (LoadUsingPHIs.count(InPN))
1142 // Load from GV is ok.
1143 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
1144 if (LI->getOperand(0) == GV)
1149 // Anything else is rejected.
1157 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1158 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1159 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1160 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1162 if (FieldNo >= FieldVals.size())
1163 FieldVals.resize(FieldNo+1);
1165 // If we already have this value, just reuse the previously scalarized
1167 if (Value *FieldVal = FieldVals[FieldNo])
1170 // Depending on what instruction this is, we have several cases.
1172 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1173 // This is a scalarized version of the load from the global. Just create
1174 // a new Load of the scalarized global.
1175 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1176 InsertedScalarizedValues,
1178 LI->getName()+".f"+Twine(FieldNo), LI);
1179 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1180 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1182 const StructType *ST =
1183 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1186 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1187 PN->getName()+".f"+Twine(FieldNo), PN);
1188 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1190 llvm_unreachable("Unknown usable value");
1194 return FieldVals[FieldNo] = Result;
1197 /// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1198 /// the load, rewrite the derived value to use the HeapSRoA'd load.
1199 static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1200 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1201 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1202 // If this is a comparison against null, handle it.
1203 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1204 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1205 // If we have a setcc of the loaded pointer, we can use a setcc of any
1207 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1208 InsertedScalarizedValues, PHIsToRewrite);
1210 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
1211 Constant::getNullValue(NPtr->getType()),
1213 SCI->replaceAllUsesWith(New);
1214 SCI->eraseFromParent();
1218 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
1219 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1220 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1221 && "Unexpected GEPI!");
1223 // Load the pointer for this field.
1224 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1225 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1226 InsertedScalarizedValues, PHIsToRewrite);
1228 // Create the new GEP idx vector.
1229 SmallVector<Value*, 8> GEPIdx;
1230 GEPIdx.push_back(GEPI->getOperand(1));
1231 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1233 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1234 GEPIdx.begin(), GEPIdx.end(),
1235 GEPI->getName(), GEPI);
1236 GEPI->replaceAllUsesWith(NGEPI);
1237 GEPI->eraseFromParent();
1241 // Recursively transform the users of PHI nodes. This will lazily create the
1242 // PHIs that are needed for individual elements. Keep track of what PHIs we
1243 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1244 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1245 // already been seen first by another load, so its uses have already been
1247 PHINode *PN = cast<PHINode>(LoadUser);
1249 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1250 tie(InsertPos, Inserted) =
1251 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1252 if (!Inserted) return;
1254 // If this is the first time we've seen this PHI, recursively process all
1256 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1257 Instruction *User = cast<Instruction>(*UI++);
1258 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1262 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1263 /// is a value loaded from the global. Eliminate all uses of Ptr, making them
1264 /// use FieldGlobals instead. All uses of loaded values satisfy
1265 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
1266 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
1267 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1268 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1269 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
1271 Instruction *User = cast<Instruction>(*UI++);
1272 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1275 if (Load->use_empty()) {
1276 Load->eraseFromParent();
1277 InsertedScalarizedValues.erase(Load);
1281 /// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1282 /// it up into multiple allocations of arrays of the fields.
1283 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1284 Value* NElems, TargetData *TD) {
1285 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
1286 const Type* MAT = getMallocAllocatedType(CI);
1287 const StructType *STy = cast<StructType>(MAT);
1289 // There is guaranteed to be at least one use of the malloc (storing
1290 // it into GV). If there are other uses, change them to be uses of
1291 // the global to simplify later code. This also deletes the store
1293 ReplaceUsesOfMallocWithGlobal(CI, GV);
1295 // Okay, at this point, there are no users of the malloc. Insert N
1296 // new mallocs at the same place as CI, and N globals.
1297 std::vector<Value*> FieldGlobals;
1298 std::vector<Value*> FieldMallocs;
1300 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1301 const Type *FieldTy = STy->getElementType(FieldNo);
1302 const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1304 GlobalVariable *NGV =
1305 new GlobalVariable(*GV->getParent(),
1306 PFieldTy, false, GlobalValue::InternalLinkage,
1307 Constant::getNullValue(PFieldTy),
1308 GV->getName() + ".f" + Twine(FieldNo), GV,
1309 GV->isThreadLocal());
1310 FieldGlobals.push_back(NGV);
1312 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
1313 if (const StructType *ST = dyn_cast<StructType>(FieldTy))
1314 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
1315 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1316 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1317 ConstantInt::get(IntPtrTy, TypeSize),
1319 CI->getName() + ".f" + Twine(FieldNo));
1320 FieldMallocs.push_back(NMI);
1321 new StoreInst(NMI, NGV, CI);
1324 // The tricky aspect of this transformation is handling the case when malloc
1325 // fails. In the original code, malloc failing would set the result pointer
1326 // of malloc to null. In this case, some mallocs could succeed and others
1327 // could fail. As such, we emit code that looks like this:
1328 // F0 = malloc(field0)
1329 // F1 = malloc(field1)
1330 // F2 = malloc(field2)
1331 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1332 // if (F0) { free(F0); F0 = 0; }
1333 // if (F1) { free(F1); F1 = 0; }
1334 // if (F2) { free(F2); F2 = 0; }
1336 // The malloc can also fail if its argument is too large.
1337 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1338 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
1339 ConstantZero, "isneg");
1340 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1341 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1342 Constant::getNullValue(FieldMallocs[i]->getType()),
1344 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
1347 // Split the basic block at the old malloc.
1348 BasicBlock *OrigBB = CI->getParent();
1349 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
1351 // Create the block to check the first condition. Put all these blocks at the
1352 // end of the function as they are unlikely to be executed.
1353 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1355 OrigBB->getParent());
1357 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1358 // branch on RunningOr.
1359 OrigBB->getTerminator()->eraseFromParent();
1360 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1362 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1363 // pointer, because some may be null while others are not.
1364 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1365 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1366 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1367 Constant::getNullValue(GVVal->getType()),
1369 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
1370 OrigBB->getParent());
1371 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
1372 OrigBB->getParent());
1373 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1376 // Fill in FreeBlock.
1377 CallInst::CreateFree(GVVal, BI);
1378 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1380 BranchInst::Create(NextBlock, FreeBlock);
1382 NullPtrBlock = NextBlock;
1385 BranchInst::Create(ContBB, NullPtrBlock);
1387 // CI is no longer needed, remove it.
1388 CI->eraseFromParent();
1390 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1391 /// update all uses of the load, keep track of what scalarized loads are
1392 /// inserted for a given load.
1393 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1394 InsertedScalarizedValues[GV] = FieldGlobals;
1396 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1398 // Okay, the malloc site is completely handled. All of the uses of GV are now
1399 // loads, and all uses of those loads are simple. Rewrite them to use loads
1400 // of the per-field globals instead.
1401 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1402 Instruction *User = cast<Instruction>(*UI++);
1404 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1405 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
1409 // Must be a store of null.
1410 StoreInst *SI = cast<StoreInst>(User);
1411 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1412 "Unexpected heap-sra user!");
1414 // Insert a store of null into each global.
1415 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1416 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1417 Constant *Null = Constant::getNullValue(PT->getElementType());
1418 new StoreInst(Null, FieldGlobals[i], SI);
1420 // Erase the original store.
1421 SI->eraseFromParent();
1424 // While we have PHIs that are interesting to rewrite, do it.
1425 while (!PHIsToRewrite.empty()) {
1426 PHINode *PN = PHIsToRewrite.back().first;
1427 unsigned FieldNo = PHIsToRewrite.back().second;
1428 PHIsToRewrite.pop_back();
1429 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1430 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1432 // Add all the incoming values. This can materialize more phis.
1433 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1434 Value *InVal = PN->getIncomingValue(i);
1435 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1437 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1441 // Drop all inter-phi links and any loads that made it this far.
1442 for (DenseMap<Value*, std::vector<Value*> >::iterator
1443 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1445 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1446 PN->dropAllReferences();
1447 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1448 LI->dropAllReferences();
1451 // Delete all the phis and loads now that inter-references are dead.
1452 for (DenseMap<Value*, std::vector<Value*> >::iterator
1453 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1455 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1456 PN->eraseFromParent();
1457 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1458 LI->eraseFromParent();
1461 // The old global is now dead, remove it.
1462 GV->eraseFromParent();
1465 return cast<GlobalVariable>(FieldGlobals[0]);
1468 /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1469 /// pointer global variable with a single value stored it that is a malloc or
1471 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1473 const Type *AllocTy,
1474 Module::global_iterator &GVI,
1479 // If this is a malloc of an abstract type, don't touch it.
1480 if (!AllocTy->isSized())
1483 // We can't optimize this global unless all uses of it are *known* to be
1484 // of the malloc value, not of the null initializer value (consider a use
1485 // that compares the global's value against zero to see if the malloc has
1486 // been reached). To do this, we check to see if all uses of the global
1487 // would trap if the global were null: this proves that they must all
1488 // happen after the malloc.
1489 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1492 // We can't optimize this if the malloc itself is used in a complex way,
1493 // for example, being stored into multiple globals. This allows the
1494 // malloc to be stored into the specified global, loaded setcc'd, and
1495 // GEP'd. These are all things we could transform to using the global
1497 SmallPtrSet<const PHINode*, 8> PHIs;
1498 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1501 // If we have a global that is only initialized with a fixed size malloc,
1502 // transform the program to use global memory instead of malloc'd memory.
1503 // This eliminates dynamic allocation, avoids an indirection accessing the
1504 // data, and exposes the resultant global to further GlobalOpt.
1505 // We cannot optimize the malloc if we cannot determine malloc array size.
1506 Value *NElems = getMallocArraySize(CI, TD, true);
1510 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1511 // Restrict this transformation to only working on small allocations
1512 // (2048 bytes currently), as we don't want to introduce a 16M global or
1514 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1515 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
1519 // If the allocation is an array of structures, consider transforming this
1520 // into multiple malloc'd arrays, one for each field. This is basically
1521 // SRoA for malloc'd memory.
1523 // If this is an allocation of a fixed size array of structs, analyze as a
1524 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1525 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
1526 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1527 AllocTy = AT->getElementType();
1529 const StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
1533 // This the structure has an unreasonable number of fields, leave it
1535 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1536 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1538 // If this is a fixed size array, transform the Malloc to be an alloc of
1539 // structs. malloc [100 x struct],1 -> malloc struct, 100
1540 if (const ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1541 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1542 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1543 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1544 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1545 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1546 AllocSize, NumElements,
1548 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1549 CI->replaceAllUsesWith(Cast);
1550 CI->eraseFromParent();
1551 CI = dyn_cast<BitCastInst>(Malloc) ?
1552 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
1555 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
1562 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1563 // that only one value (besides its initializer) is ever stored to the global.
1564 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1565 Module::global_iterator &GVI,
1567 // Ignore no-op GEPs and bitcasts.
1568 StoredOnceVal = StoredOnceVal->stripPointerCasts();
1570 // If we are dealing with a pointer global that is initialized to null and
1571 // only has one (non-null) value stored into it, then we can optimize any
1572 // users of the loaded value (often calls and loads) that would trap if the
1574 if (GV->getInitializer()->getType()->isPointerTy() &&
1575 GV->getInitializer()->isNullValue()) {
1576 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1577 if (GV->getInitializer()->getType() != SOVC->getType())
1579 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1581 // Optimize away any trapping uses of the loaded value.
1582 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
1584 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
1585 const Type* MallocType = getMallocAllocatedType(CI);
1586 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
1595 /// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1596 /// two values ever stored into GV are its initializer and OtherVal. See if we
1597 /// can shrink the global into a boolean and select between the two values
1598 /// whenever it is used. This exposes the values to other scalar optimizations.
1599 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1600 const Type *GVElType = GV->getType()->getElementType();
1602 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1603 // an FP value, pointer or vector, don't do this optimization because a select
1604 // between them is very expensive and unlikely to lead to later
1605 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1606 // where v1 and v2 both require constant pool loads, a big loss.
1607 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
1608 GVElType->isFloatingPointTy() ||
1609 GVElType->isPointerTy() || GVElType->isVectorTy())
1612 // Walk the use list of the global seeing if all the uses are load or store.
1613 // If there is anything else, bail out.
1614 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1616 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
1620 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
1622 // Create the new global, initializing it to false.
1623 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1625 GlobalValue::InternalLinkage,
1626 ConstantInt::getFalse(GV->getContext()),
1628 GV->isThreadLocal());
1629 GV->getParent()->getGlobalList().insert(GV, NewGV);
1631 Constant *InitVal = GV->getInitializer();
1632 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
1633 "No reason to shrink to bool!");
1635 // If initialized to zero and storing one into the global, we can use a cast
1636 // instead of a select to synthesize the desired value.
1637 bool IsOneZero = false;
1638 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1639 IsOneZero = InitVal->isNullValue() && CI->isOne();
1641 while (!GV->use_empty()) {
1642 Instruction *UI = cast<Instruction>(GV->use_back());
1643 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1644 // Change the store into a boolean store.
1645 bool StoringOther = SI->getOperand(0) == OtherVal;
1646 // Only do this if we weren't storing a loaded value.
1648 if (StoringOther || SI->getOperand(0) == InitVal)
1649 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1652 // Otherwise, we are storing a previously loaded copy. To do this,
1653 // change the copy from copying the original value to just copying the
1655 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1657 // If we've already replaced the input, StoredVal will be a cast or
1658 // select instruction. If not, it will be a load of the original
1660 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1661 assert(LI->getOperand(0) == GV && "Not a copy!");
1662 // Insert a new load, to preserve the saved value.
1663 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1665 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1666 "This is not a form that we understand!");
1667 StoreVal = StoredVal->getOperand(0);
1668 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1671 new StoreInst(StoreVal, NewGV, SI);
1673 // Change the load into a load of bool then a select.
1674 LoadInst *LI = cast<LoadInst>(UI);
1675 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1678 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1680 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1682 LI->replaceAllUsesWith(NSI);
1684 UI->eraseFromParent();
1687 GV->eraseFromParent();
1692 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1693 /// it if possible. If we make a change, return true.
1694 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1695 Module::global_iterator &GVI) {
1696 SmallPtrSet<const PHINode*, 16> PHIUsers;
1698 GV->removeDeadConstantUsers();
1700 if (GV->use_empty()) {
1701 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
1702 GV->eraseFromParent();
1707 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1709 DEBUG(dbgs() << "Global: " << *GV);
1710 DEBUG(dbgs() << " isLoaded = " << GS.isLoaded << "\n");
1711 DEBUG(dbgs() << " StoredType = ");
1712 switch (GS.StoredType) {
1713 case GlobalStatus::NotStored: DEBUG(dbgs() << "NEVER STORED\n"); break;
1714 case GlobalStatus::isInitializerStored: DEBUG(dbgs() << "INIT STORED\n");
1716 case GlobalStatus::isStoredOnce: DEBUG(dbgs() << "STORED ONCE\n"); break;
1717 case GlobalStatus::isStored: DEBUG(dbgs() << "stored\n"); break;
1719 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1720 DEBUG(dbgs() << " StoredOnceValue = " << *GS.StoredOnceValue << "\n");
1721 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1722 DEBUG(dbgs() << " AccessingFunction = "
1723 << GS.AccessingFunction->getName() << "\n");
1724 DEBUG(dbgs() << " HasMultipleAccessingFunctions = "
1725 << GS.HasMultipleAccessingFunctions << "\n");
1726 DEBUG(dbgs() << " HasNonInstructionUser = "
1727 << GS.HasNonInstructionUser<<"\n");
1728 DEBUG(dbgs() << "\n");
1731 // If this is a first class global and has only one accessing function
1732 // and this function is main (which we know is not recursive we can make
1733 // this global a local variable) we replace the global with a local alloca
1734 // in this function.
1736 // NOTE: It doesn't make sense to promote non single-value types since we
1737 // are just replacing static memory to stack memory.
1739 // If the global is in different address space, don't bring it to stack.
1740 if (!GS.HasMultipleAccessingFunctions &&
1741 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1742 GV->getType()->getElementType()->isSingleValueType() &&
1743 GS.AccessingFunction->getName() == "main" &&
1744 GS.AccessingFunction->hasExternalLinkage() &&
1745 GV->getType()->getAddressSpace() == 0) {
1746 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1747 Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1748 ->getEntryBlock().begin());
1749 const Type* ElemTy = GV->getType()->getElementType();
1750 // FIXME: Pass Global's alignment when globals have alignment
1751 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1752 if (!isa<UndefValue>(GV->getInitializer()))
1753 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1755 GV->replaceAllUsesWith(Alloca);
1756 GV->eraseFromParent();
1761 // If the global is never loaded (but may be stored to), it is dead.
1764 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1766 // Delete any stores we can find to the global. We may not be able to
1767 // make it completely dead though.
1768 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1770 // If the global is dead now, delete it.
1771 if (GV->use_empty()) {
1772 GV->eraseFromParent();
1778 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1779 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1780 GV->setConstant(true);
1782 // Clean up any obviously simplifiable users now.
1783 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1785 // If the global is dead now, just nuke it.
1786 if (GV->use_empty()) {
1787 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1788 << "all users and delete global!\n");
1789 GV->eraseFromParent();
1795 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1796 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1797 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1798 GVI = FirstNewGV; // Don't skip the newly produced globals!
1801 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1802 // If the initial value for the global was an undef value, and if only
1803 // one other value was stored into it, we can just change the
1804 // initializer to be the stored value, then delete all stores to the
1805 // global. This allows us to mark it constant.
1806 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1807 if (isa<UndefValue>(GV->getInitializer())) {
1808 // Change the initial value here.
1809 GV->setInitializer(SOVConstant);
1811 // Clean up any obviously simplifiable users now.
1812 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1814 if (GV->use_empty()) {
1815 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1816 << "simplify all users and delete global!\n");
1817 GV->eraseFromParent();
1826 // Try to optimize globals based on the knowledge that only one value
1827 // (besides its initializer) is ever stored to the global.
1828 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1829 getAnalysisIfAvailable<TargetData>()))
1832 // Otherwise, if the global was not a boolean, we can shrink it to be a
1834 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1835 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1844 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1845 /// function, changing them to FastCC.
1846 static void ChangeCalleesToFastCall(Function *F) {
1847 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1848 CallSite User(cast<Instruction>(*UI));
1849 User.setCallingConv(CallingConv::Fast);
1853 static AttrListPtr StripNest(const AttrListPtr &Attrs) {
1854 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1855 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
1858 // There can be only one.
1859 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
1865 static void RemoveNestAttribute(Function *F) {
1866 F->setAttributes(StripNest(F->getAttributes()));
1867 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1868 CallSite User(cast<Instruction>(*UI));
1869 User.setAttributes(StripNest(User.getAttributes()));
1873 bool GlobalOpt::OptimizeFunctions(Module &M) {
1874 bool Changed = false;
1875 // Optimize functions.
1876 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1878 // Functions without names cannot be referenced outside this module.
1879 if (!F->hasName() && !F->isDeclaration())
1880 F->setLinkage(GlobalValue::InternalLinkage);
1881 F->removeDeadConstantUsers();
1882 if (F->use_empty() && (F->hasLocalLinkage() || F->hasLinkOnceLinkage())) {
1883 F->eraseFromParent();
1886 } else if (F->hasLocalLinkage()) {
1887 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1888 !F->hasAddressTaken()) {
1889 // If this function has C calling conventions, is not a varargs
1890 // function, and is only called directly, promote it to use the Fast
1891 // calling convention.
1892 F->setCallingConv(CallingConv::Fast);
1893 ChangeCalleesToFastCall(F);
1898 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
1899 !F->hasAddressTaken()) {
1900 // The function is not used by a trampoline intrinsic, so it is safe
1901 // to remove the 'nest' attribute.
1902 RemoveNestAttribute(F);
1911 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1912 bool Changed = false;
1913 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1915 GlobalVariable *GV = GVI++;
1916 // Global variables without names cannot be referenced outside this module.
1917 if (!GV->hasName() && !GV->isDeclaration())
1918 GV->setLinkage(GlobalValue::InternalLinkage);
1919 // Simplify the initializer.
1920 if (GV->hasInitializer())
1921 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
1922 TargetData *TD = getAnalysisIfAvailable<TargetData>();
1923 Constant *New = ConstantFoldConstantExpression(CE, TD);
1924 if (New && New != CE)
1925 GV->setInitializer(New);
1927 // Do more involved optimizations if the global is internal.
1928 if (!GV->isConstant() && GV->hasLocalLinkage() &&
1929 GV->hasInitializer())
1930 Changed |= ProcessInternalGlobal(GV, GVI);
1935 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1936 /// initializers have an init priority of 65535.
1937 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1938 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1939 if (GV == 0) return 0;
1941 // Found it, verify it's an array of { int, void()* }.
1942 const ArrayType *ATy =dyn_cast<ArrayType>(GV->getType()->getElementType());
1944 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1945 if (!STy || STy->getNumElements() != 2 ||
1946 !STy->getElementType(0)->isIntegerTy(32)) return 0;
1947 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1948 if (!PFTy) return 0;
1949 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1950 if (!FTy || !FTy->getReturnType()->isVoidTy() ||
1951 FTy->isVarArg() || FTy->getNumParams() != 0)
1954 // Verify that the initializer is simple enough for us to handle. We are
1955 // only allowed to optimize the initializer if it is unique.
1956 if (!GV->hasUniqueInitializer()) return 0;
1958 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1961 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1962 ConstantStruct *CS = dyn_cast<ConstantStruct>(*i);
1963 if (CS == 0) return 0;
1965 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1968 // Must have a function or null ptr.
1969 if (!isa<Function>(CS->getOperand(1)))
1972 // Init priority must be standard.
1973 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1974 if (!CI || CI->getZExtValue() != 65535)
1981 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1982 /// return a list of the functions and null terminator as a vector.
1983 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1984 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1985 std::vector<Function*> Result;
1986 Result.reserve(CA->getNumOperands());
1987 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1988 ConstantStruct *CS = cast<ConstantStruct>(*i);
1989 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1994 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1995 /// specified array, returning the new global to use.
1996 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1997 const std::vector<Function*> &Ctors) {
1998 // If we made a change, reassemble the initializer list.
1999 std::vector<Constant*> CSVals;
2000 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(GCL->getContext()),65535));
2001 CSVals.push_back(0);
2003 // Create the new init list.
2004 std::vector<Constant*> CAList;
2005 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
2007 CSVals[1] = Ctors[i];
2009 const Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
2011 const PointerType *PFTy = PointerType::getUnqual(FTy);
2012 CSVals[1] = Constant::getNullValue(PFTy);
2013 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
2016 CAList.push_back(ConstantStruct::get(GCL->getContext(), CSVals, false));
2019 // Create the array initializer.
2020 const Type *StructTy =
2021 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
2022 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
2023 CAList.size()), CAList);
2025 // If we didn't change the number of elements, don't create a new GV.
2026 if (CA->getType() == GCL->getInitializer()->getType()) {
2027 GCL->setInitializer(CA);
2031 // Create the new global and insert it next to the existing list.
2032 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
2033 GCL->getLinkage(), CA, "",
2034 GCL->isThreadLocal());
2035 GCL->getParent()->getGlobalList().insert(GCL, NGV);
2038 // Nuke the old list, replacing any uses with the new one.
2039 if (!GCL->use_empty()) {
2041 if (V->getType() != GCL->getType())
2042 V = ConstantExpr::getBitCast(V, GCL->getType());
2043 GCL->replaceAllUsesWith(V);
2045 GCL->eraseFromParent();
2054 static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues, Value *V) {
2055 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2056 Constant *R = ComputedValues[V];
2057 assert(R && "Reference to an uncomputed value!");
2062 isSimpleEnoughValueToCommit(Constant *C,
2063 SmallPtrSet<Constant*, 8> &SimpleConstants);
2066 /// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2067 /// handled by the code generator. We don't want to generate something like:
2068 /// void *X = &X/42;
2069 /// because the code generator doesn't have a relocation that can handle that.
2071 /// This function should be called if C was not found (but just got inserted)
2072 /// in SimpleConstants to avoid having to rescan the same constants all the
2074 static bool isSimpleEnoughValueToCommitHelper(Constant *C,
2075 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2076 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2078 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2079 isa<GlobalValue>(C))
2082 // Aggregate values are safe if all their elements are.
2083 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2084 isa<ConstantVector>(C)) {
2085 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2086 Constant *Op = cast<Constant>(C->getOperand(i));
2087 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants))
2093 // We don't know exactly what relocations are allowed in constant expressions,
2094 // so we allow &global+constantoffset, which is safe and uniformly supported
2096 ConstantExpr *CE = cast<ConstantExpr>(C);
2097 switch (CE->getOpcode()) {
2098 case Instruction::BitCast:
2099 case Instruction::IntToPtr:
2100 case Instruction::PtrToInt:
2101 // These casts are always fine if the casted value is.
2102 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2104 // GEP is fine if it is simple + constant offset.
2105 case Instruction::GetElementPtr:
2106 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2107 if (!isa<ConstantInt>(CE->getOperand(i)))
2109 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2111 case Instruction::Add:
2112 // We allow simple+cst.
2113 if (!isa<ConstantInt>(CE->getOperand(1)))
2115 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2121 isSimpleEnoughValueToCommit(Constant *C,
2122 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2123 // If we already checked this constant, we win.
2124 if (!SimpleConstants.insert(C)) return true;
2125 // Check the constant.
2126 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants);
2130 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2131 /// enough for us to understand. In particular, if it is a cast to anything
2132 /// other than from one pointer type to another pointer type, we punt.
2133 /// We basically just support direct accesses to globals and GEP's of
2134 /// globals. This should be kept up to date with CommitValueTo.
2135 static bool isSimpleEnoughPointerToCommit(Constant *C) {
2136 // Conservatively, avoid aggregate types. This is because we don't
2137 // want to worry about them partially overlapping other stores.
2138 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2141 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2142 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2143 // external globals.
2144 return GV->hasUniqueInitializer();
2146 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2147 // Handle a constantexpr gep.
2148 if (CE->getOpcode() == Instruction::GetElementPtr &&
2149 isa<GlobalVariable>(CE->getOperand(0)) &&
2150 cast<GEPOperator>(CE)->isInBounds()) {
2151 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2152 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2153 // external globals.
2154 if (!GV->hasUniqueInitializer())
2157 // The first index must be zero.
2158 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
2159 if (!CI || !CI->isZero()) return false;
2161 // The remaining indices must be compile-time known integers within the
2162 // notional bounds of the corresponding static array types.
2163 if (!CE->isGEPWithNoNotionalOverIndexing())
2166 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2168 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2169 // and we know how to evaluate it by moving the bitcast from the pointer
2170 // operand to the value operand.
2171 } else if (CE->getOpcode() == Instruction::BitCast &&
2172 CE->getType()->isPointerTy() &&
2173 CE->getOperand(0)->getType()->isPointerTy()) {
2174 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2175 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2176 // external globals.
2177 if (!GV->hasUniqueInitializer())
2187 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2188 /// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2189 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2190 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2191 ConstantExpr *Addr, unsigned OpNo) {
2192 // Base case of the recursion.
2193 if (OpNo == Addr->getNumOperands()) {
2194 assert(Val->getType() == Init->getType() && "Type mismatch!");
2198 std::vector<Constant*> Elts;
2199 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2201 // Break up the constant into its elements.
2202 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2203 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2204 Elts.push_back(cast<Constant>(*i));
2205 } else if (isa<ConstantAggregateZero>(Init)) {
2206 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2207 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
2208 } else if (isa<UndefValue>(Init)) {
2209 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2210 Elts.push_back(UndefValue::get(STy->getElementType(i)));
2212 llvm_unreachable("This code is out of sync with "
2213 " ConstantFoldLoadThroughGEPConstantExpr");
2216 // Replace the element that we are supposed to.
2217 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2218 unsigned Idx = CU->getZExtValue();
2219 assert(Idx < STy->getNumElements() && "Struct index out of range!");
2220 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2222 // Return the modified struct.
2223 return ConstantStruct::get(Init->getContext(), &Elts[0], Elts.size(),
2226 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2227 const SequentialType *InitTy = cast<SequentialType>(Init->getType());
2230 if (const ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2231 NumElts = ATy->getNumElements();
2233 NumElts = cast<VectorType>(InitTy)->getNumElements();
2236 // Break up the array into elements.
2237 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2238 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2239 Elts.push_back(cast<Constant>(*i));
2240 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2241 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2242 Elts.push_back(cast<Constant>(*i));
2243 } else if (isa<ConstantAggregateZero>(Init)) {
2244 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
2246 assert(isa<UndefValue>(Init) && "This code is out of sync with "
2247 " ConstantFoldLoadThroughGEPConstantExpr");
2248 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
2251 assert(CI->getZExtValue() < NumElts);
2252 Elts[CI->getZExtValue()] =
2253 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2255 if (Init->getType()->isArrayTy())
2256 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2258 return ConstantVector::get(&Elts[0], Elts.size());
2262 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
2263 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2264 static void CommitValueTo(Constant *Val, Constant *Addr) {
2265 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2266 assert(GV->hasInitializer());
2267 GV->setInitializer(Val);
2271 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2272 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2273 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
2276 /// ComputeLoadResult - Return the value that would be computed by a load from
2277 /// P after the stores reflected by 'memory' have been performed. If we can't
2278 /// decide, return null.
2279 static Constant *ComputeLoadResult(Constant *P,
2280 const DenseMap<Constant*, Constant*> &Memory) {
2281 // If this memory location has been recently stored, use the stored value: it
2282 // is the most up-to-date.
2283 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
2284 if (I != Memory.end()) return I->second;
2287 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2288 if (GV->hasDefinitiveInitializer())
2289 return GV->getInitializer();
2293 // Handle a constantexpr getelementptr.
2294 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2295 if (CE->getOpcode() == Instruction::GetElementPtr &&
2296 isa<GlobalVariable>(CE->getOperand(0))) {
2297 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2298 if (GV->hasDefinitiveInitializer())
2299 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2302 return 0; // don't know how to evaluate.
2305 /// EvaluateFunction - Evaluate a call to function F, returning true if
2306 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2307 /// arguments for the function.
2308 static bool EvaluateFunction(Function *F, Constant *&RetVal,
2309 const SmallVectorImpl<Constant*> &ActualArgs,
2310 std::vector<Function*> &CallStack,
2311 DenseMap<Constant*, Constant*> &MutatedMemory,
2312 std::vector<GlobalVariable*> &AllocaTmps,
2313 SmallPtrSet<Constant*, 8> &SimpleConstants,
2314 const TargetData *TD) {
2315 // Check to see if this function is already executing (recursion). If so,
2316 // bail out. TODO: we might want to accept limited recursion.
2317 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2320 CallStack.push_back(F);
2322 /// Values - As we compute SSA register values, we store their contents here.
2323 DenseMap<Value*, Constant*> Values;
2325 // Initialize arguments to the incoming values specified.
2327 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2329 Values[AI] = ActualArgs[ArgNo];
2331 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2332 /// we can only evaluate any one basic block at most once. This set keeps
2333 /// track of what we have executed so we can detect recursive cases etc.
2334 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2336 // CurInst - The current instruction we're evaluating.
2337 BasicBlock::iterator CurInst = F->begin()->begin();
2339 // This is the main evaluation loop.
2341 Constant *InstResult = 0;
2343 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2344 if (SI->isVolatile()) return false; // no volatile accesses.
2345 Constant *Ptr = getVal(Values, SI->getOperand(1));
2346 if (!isSimpleEnoughPointerToCommit(Ptr))
2347 // If this is too complex for us to commit, reject it.
2350 Constant *Val = getVal(Values, SI->getOperand(0));
2352 // If this might be too difficult for the backend to handle (e.g. the addr
2353 // of one global variable divided by another) then we can't commit it.
2354 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants))
2357 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2358 if (CE->getOpcode() == Instruction::BitCast) {
2359 // If we're evaluating a store through a bitcast, then we need
2360 // to pull the bitcast off the pointer type and push it onto the
2362 Ptr = dyn_cast<Constant>(Ptr->getOperand(0));
2363 if (!Ptr) return false;
2365 const PointerType *Ty = dyn_cast<PointerType>(Ptr->getType());
2366 if (!Ty) return false;
2367 const Type *NewTy = Ty->getElementType();
2369 // A bitcast'd pointer implicitly points to the first field of a
2370 // struct. Insert implicity "gep @x, 0, 0, ..." until we get down
2371 // to the first concrete member.
2372 // FIXME: This could be extended to work for arrays as well.
2373 while (const StructType *STy = dyn_cast<StructType>(NewTy)) {
2374 NewTy = STy->getTypeAtIndex(0U);
2376 const IntegerType *IdxTy =
2377 IntegerType::get(NewTy->getContext(), 32);
2378 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2379 Constant * const IdxList[] = {IdxZero, IdxZero};
2381 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList, 2);
2384 if (!isa<PointerType>(NewTy)) return false;
2385 Val = ConstantExpr::getBitCast(Val, NewTy);
2388 MutatedMemory[Ptr] = Val;
2389 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2390 InstResult = ConstantExpr::get(BO->getOpcode(),
2391 getVal(Values, BO->getOperand(0)),
2392 getVal(Values, BO->getOperand(1)));
2393 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2394 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2395 getVal(Values, CI->getOperand(0)),
2396 getVal(Values, CI->getOperand(1)));
2397 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
2398 InstResult = ConstantExpr::getCast(CI->getOpcode(),
2399 getVal(Values, CI->getOperand(0)),
2401 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2402 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
2403 getVal(Values, SI->getOperand(1)),
2404 getVal(Values, SI->getOperand(2)));
2405 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2406 Constant *P = getVal(Values, GEP->getOperand(0));
2407 SmallVector<Constant*, 8> GEPOps;
2408 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2410 GEPOps.push_back(getVal(Values, *i));
2411 InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2412 ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2413 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
2414 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2415 if (LI->isVolatile()) return false; // no volatile accesses.
2416 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
2418 if (InstResult == 0) return false; // Could not evaluate load.
2419 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2420 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
2421 const Type *Ty = AI->getType()->getElementType();
2422 AllocaTmps.push_back(new GlobalVariable(Ty, false,
2423 GlobalValue::InternalLinkage,
2424 UndefValue::get(Ty),
2426 InstResult = AllocaTmps.back();
2427 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
2429 // Debug info can safely be ignored here.
2430 if (isa<DbgInfoIntrinsic>(CI)) {
2435 // Cannot handle inline asm.
2436 if (isa<InlineAsm>(CI->getCalledValue())) return false;
2438 // Resolve function pointers.
2439 Function *Callee = dyn_cast<Function>(getVal(Values,
2440 CI->getCalledValue()));
2441 if (!Callee) return false; // Cannot resolve.
2443 SmallVector<Constant*, 8> Formals;
2445 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end();
2447 Formals.push_back(getVal(Values, *i));
2449 if (Callee->isDeclaration()) {
2450 // If this is a function we can constant fold, do it.
2451 if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
2458 if (Callee->getFunctionType()->isVarArg())
2462 // Execute the call, if successful, use the return value.
2463 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2464 MutatedMemory, AllocaTmps, SimpleConstants, TD))
2466 InstResult = RetVal;
2468 } else if (isa<TerminatorInst>(CurInst)) {
2469 BasicBlock *NewBB = 0;
2470 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2471 if (BI->isUnconditional()) {
2472 NewBB = BI->getSuccessor(0);
2475 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
2476 if (!Cond) return false; // Cannot determine.
2478 NewBB = BI->getSuccessor(!Cond->getZExtValue());
2480 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2482 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
2483 if (!Val) return false; // Cannot determine.
2484 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2485 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2486 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2487 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2488 NewBB = BA->getBasicBlock();
2490 return false; // Cannot determine.
2491 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
2492 if (RI->getNumOperands())
2493 RetVal = getVal(Values, RI->getOperand(0));
2495 CallStack.pop_back(); // return from fn.
2496 return true; // We succeeded at evaluating this ctor!
2498 // invoke, unwind, unreachable.
2499 return false; // Cannot handle this terminator.
2502 // Okay, we succeeded in evaluating this control flow. See if we have
2503 // executed the new block before. If so, we have a looping function,
2504 // which we cannot evaluate in reasonable time.
2505 if (!ExecutedBlocks.insert(NewBB))
2506 return false; // looped!
2508 // Okay, we have never been in this block before. Check to see if there
2509 // are any PHI nodes. If so, evaluate them with information about where
2511 BasicBlock *OldBB = CurInst->getParent();
2512 CurInst = NewBB->begin();
2514 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2515 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2517 // Do NOT increment CurInst. We know that the terminator had no value.
2520 // Did not know how to evaluate this!
2524 if (!CurInst->use_empty()) {
2525 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
2526 InstResult = ConstantFoldConstantExpression(CE, TD);
2528 Values[CurInst] = InstResult;
2531 // Advance program counter.
2536 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2537 /// we can. Return true if we can, false otherwise.
2538 static bool EvaluateStaticConstructor(Function *F, const TargetData *TD) {
2539 /// MutatedMemory - For each store we execute, we update this map. Loads
2540 /// check this to get the most up-to-date value. If evaluation is successful,
2541 /// this state is committed to the process.
2542 DenseMap<Constant*, Constant*> MutatedMemory;
2544 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2545 /// to represent its body. This vector is needed so we can delete the
2546 /// temporary globals when we are done.
2547 std::vector<GlobalVariable*> AllocaTmps;
2549 /// CallStack - This is used to detect recursion. In pathological situations
2550 /// we could hit exponential behavior, but at least there is nothing
2552 std::vector<Function*> CallStack;
2554 /// SimpleConstants - These are constants we have checked and know to be
2555 /// simple enough to live in a static initializer of a global.
2556 SmallPtrSet<Constant*, 8> SimpleConstants;
2558 // Call the function.
2559 Constant *RetValDummy;
2560 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2561 SmallVector<Constant*, 0>(), CallStack,
2562 MutatedMemory, AllocaTmps,
2563 SimpleConstants, TD);
2566 // We succeeded at evaluation: commit the result.
2567 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2568 << F->getName() << "' to " << MutatedMemory.size()
2570 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
2571 E = MutatedMemory.end(); I != E; ++I)
2572 CommitValueTo(I->second, I->first);
2575 // At this point, we are done interpreting. If we created any 'alloca'
2576 // temporaries, release them now.
2577 while (!AllocaTmps.empty()) {
2578 GlobalVariable *Tmp = AllocaTmps.back();
2579 AllocaTmps.pop_back();
2581 // If there are still users of the alloca, the program is doing something
2582 // silly, e.g. storing the address of the alloca somewhere and using it
2583 // later. Since this is undefined, we'll just make it be null.
2584 if (!Tmp->use_empty())
2585 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2594 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2595 /// Return true if anything changed.
2596 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2597 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2598 bool MadeChange = false;
2599 if (Ctors.empty()) return false;
2601 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
2602 // Loop over global ctors, optimizing them when we can.
2603 for (unsigned i = 0; i != Ctors.size(); ++i) {
2604 Function *F = Ctors[i];
2605 // Found a null terminator in the middle of the list, prune off the rest of
2608 if (i != Ctors.size()-1) {
2615 // We cannot simplify external ctor functions.
2616 if (F->empty()) continue;
2618 // If we can evaluate the ctor at compile time, do.
2619 if (EvaluateStaticConstructor(F, TD)) {
2620 Ctors.erase(Ctors.begin()+i);
2623 ++NumCtorsEvaluated;
2628 if (!MadeChange) return false;
2630 GCL = InstallGlobalCtors(GCL, Ctors);
2634 bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
2635 bool Changed = false;
2637 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
2639 Module::alias_iterator J = I++;
2640 // Aliases without names cannot be referenced outside this module.
2641 if (!J->hasName() && !J->isDeclaration())
2642 J->setLinkage(GlobalValue::InternalLinkage);
2643 // If the aliasee may change at link time, nothing can be done - bail out.
2644 if (J->mayBeOverridden())
2647 Constant *Aliasee = J->getAliasee();
2648 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2649 Target->removeDeadConstantUsers();
2650 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2652 // Make all users of the alias use the aliasee instead.
2653 if (!J->use_empty()) {
2654 J->replaceAllUsesWith(Aliasee);
2655 ++NumAliasesResolved;
2659 // If the alias is externally visible, we may still be able to simplify it.
2660 if (!J->hasLocalLinkage()) {
2661 // If the aliasee has internal linkage, give it the name and linkage
2662 // of the alias, and delete the alias. This turns:
2663 // define internal ... @f(...)
2664 // @a = alias ... @f
2666 // define ... @a(...)
2667 if (!Target->hasLocalLinkage())
2670 // Do not perform the transform if multiple aliases potentially target the
2671 // aliasee. This check also ensures that it is safe to replace the section
2672 // and other attributes of the aliasee with those of the alias.
2676 // Give the aliasee the name, linkage and other attributes of the alias.
2677 Target->takeName(J);
2678 Target->setLinkage(J->getLinkage());
2679 Target->GlobalValue::copyAttributesFrom(J);
2682 // Delete the alias.
2683 M.getAliasList().erase(J);
2684 ++NumAliasesRemoved;
2691 bool GlobalOpt::runOnModule(Module &M) {
2692 bool Changed = false;
2694 // Try to find the llvm.globalctors list.
2695 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2697 bool LocalChange = true;
2698 while (LocalChange) {
2699 LocalChange = false;
2701 // Delete functions that are trivially dead, ccc -> fastcc
2702 LocalChange |= OptimizeFunctions(M);
2704 // Optimize global_ctors list.
2706 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2708 // Optimize non-address-taken globals.
2709 LocalChange |= OptimizeGlobalVars(M);
2711 // Resolve aliases, when possible.
2712 LocalChange |= OptimizeGlobalAliases(M);
2713 Changed |= LocalChange;
2716 // TODO: Move all global ctors functions to the end of the module for code