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;
170 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
171 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
172 if (!GS.HasMultipleAccessingFunctions) {
173 const Function *F = I->getParent()->getParent();
174 if (GS.AccessingFunction == 0)
175 GS.AccessingFunction = F;
176 else if (GS.AccessingFunction != F)
177 GS.HasMultipleAccessingFunctions = true;
179 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
181 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
182 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
183 // Don't allow a store OF the address, only stores TO the address.
184 if (SI->getOperand(0) == V) return true;
186 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
188 // If this is a direct store to the global (i.e., the global is a scalar
189 // value, not an aggregate), keep more specific information about
191 if (GS.StoredType != GlobalStatus::isStored) {
192 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
193 SI->getOperand(1))) {
194 Value *StoredVal = SI->getOperand(0);
195 if (StoredVal == GV->getInitializer()) {
196 if (GS.StoredType < GlobalStatus::isInitializerStored)
197 GS.StoredType = GlobalStatus::isInitializerStored;
198 } else if (isa<LoadInst>(StoredVal) &&
199 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
200 if (GS.StoredType < GlobalStatus::isInitializerStored)
201 GS.StoredType = GlobalStatus::isInitializerStored;
202 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
203 GS.StoredType = GlobalStatus::isStoredOnce;
204 GS.StoredOnceValue = StoredVal;
205 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
206 GS.StoredOnceValue == StoredVal) {
209 GS.StoredType = GlobalStatus::isStored;
212 GS.StoredType = GlobalStatus::isStored;
215 } else if (isa<GetElementPtrInst>(I)) {
216 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
217 } else if (isa<SelectInst>(I)) {
218 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
219 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
220 // PHI nodes we can check just like select or GEP instructions, but we
221 // have to be careful about infinite recursion.
222 if (PHIUsers.insert(PN)) // Not already visited.
223 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
224 GS.HasPHIUser = true;
225 } else if (isa<CmpInst>(I)) {
226 // Nothing to analyse.
227 } else if (isa<MemTransferInst>(I)) {
228 const MemTransferInst *MTI = cast<MemTransferInst>(I);
229 if (MTI->getArgOperand(0) == V)
230 GS.StoredType = GlobalStatus::isStored;
231 if (MTI->getArgOperand(1) == V)
233 } else if (isa<MemSetInst>(I)) {
234 assert(cast<MemSetInst>(I)->getArgOperand(0) == V &&
235 "Memset only takes one pointer!");
236 GS.StoredType = GlobalStatus::isStored;
238 return true; // Any other non-load instruction might take address!
240 } else if (const Constant *C = dyn_cast<Constant>(U)) {
241 GS.HasNonInstructionUser = true;
242 // We might have a dead and dangling constant hanging off of here.
243 if (!SafeToDestroyConstant(C))
246 GS.HasNonInstructionUser = true;
247 // Otherwise must be some other user.
255 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
256 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
258 unsigned IdxV = CI->getZExtValue();
260 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
261 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
262 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
263 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
264 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
265 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
266 } else if (isa<ConstantAggregateZero>(Agg)) {
267 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
268 if (IdxV < STy->getNumElements())
269 return Constant::getNullValue(STy->getElementType(IdxV));
270 } else if (const SequentialType *STy =
271 dyn_cast<SequentialType>(Agg->getType())) {
272 return Constant::getNullValue(STy->getElementType());
274 } else if (isa<UndefValue>(Agg)) {
275 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
276 if (IdxV < STy->getNumElements())
277 return UndefValue::get(STy->getElementType(IdxV));
278 } else if (const SequentialType *STy =
279 dyn_cast<SequentialType>(Agg->getType())) {
280 return UndefValue::get(STy->getElementType());
287 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
288 /// users of the global, cleaning up the obvious ones. This is largely just a
289 /// quick scan over the use list to clean up the easy and obvious cruft. This
290 /// returns true if it made a change.
291 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
292 bool Changed = false;
293 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
296 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
298 // Replace the load with the initializer.
299 LI->replaceAllUsesWith(Init);
300 LI->eraseFromParent();
303 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
304 // Store must be unreachable or storing Init into the global.
305 SI->eraseFromParent();
307 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
308 if (CE->getOpcode() == Instruction::GetElementPtr) {
309 Constant *SubInit = 0;
311 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
312 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
313 } else if (CE->getOpcode() == Instruction::BitCast &&
314 CE->getType()->isPointerTy()) {
315 // Pointer cast, delete any stores and memsets to the global.
316 Changed |= CleanupConstantGlobalUsers(CE, 0);
319 if (CE->use_empty()) {
320 CE->destroyConstant();
323 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
324 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
325 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
326 // and will invalidate our notion of what Init is.
327 Constant *SubInit = 0;
328 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
330 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
331 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
332 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
334 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
336 if (GEP->use_empty()) {
337 GEP->eraseFromParent();
340 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
341 if (MI->getRawDest() == V) {
342 MI->eraseFromParent();
346 } else if (Constant *C = dyn_cast<Constant>(U)) {
347 // If we have a chain of dead constantexprs or other things dangling from
348 // us, and if they are all dead, nuke them without remorse.
349 if (SafeToDestroyConstant(C)) {
350 C->destroyConstant();
351 // This could have invalidated UI, start over from scratch.
352 CleanupConstantGlobalUsers(V, Init);
360 /// isSafeSROAElementUse - Return true if the specified instruction is a safe
361 /// user of a derived expression from a global that we want to SROA.
362 static bool isSafeSROAElementUse(Value *V) {
363 // We might have a dead and dangling constant hanging off of here.
364 if (Constant *C = dyn_cast<Constant>(V))
365 return SafeToDestroyConstant(C);
367 Instruction *I = dyn_cast<Instruction>(V);
368 if (!I) return false;
371 if (isa<LoadInst>(I)) return true;
373 // Stores *to* the pointer are ok.
374 if (StoreInst *SI = dyn_cast<StoreInst>(I))
375 return SI->getOperand(0) != V;
377 // Otherwise, it must be a GEP.
378 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
379 if (GEPI == 0) return false;
381 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
382 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
385 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
387 if (!isSafeSROAElementUse(*I))
393 /// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
394 /// Look at it and its uses and decide whether it is safe to SROA this global.
396 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
397 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
398 if (!isa<GetElementPtrInst>(U) &&
399 (!isa<ConstantExpr>(U) ||
400 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
403 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
404 // don't like < 3 operand CE's, and we don't like non-constant integer
405 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
407 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
408 !cast<Constant>(U->getOperand(1))->isNullValue() ||
409 !isa<ConstantInt>(U->getOperand(2)))
412 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
413 ++GEPI; // Skip over the pointer index.
415 // If this is a use of an array allocation, do a bit more checking for sanity.
416 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
417 uint64_t NumElements = AT->getNumElements();
418 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
420 // Check to make sure that index falls within the array. If not,
421 // something funny is going on, so we won't do the optimization.
423 if (Idx->getZExtValue() >= NumElements)
426 // We cannot scalar repl this level of the array unless any array
427 // sub-indices are in-range constants. In particular, consider:
428 // A[0][i]. We cannot know that the user isn't doing invalid things like
429 // allowing i to index an out-of-range subscript that accesses A[1].
431 // Scalar replacing *just* the outer index of the array is probably not
432 // going to be a win anyway, so just give up.
433 for (++GEPI; // Skip array index.
436 uint64_t NumElements;
437 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
438 NumElements = SubArrayTy->getNumElements();
439 else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
440 NumElements = SubVectorTy->getNumElements();
442 assert((*GEPI)->isStructTy() &&
443 "Indexed GEP type is not array, vector, or struct!");
447 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
448 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
453 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
454 if (!isSafeSROAElementUse(*I))
459 /// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
460 /// is safe for us to perform this transformation.
462 static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
463 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
465 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
472 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
473 /// variable. This opens the door for other optimizations by exposing the
474 /// behavior of the program in a more fine-grained way. We have determined that
475 /// this transformation is safe already. We return the first global variable we
476 /// insert so that the caller can reprocess it.
477 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
478 // Make sure this global only has simple uses that we can SRA.
479 if (!GlobalUsersSafeToSRA(GV))
482 assert(GV->hasLocalLinkage() && !GV->isConstant());
483 Constant *Init = GV->getInitializer();
484 const Type *Ty = Init->getType();
486 std::vector<GlobalVariable*> NewGlobals;
487 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
489 // Get the alignment of the global, either explicit or target-specific.
490 unsigned StartAlignment = GV->getAlignment();
491 if (StartAlignment == 0)
492 StartAlignment = TD.getABITypeAlignment(GV->getType());
494 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
495 NewGlobals.reserve(STy->getNumElements());
496 const StructLayout &Layout = *TD.getStructLayout(STy);
497 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
498 Constant *In = getAggregateConstantElement(Init,
499 ConstantInt::get(Type::getInt32Ty(STy->getContext()), i));
500 assert(In && "Couldn't get element of initializer?");
501 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
502 GlobalVariable::InternalLinkage,
503 In, GV->getName()+"."+Twine(i),
505 GV->getType()->getAddressSpace());
506 Globals.insert(GV, NGV);
507 NewGlobals.push_back(NGV);
509 // Calculate the known alignment of the field. If the original aggregate
510 // had 256 byte alignment for example, something might depend on that:
511 // propagate info to each field.
512 uint64_t FieldOffset = Layout.getElementOffset(i);
513 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
514 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
515 NGV->setAlignment(NewAlign);
517 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
518 unsigned NumElements = 0;
519 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
520 NumElements = ATy->getNumElements();
522 NumElements = cast<VectorType>(STy)->getNumElements();
524 if (NumElements > 16 && GV->hasNUsesOrMore(16))
525 return 0; // It's not worth it.
526 NewGlobals.reserve(NumElements);
528 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
529 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
530 for (unsigned i = 0, e = NumElements; i != e; ++i) {
531 Constant *In = getAggregateConstantElement(Init,
532 ConstantInt::get(Type::getInt32Ty(Init->getContext()), i));
533 assert(In && "Couldn't get element of initializer?");
535 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
536 GlobalVariable::InternalLinkage,
537 In, GV->getName()+"."+Twine(i),
539 GV->getType()->getAddressSpace());
540 Globals.insert(GV, NGV);
541 NewGlobals.push_back(NGV);
543 // Calculate the known alignment of the field. If the original aggregate
544 // had 256 byte alignment for example, something might depend on that:
545 // propagate info to each field.
546 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
547 if (NewAlign > EltAlign)
548 NGV->setAlignment(NewAlign);
552 if (NewGlobals.empty())
555 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
557 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
559 // Loop over all of the uses of the global, replacing the constantexpr geps,
560 // with smaller constantexpr geps or direct references.
561 while (!GV->use_empty()) {
562 User *GEP = GV->use_back();
563 assert(((isa<ConstantExpr>(GEP) &&
564 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
565 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
567 // Ignore the 1th operand, which has to be zero or else the program is quite
568 // broken (undefined). Get the 2nd operand, which is the structure or array
570 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
571 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
573 Value *NewPtr = NewGlobals[Val];
575 // Form a shorter GEP if needed.
576 if (GEP->getNumOperands() > 3) {
577 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
578 SmallVector<Constant*, 8> Idxs;
579 Idxs.push_back(NullInt);
580 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
581 Idxs.push_back(CE->getOperand(i));
582 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
583 &Idxs[0], Idxs.size());
585 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
586 SmallVector<Value*, 8> Idxs;
587 Idxs.push_back(NullInt);
588 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
589 Idxs.push_back(GEPI->getOperand(i));
590 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
591 GEPI->getName()+"."+Twine(Val),GEPI);
594 GEP->replaceAllUsesWith(NewPtr);
596 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
597 GEPI->eraseFromParent();
599 cast<ConstantExpr>(GEP)->destroyConstant();
602 // Delete the old global, now that it is dead.
606 // Loop over the new globals array deleting any globals that are obviously
607 // dead. This can arise due to scalarization of a structure or an array that
608 // has elements that are dead.
609 unsigned FirstGlobal = 0;
610 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
611 if (NewGlobals[i]->use_empty()) {
612 Globals.erase(NewGlobals[i]);
613 if (FirstGlobal == i) ++FirstGlobal;
616 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
619 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
620 /// value will trap if the value is dynamically null. PHIs keeps track of any
621 /// phi nodes we've seen to avoid reprocessing them.
622 static bool AllUsesOfValueWillTrapIfNull(const Value *V,
623 SmallPtrSet<const PHINode*, 8> &PHIs) {
624 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
628 if (isa<LoadInst>(U)) {
630 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
631 if (SI->getOperand(0) == V) {
632 //cerr << "NONTRAPPING USE: " << *U;
633 return false; // Storing the value.
635 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
636 if (CI->getCalledValue() != V) {
637 //cerr << "NONTRAPPING USE: " << *U;
638 return false; // Not calling the ptr
640 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
641 if (II->getCalledValue() != V) {
642 //cerr << "NONTRAPPING USE: " << *U;
643 return false; // Not calling the ptr
645 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
646 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
647 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
648 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
649 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
650 // If we've already seen this phi node, ignore it, it has already been
652 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
654 } else if (isa<ICmpInst>(U) &&
655 isa<ConstantPointerNull>(UI->getOperand(1))) {
656 // Ignore icmp X, null
658 //cerr << "NONTRAPPING USE: " << *U;
665 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
666 /// from GV will trap if the loaded value is null. Note that this also permits
667 /// comparisons of the loaded value against null, as a special case.
668 static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
669 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
673 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
674 SmallPtrSet<const PHINode*, 8> PHIs;
675 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
677 } else if (isa<StoreInst>(U)) {
678 // Ignore stores to the global.
680 // We don't know or understand this user, bail out.
681 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
688 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
689 bool Changed = false;
690 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
691 Instruction *I = cast<Instruction>(*UI++);
692 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
693 LI->setOperand(0, NewV);
695 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
696 if (SI->getOperand(1) == V) {
697 SI->setOperand(1, NewV);
700 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
702 if (CS.getCalledValue() == V) {
703 // Calling through the pointer! Turn into a direct call, but be careful
704 // that the pointer is not also being passed as an argument.
705 CS.setCalledFunction(NewV);
707 bool PassedAsArg = false;
708 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
709 if (CS.getArgument(i) == V) {
711 CS.setArgument(i, NewV);
715 // Being passed as an argument also. Be careful to not invalidate UI!
719 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
720 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
721 ConstantExpr::getCast(CI->getOpcode(),
722 NewV, CI->getType()));
723 if (CI->use_empty()) {
725 CI->eraseFromParent();
727 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
728 // Should handle GEP here.
729 SmallVector<Constant*, 8> Idxs;
730 Idxs.reserve(GEPI->getNumOperands()-1);
731 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
733 if (Constant *C = dyn_cast<Constant>(*i))
737 if (Idxs.size() == GEPI->getNumOperands()-1)
738 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
739 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
741 if (GEPI->use_empty()) {
743 GEPI->eraseFromParent();
752 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
753 /// value stored into it. If there are uses of the loaded value that would trap
754 /// if the loaded value is dynamically null, then we know that they cannot be
755 /// reachable with a null optimize away the load.
756 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
757 bool Changed = false;
759 // Keep track of whether we are able to remove all the uses of the global
760 // other than the store that defines it.
761 bool AllNonStoreUsesGone = true;
763 // Replace all uses of loads with uses of uses of the stored value.
764 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
765 User *GlobalUser = *GUI++;
766 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
767 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
768 // If we were able to delete all uses of the loads
769 if (LI->use_empty()) {
770 LI->eraseFromParent();
773 AllNonStoreUsesGone = false;
775 } else if (isa<StoreInst>(GlobalUser)) {
776 // Ignore the store that stores "LV" to the global.
777 assert(GlobalUser->getOperand(1) == GV &&
778 "Must be storing *to* the global");
780 AllNonStoreUsesGone = false;
782 // If we get here we could have other crazy uses that are transitively
784 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
785 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
790 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
794 // If we nuked all of the loads, then none of the stores are needed either,
795 // nor is the global.
796 if (AllNonStoreUsesGone) {
797 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
798 CleanupConstantGlobalUsers(GV, 0);
799 if (GV->use_empty()) {
800 GV->eraseFromParent();
808 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
809 /// instructions that are foldable.
810 static void ConstantPropUsersOf(Value *V) {
811 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
812 if (Instruction *I = dyn_cast<Instruction>(*UI++))
813 if (Constant *NewC = ConstantFoldInstruction(I)) {
814 I->replaceAllUsesWith(NewC);
816 // Advance UI to the next non-I use to avoid invalidating it!
817 // Instructions could multiply use V.
818 while (UI != E && *UI == I)
820 I->eraseFromParent();
824 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
825 /// variable, and transforms the program as if it always contained the result of
826 /// the specified malloc. Because it is always the result of the specified
827 /// malloc, there is no reason to actually DO the malloc. Instead, turn the
828 /// malloc into a global, and any loads of GV as uses of the new global.
829 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
832 ConstantInt *NElements,
834 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
836 const Type *GlobalType;
837 if (NElements->getZExtValue() == 1)
838 GlobalType = AllocTy;
840 // If we have an array allocation, the global variable is of an array.
841 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
843 // Create the new global variable. The contents of the malloc'd memory is
844 // undefined, so initialize with an undef value.
845 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
847 GlobalValue::InternalLinkage,
848 UndefValue::get(GlobalType),
849 GV->getName()+".body",
851 GV->isThreadLocal());
853 // If there are bitcast users of the malloc (which is typical, usually we have
854 // a malloc + bitcast) then replace them with uses of the new global. Update
855 // other users to use the global as well.
856 BitCastInst *TheBC = 0;
857 while (!CI->use_empty()) {
858 Instruction *User = cast<Instruction>(CI->use_back());
859 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
860 if (BCI->getType() == NewGV->getType()) {
861 BCI->replaceAllUsesWith(NewGV);
862 BCI->eraseFromParent();
864 BCI->setOperand(0, NewGV);
868 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
869 User->replaceUsesOfWith(CI, TheBC);
873 Constant *RepValue = NewGV;
874 if (NewGV->getType() != GV->getType()->getElementType())
875 RepValue = ConstantExpr::getBitCast(RepValue,
876 GV->getType()->getElementType());
878 // If there is a comparison against null, we will insert a global bool to
879 // keep track of whether the global was initialized yet or not.
880 GlobalVariable *InitBool =
881 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
882 GlobalValue::InternalLinkage,
883 ConstantInt::getFalse(GV->getContext()),
884 GV->getName()+".init", GV->isThreadLocal());
885 bool InitBoolUsed = false;
887 // Loop over all uses of GV, processing them in turn.
888 while (!GV->use_empty()) {
889 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
890 // The global is initialized when the store to it occurs.
891 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
892 SI->eraseFromParent();
896 LoadInst *LI = cast<LoadInst>(GV->use_back());
897 while (!LI->use_empty()) {
898 Use &LoadUse = LI->use_begin().getUse();
899 if (!isa<ICmpInst>(LoadUse.getUser())) {
904 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
905 // Replace the cmp X, 0 with a use of the bool value.
906 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
908 switch (ICI->getPredicate()) {
909 default: llvm_unreachable("Unknown ICmp Predicate!");
910 case ICmpInst::ICMP_ULT:
911 case ICmpInst::ICMP_SLT: // X < null -> always false
912 LV = ConstantInt::getFalse(GV->getContext());
914 case ICmpInst::ICMP_ULE:
915 case ICmpInst::ICMP_SLE:
916 case ICmpInst::ICMP_EQ:
917 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
919 case ICmpInst::ICMP_NE:
920 case ICmpInst::ICMP_UGE:
921 case ICmpInst::ICMP_SGE:
922 case ICmpInst::ICMP_UGT:
923 case ICmpInst::ICMP_SGT:
926 ICI->replaceAllUsesWith(LV);
927 ICI->eraseFromParent();
929 LI->eraseFromParent();
932 // If the initialization boolean was used, insert it, otherwise delete it.
934 while (!InitBool->use_empty()) // Delete initializations
935 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
938 GV->getParent()->getGlobalList().insert(GV, InitBool);
940 // Now the GV is dead, nuke it and the malloc..
941 GV->eraseFromParent();
942 CI->eraseFromParent();
944 // To further other optimizations, loop over all users of NewGV and try to
945 // constant prop them. This will promote GEP instructions with constant
946 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
947 ConstantPropUsersOf(NewGV);
948 if (RepValue != NewGV)
949 ConstantPropUsersOf(RepValue);
954 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
955 /// to make sure that there are no complex uses of V. We permit simple things
956 /// like dereferencing the pointer, but not storing through the address, unless
957 /// it is to the specified global.
958 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
959 const GlobalVariable *GV,
960 SmallPtrSet<const PHINode*, 8> &PHIs) {
961 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
963 const Instruction *Inst = cast<Instruction>(*UI);
965 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
966 continue; // Fine, ignore.
969 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
970 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
971 return false; // Storing the pointer itself... bad.
972 continue; // Otherwise, storing through it, or storing into GV... fine.
975 // Must index into the array and into the struct.
976 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
977 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
982 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
983 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
986 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
991 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
992 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1002 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1003 /// somewhere. Transform all uses of the allocation into loads from the
1004 /// global and uses of the resultant pointer. Further, delete the store into
1005 /// GV. This assumes that these value pass the
1006 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
1007 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
1008 GlobalVariable *GV) {
1009 while (!Alloc->use_empty()) {
1010 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1011 Instruction *InsertPt = U;
1012 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1013 // If this is the store of the allocation into the global, remove it.
1014 if (SI->getOperand(1) == GV) {
1015 SI->eraseFromParent();
1018 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1019 // Insert the load in the corresponding predecessor, not right before the
1021 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
1022 } else if (isa<BitCastInst>(U)) {
1023 // Must be bitcast between the malloc and store to initialize the global.
1024 ReplaceUsesOfMallocWithGlobal(U, GV);
1025 U->eraseFromParent();
1027 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1028 // If this is a "GEP bitcast" and the user is a store to the global, then
1029 // just process it as a bitcast.
1030 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1031 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1032 if (SI->getOperand(1) == GV) {
1033 // Must be bitcast GEP between the malloc and store to initialize
1035 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1036 GEPI->eraseFromParent();
1041 // Insert a load from the global, and use it instead of the malloc.
1042 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
1043 U->replaceUsesOfWith(Alloc, NL);
1047 /// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1048 /// of a load) are simple enough to perform heap SRA on. This permits GEP's
1049 /// that index through the array and struct field, icmps of null, and PHIs.
1050 static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
1051 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1052 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
1053 // We permit two users of the load: setcc comparing against the null
1054 // pointer, and a getelementptr of a specific form.
1055 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1057 const Instruction *User = cast<Instruction>(*UI);
1059 // Comparison against null is ok.
1060 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1061 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1066 // getelementptr is also ok, but only a simple form.
1067 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1068 // Must index into the array and into the struct.
1069 if (GEPI->getNumOperands() < 3)
1072 // Otherwise the GEP is ok.
1076 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
1077 if (!LoadUsingPHIsPerLoad.insert(PN))
1078 // This means some phi nodes are dependent on each other.
1079 // Avoid infinite looping!
1081 if (!LoadUsingPHIs.insert(PN))
1082 // If we have already analyzed this PHI, then it is safe.
1085 // Make sure all uses of the PHI are simple enough to transform.
1086 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1087 LoadUsingPHIs, LoadUsingPHIsPerLoad))
1093 // Otherwise we don't know what this is, not ok.
1101 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1102 /// GV are simple enough to perform HeapSRA, return true.
1103 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
1104 Instruction *StoredVal) {
1105 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1106 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
1107 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1109 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1110 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1111 LoadUsingPHIsPerLoad))
1113 LoadUsingPHIsPerLoad.clear();
1116 // If we reach here, we know that all uses of the loads and transitive uses
1117 // (through PHI nodes) are simple enough to transform. However, we don't know
1118 // that all inputs the to the PHI nodes are in the same equivalence sets.
1119 // Check to verify that all operands of the PHIs are either PHIS that can be
1120 // transformed, loads from GV, or MI itself.
1121 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1122 , E = LoadUsingPHIs.end(); I != E; ++I) {
1123 const PHINode *PN = *I;
1124 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1125 Value *InVal = PN->getIncomingValue(op);
1127 // PHI of the stored value itself is ok.
1128 if (InVal == StoredVal) continue;
1130 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1131 // One of the PHIs in our set is (optimistically) ok.
1132 if (LoadUsingPHIs.count(InPN))
1137 // Load from GV is ok.
1138 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
1139 if (LI->getOperand(0) == GV)
1144 // Anything else is rejected.
1152 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1153 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1154 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1155 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1157 if (FieldNo >= FieldVals.size())
1158 FieldVals.resize(FieldNo+1);
1160 // If we already have this value, just reuse the previously scalarized
1162 if (Value *FieldVal = FieldVals[FieldNo])
1165 // Depending on what instruction this is, we have several cases.
1167 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1168 // This is a scalarized version of the load from the global. Just create
1169 // a new Load of the scalarized global.
1170 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1171 InsertedScalarizedValues,
1173 LI->getName()+".f"+Twine(FieldNo), LI);
1174 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1175 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1177 const StructType *ST =
1178 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1181 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1182 PN->getName()+".f"+Twine(FieldNo), PN);
1183 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1185 llvm_unreachable("Unknown usable value");
1189 return FieldVals[FieldNo] = Result;
1192 /// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1193 /// the load, rewrite the derived value to use the HeapSRoA'd load.
1194 static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1195 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1196 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1197 // If this is a comparison against null, handle it.
1198 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1199 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1200 // If we have a setcc of the loaded pointer, we can use a setcc of any
1202 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1203 InsertedScalarizedValues, PHIsToRewrite);
1205 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
1206 Constant::getNullValue(NPtr->getType()),
1208 SCI->replaceAllUsesWith(New);
1209 SCI->eraseFromParent();
1213 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
1214 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1215 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1216 && "Unexpected GEPI!");
1218 // Load the pointer for this field.
1219 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1220 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1221 InsertedScalarizedValues, PHIsToRewrite);
1223 // Create the new GEP idx vector.
1224 SmallVector<Value*, 8> GEPIdx;
1225 GEPIdx.push_back(GEPI->getOperand(1));
1226 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1228 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1229 GEPIdx.begin(), GEPIdx.end(),
1230 GEPI->getName(), GEPI);
1231 GEPI->replaceAllUsesWith(NGEPI);
1232 GEPI->eraseFromParent();
1236 // Recursively transform the users of PHI nodes. This will lazily create the
1237 // PHIs that are needed for individual elements. Keep track of what PHIs we
1238 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1239 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1240 // already been seen first by another load, so its uses have already been
1242 PHINode *PN = cast<PHINode>(LoadUser);
1244 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1245 tie(InsertPos, Inserted) =
1246 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1247 if (!Inserted) return;
1249 // If this is the first time we've seen this PHI, recursively process all
1251 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1252 Instruction *User = cast<Instruction>(*UI++);
1253 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1257 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1258 /// is a value loaded from the global. Eliminate all uses of Ptr, making them
1259 /// use FieldGlobals instead. All uses of loaded values satisfy
1260 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
1261 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
1262 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1263 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1264 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
1266 Instruction *User = cast<Instruction>(*UI++);
1267 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1270 if (Load->use_empty()) {
1271 Load->eraseFromParent();
1272 InsertedScalarizedValues.erase(Load);
1276 /// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1277 /// it up into multiple allocations of arrays of the fields.
1278 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1279 Value* NElems, TargetData *TD) {
1280 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
1281 const Type* MAT = getMallocAllocatedType(CI);
1282 const StructType *STy = cast<StructType>(MAT);
1284 // There is guaranteed to be at least one use of the malloc (storing
1285 // it into GV). If there are other uses, change them to be uses of
1286 // the global to simplify later code. This also deletes the store
1288 ReplaceUsesOfMallocWithGlobal(CI, GV);
1290 // Okay, at this point, there are no users of the malloc. Insert N
1291 // new mallocs at the same place as CI, and N globals.
1292 std::vector<Value*> FieldGlobals;
1293 std::vector<Value*> FieldMallocs;
1295 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1296 const Type *FieldTy = STy->getElementType(FieldNo);
1297 const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1299 GlobalVariable *NGV =
1300 new GlobalVariable(*GV->getParent(),
1301 PFieldTy, false, GlobalValue::InternalLinkage,
1302 Constant::getNullValue(PFieldTy),
1303 GV->getName() + ".f" + Twine(FieldNo), GV,
1304 GV->isThreadLocal());
1305 FieldGlobals.push_back(NGV);
1307 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
1308 if (const StructType *ST = dyn_cast<StructType>(FieldTy))
1309 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
1310 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1311 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1312 ConstantInt::get(IntPtrTy, TypeSize),
1314 CI->getName() + ".f" + Twine(FieldNo));
1315 FieldMallocs.push_back(NMI);
1316 new StoreInst(NMI, NGV, CI);
1319 // The tricky aspect of this transformation is handling the case when malloc
1320 // fails. In the original code, malloc failing would set the result pointer
1321 // of malloc to null. In this case, some mallocs could succeed and others
1322 // could fail. As such, we emit code that looks like this:
1323 // F0 = malloc(field0)
1324 // F1 = malloc(field1)
1325 // F2 = malloc(field2)
1326 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1327 // if (F0) { free(F0); F0 = 0; }
1328 // if (F1) { free(F1); F1 = 0; }
1329 // if (F2) { free(F2); F2 = 0; }
1331 // The malloc can also fail if its argument is too large.
1332 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1333 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
1334 ConstantZero, "isneg");
1335 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1336 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1337 Constant::getNullValue(FieldMallocs[i]->getType()),
1339 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
1342 // Split the basic block at the old malloc.
1343 BasicBlock *OrigBB = CI->getParent();
1344 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
1346 // Create the block to check the first condition. Put all these blocks at the
1347 // end of the function as they are unlikely to be executed.
1348 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1350 OrigBB->getParent());
1352 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1353 // branch on RunningOr.
1354 OrigBB->getTerminator()->eraseFromParent();
1355 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1357 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1358 // pointer, because some may be null while others are not.
1359 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1360 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1361 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1362 Constant::getNullValue(GVVal->getType()),
1364 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
1365 OrigBB->getParent());
1366 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
1367 OrigBB->getParent());
1368 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1371 // Fill in FreeBlock.
1372 CallInst::CreateFree(GVVal, BI);
1373 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1375 BranchInst::Create(NextBlock, FreeBlock);
1377 NullPtrBlock = NextBlock;
1380 BranchInst::Create(ContBB, NullPtrBlock);
1382 // CI is no longer needed, remove it.
1383 CI->eraseFromParent();
1385 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1386 /// update all uses of the load, keep track of what scalarized loads are
1387 /// inserted for a given load.
1388 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1389 InsertedScalarizedValues[GV] = FieldGlobals;
1391 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1393 // Okay, the malloc site is completely handled. All of the uses of GV are now
1394 // loads, and all uses of those loads are simple. Rewrite them to use loads
1395 // of the per-field globals instead.
1396 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1397 Instruction *User = cast<Instruction>(*UI++);
1399 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1400 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
1404 // Must be a store of null.
1405 StoreInst *SI = cast<StoreInst>(User);
1406 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1407 "Unexpected heap-sra user!");
1409 // Insert a store of null into each global.
1410 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1411 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1412 Constant *Null = Constant::getNullValue(PT->getElementType());
1413 new StoreInst(Null, FieldGlobals[i], SI);
1415 // Erase the original store.
1416 SI->eraseFromParent();
1419 // While we have PHIs that are interesting to rewrite, do it.
1420 while (!PHIsToRewrite.empty()) {
1421 PHINode *PN = PHIsToRewrite.back().first;
1422 unsigned FieldNo = PHIsToRewrite.back().second;
1423 PHIsToRewrite.pop_back();
1424 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1425 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1427 // Add all the incoming values. This can materialize more phis.
1428 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1429 Value *InVal = PN->getIncomingValue(i);
1430 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1432 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1436 // Drop all inter-phi links and any loads that made it this far.
1437 for (DenseMap<Value*, std::vector<Value*> >::iterator
1438 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1440 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1441 PN->dropAllReferences();
1442 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1443 LI->dropAllReferences();
1446 // Delete all the phis and loads now that inter-references are dead.
1447 for (DenseMap<Value*, std::vector<Value*> >::iterator
1448 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1450 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1451 PN->eraseFromParent();
1452 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1453 LI->eraseFromParent();
1456 // The old global is now dead, remove it.
1457 GV->eraseFromParent();
1460 return cast<GlobalVariable>(FieldGlobals[0]);
1463 /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1464 /// pointer global variable with a single value stored it that is a malloc or
1466 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1468 const Type *AllocTy,
1469 Module::global_iterator &GVI,
1474 // If this is a malloc of an abstract type, don't touch it.
1475 if (!AllocTy->isSized())
1478 // We can't optimize this global unless all uses of it are *known* to be
1479 // of the malloc value, not of the null initializer value (consider a use
1480 // that compares the global's value against zero to see if the malloc has
1481 // been reached). To do this, we check to see if all uses of the global
1482 // would trap if the global were null: this proves that they must all
1483 // happen after the malloc.
1484 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1487 // We can't optimize this if the malloc itself is used in a complex way,
1488 // for example, being stored into multiple globals. This allows the
1489 // malloc to be stored into the specified global, loaded setcc'd, and
1490 // GEP'd. These are all things we could transform to using the global
1492 SmallPtrSet<const PHINode*, 8> PHIs;
1493 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1496 // If we have a global that is only initialized with a fixed size malloc,
1497 // transform the program to use global memory instead of malloc'd memory.
1498 // This eliminates dynamic allocation, avoids an indirection accessing the
1499 // data, and exposes the resultant global to further GlobalOpt.
1500 // We cannot optimize the malloc if we cannot determine malloc array size.
1501 Value *NElems = getMallocArraySize(CI, TD, true);
1505 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1506 // Restrict this transformation to only working on small allocations
1507 // (2048 bytes currently), as we don't want to introduce a 16M global or
1509 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1510 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
1514 // If the allocation is an array of structures, consider transforming this
1515 // into multiple malloc'd arrays, one for each field. This is basically
1516 // SRoA for malloc'd memory.
1518 // If this is an allocation of a fixed size array of structs, analyze as a
1519 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1520 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
1521 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1522 AllocTy = AT->getElementType();
1524 const StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
1528 // This the structure has an unreasonable number of fields, leave it
1530 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1531 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1533 // If this is a fixed size array, transform the Malloc to be an alloc of
1534 // structs. malloc [100 x struct],1 -> malloc struct, 100
1535 if (const ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1536 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1537 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1538 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1539 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1540 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1541 AllocSize, NumElements,
1543 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1544 CI->replaceAllUsesWith(Cast);
1545 CI->eraseFromParent();
1546 CI = dyn_cast<BitCastInst>(Malloc) ?
1547 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
1550 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
1557 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1558 // that only one value (besides its initializer) is ever stored to the global.
1559 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1560 Module::global_iterator &GVI,
1562 // Ignore no-op GEPs and bitcasts.
1563 StoredOnceVal = StoredOnceVal->stripPointerCasts();
1565 // If we are dealing with a pointer global that is initialized to null and
1566 // only has one (non-null) value stored into it, then we can optimize any
1567 // users of the loaded value (often calls and loads) that would trap if the
1569 if (GV->getInitializer()->getType()->isPointerTy() &&
1570 GV->getInitializer()->isNullValue()) {
1571 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1572 if (GV->getInitializer()->getType() != SOVC->getType())
1574 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1576 // Optimize away any trapping uses of the loaded value.
1577 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
1579 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
1580 const Type* MallocType = getMallocAllocatedType(CI);
1581 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
1590 /// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1591 /// two values ever stored into GV are its initializer and OtherVal. See if we
1592 /// can shrink the global into a boolean and select between the two values
1593 /// whenever it is used. This exposes the values to other scalar optimizations.
1594 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1595 const Type *GVElType = GV->getType()->getElementType();
1597 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1598 // an FP value, pointer or vector, don't do this optimization because a select
1599 // between them is very expensive and unlikely to lead to later
1600 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1601 // where v1 and v2 both require constant pool loads, a big loss.
1602 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
1603 GVElType->isFloatingPointTy() ||
1604 GVElType->isPointerTy() || GVElType->isVectorTy())
1607 // Walk the use list of the global seeing if all the uses are load or store.
1608 // If there is anything else, bail out.
1609 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1611 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
1615 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
1617 // Create the new global, initializing it to false.
1618 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1620 GlobalValue::InternalLinkage,
1621 ConstantInt::getFalse(GV->getContext()),
1623 GV->isThreadLocal());
1624 GV->getParent()->getGlobalList().insert(GV, NewGV);
1626 Constant *InitVal = GV->getInitializer();
1627 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
1628 "No reason to shrink to bool!");
1630 // If initialized to zero and storing one into the global, we can use a cast
1631 // instead of a select to synthesize the desired value.
1632 bool IsOneZero = false;
1633 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1634 IsOneZero = InitVal->isNullValue() && CI->isOne();
1636 while (!GV->use_empty()) {
1637 Instruction *UI = cast<Instruction>(GV->use_back());
1638 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1639 // Change the store into a boolean store.
1640 bool StoringOther = SI->getOperand(0) == OtherVal;
1641 // Only do this if we weren't storing a loaded value.
1643 if (StoringOther || SI->getOperand(0) == InitVal)
1644 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1647 // Otherwise, we are storing a previously loaded copy. To do this,
1648 // change the copy from copying the original value to just copying the
1650 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1652 // If we've already replaced the input, StoredVal will be a cast or
1653 // select instruction. If not, it will be a load of the original
1655 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1656 assert(LI->getOperand(0) == GV && "Not a copy!");
1657 // Insert a new load, to preserve the saved value.
1658 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1660 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1661 "This is not a form that we understand!");
1662 StoreVal = StoredVal->getOperand(0);
1663 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1666 new StoreInst(StoreVal, NewGV, SI);
1668 // Change the load into a load of bool then a select.
1669 LoadInst *LI = cast<LoadInst>(UI);
1670 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1673 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1675 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1677 LI->replaceAllUsesWith(NSI);
1679 UI->eraseFromParent();
1682 GV->eraseFromParent();
1687 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1688 /// it if possible. If we make a change, return true.
1689 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1690 Module::global_iterator &GVI) {
1691 SmallPtrSet<const PHINode*, 16> PHIUsers;
1693 GV->removeDeadConstantUsers();
1695 if (GV->use_empty()) {
1696 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
1697 GV->eraseFromParent();
1702 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1704 DEBUG(dbgs() << "Global: " << *GV);
1705 DEBUG(dbgs() << " isLoaded = " << GS.isLoaded << "\n");
1706 DEBUG(dbgs() << " StoredType = ");
1707 switch (GS.StoredType) {
1708 case GlobalStatus::NotStored: DEBUG(dbgs() << "NEVER STORED\n"); break;
1709 case GlobalStatus::isInitializerStored: DEBUG(dbgs() << "INIT STORED\n");
1711 case GlobalStatus::isStoredOnce: DEBUG(dbgs() << "STORED ONCE\n"); break;
1712 case GlobalStatus::isStored: DEBUG(dbgs() << "stored\n"); break;
1714 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1715 DEBUG(dbgs() << " StoredOnceValue = " << *GS.StoredOnceValue << "\n");
1716 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1717 DEBUG(dbgs() << " AccessingFunction = "
1718 << GS.AccessingFunction->getName() << "\n");
1719 DEBUG(dbgs() << " HasMultipleAccessingFunctions = "
1720 << GS.HasMultipleAccessingFunctions << "\n");
1721 DEBUG(dbgs() << " HasNonInstructionUser = "
1722 << GS.HasNonInstructionUser<<"\n");
1723 DEBUG(dbgs() << "\n");
1726 // If this is a first class global and has only one accessing function
1727 // and this function is main (which we know is not recursive we can make
1728 // this global a local variable) we replace the global with a local alloca
1729 // in this function.
1731 // NOTE: It doesn't make sense to promote non single-value types since we
1732 // are just replacing static memory to stack memory.
1734 // If the global is in different address space, don't bring it to stack.
1735 if (!GS.HasMultipleAccessingFunctions &&
1736 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1737 GV->getType()->getElementType()->isSingleValueType() &&
1738 GS.AccessingFunction->getName() == "main" &&
1739 GS.AccessingFunction->hasExternalLinkage() &&
1740 GV->getType()->getAddressSpace() == 0) {
1741 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1742 Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1743 ->getEntryBlock().begin());
1744 const Type* ElemTy = GV->getType()->getElementType();
1745 // FIXME: Pass Global's alignment when globals have alignment
1746 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1747 if (!isa<UndefValue>(GV->getInitializer()))
1748 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1750 GV->replaceAllUsesWith(Alloca);
1751 GV->eraseFromParent();
1756 // If the global is never loaded (but may be stored to), it is dead.
1759 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1761 // Delete any stores we can find to the global. We may not be able to
1762 // make it completely dead though.
1763 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1765 // If the global is dead now, delete it.
1766 if (GV->use_empty()) {
1767 GV->eraseFromParent();
1773 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1774 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1775 GV->setConstant(true);
1777 // Clean up any obviously simplifiable users now.
1778 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1780 // If the global is dead now, just nuke it.
1781 if (GV->use_empty()) {
1782 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1783 << "all users and delete global!\n");
1784 GV->eraseFromParent();
1790 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1791 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1792 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1793 GVI = FirstNewGV; // Don't skip the newly produced globals!
1796 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1797 // If the initial value for the global was an undef value, and if only
1798 // one other value was stored into it, we can just change the
1799 // initializer to be the stored value, then delete all stores to the
1800 // global. This allows us to mark it constant.
1801 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1802 if (isa<UndefValue>(GV->getInitializer())) {
1803 // Change the initial value here.
1804 GV->setInitializer(SOVConstant);
1806 // Clean up any obviously simplifiable users now.
1807 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1809 if (GV->use_empty()) {
1810 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1811 << "simplify all users and delete global!\n");
1812 GV->eraseFromParent();
1821 // Try to optimize globals based on the knowledge that only one value
1822 // (besides its initializer) is ever stored to the global.
1823 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1824 getAnalysisIfAvailable<TargetData>()))
1827 // Otherwise, if the global was not a boolean, we can shrink it to be a
1829 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1830 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1839 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1840 /// function, changing them to FastCC.
1841 static void ChangeCalleesToFastCall(Function *F) {
1842 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1843 CallSite User(cast<Instruction>(*UI));
1844 User.setCallingConv(CallingConv::Fast);
1848 static AttrListPtr StripNest(const AttrListPtr &Attrs) {
1849 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1850 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
1853 // There can be only one.
1854 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
1860 static void RemoveNestAttribute(Function *F) {
1861 F->setAttributes(StripNest(F->getAttributes()));
1862 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1863 CallSite User(cast<Instruction>(*UI));
1864 User.setAttributes(StripNest(User.getAttributes()));
1868 bool GlobalOpt::OptimizeFunctions(Module &M) {
1869 bool Changed = false;
1870 // Optimize functions.
1871 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1873 // Functions without names cannot be referenced outside this module.
1874 if (!F->hasName() && !F->isDeclaration())
1875 F->setLinkage(GlobalValue::InternalLinkage);
1876 F->removeDeadConstantUsers();
1877 if (F->use_empty() && (F->hasLocalLinkage() || F->hasLinkOnceLinkage())) {
1878 F->eraseFromParent();
1881 } else if (F->hasLocalLinkage()) {
1882 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1883 !F->hasAddressTaken()) {
1884 // If this function has C calling conventions, is not a varargs
1885 // function, and is only called directly, promote it to use the Fast
1886 // calling convention.
1887 F->setCallingConv(CallingConv::Fast);
1888 ChangeCalleesToFastCall(F);
1893 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
1894 !F->hasAddressTaken()) {
1895 // The function is not used by a trampoline intrinsic, so it is safe
1896 // to remove the 'nest' attribute.
1897 RemoveNestAttribute(F);
1906 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1907 bool Changed = false;
1908 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1910 GlobalVariable *GV = GVI++;
1911 // Global variables without names cannot be referenced outside this module.
1912 if (!GV->hasName() && !GV->isDeclaration())
1913 GV->setLinkage(GlobalValue::InternalLinkage);
1914 // Simplify the initializer.
1915 if (GV->hasInitializer())
1916 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
1917 TargetData *TD = getAnalysisIfAvailable<TargetData>();
1918 Constant *New = ConstantFoldConstantExpression(CE, TD);
1919 if (New && New != CE)
1920 GV->setInitializer(New);
1922 // Do more involved optimizations if the global is internal.
1923 if (!GV->isConstant() && GV->hasLocalLinkage() &&
1924 GV->hasInitializer())
1925 Changed |= ProcessInternalGlobal(GV, GVI);
1930 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1931 /// initializers have an init priority of 65535.
1932 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1933 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1934 if (GV == 0) return 0;
1936 // Found it, verify it's an array of { int, void()* }.
1937 const ArrayType *ATy =dyn_cast<ArrayType>(GV->getType()->getElementType());
1939 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1940 if (!STy || STy->getNumElements() != 2 ||
1941 !STy->getElementType(0)->isIntegerTy(32)) return 0;
1942 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1943 if (!PFTy) return 0;
1944 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1945 if (!FTy || !FTy->getReturnType()->isVoidTy() ||
1946 FTy->isVarArg() || FTy->getNumParams() != 0)
1949 // Verify that the initializer is simple enough for us to handle. We are
1950 // only allowed to optimize the initializer if it is unique.
1951 if (!GV->hasUniqueInitializer()) return 0;
1953 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1956 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1957 ConstantStruct *CS = dyn_cast<ConstantStruct>(*i);
1958 if (CS == 0) return 0;
1960 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1963 // Must have a function or null ptr.
1964 if (!isa<Function>(CS->getOperand(1)))
1967 // Init priority must be standard.
1968 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1969 if (!CI || CI->getZExtValue() != 65535)
1976 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1977 /// return a list of the functions and null terminator as a vector.
1978 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1979 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1980 std::vector<Function*> Result;
1981 Result.reserve(CA->getNumOperands());
1982 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1983 ConstantStruct *CS = cast<ConstantStruct>(*i);
1984 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1989 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1990 /// specified array, returning the new global to use.
1991 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1992 const std::vector<Function*> &Ctors) {
1993 // If we made a change, reassemble the initializer list.
1994 std::vector<Constant*> CSVals;
1995 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(GCL->getContext()),65535));
1996 CSVals.push_back(0);
1998 // Create the new init list.
1999 std::vector<Constant*> CAList;
2000 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
2002 CSVals[1] = Ctors[i];
2004 const Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
2006 const PointerType *PFTy = PointerType::getUnqual(FTy);
2007 CSVals[1] = Constant::getNullValue(PFTy);
2008 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
2011 CAList.push_back(ConstantStruct::get(GCL->getContext(), CSVals, false));
2014 // Create the array initializer.
2015 const Type *StructTy =
2016 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
2017 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
2018 CAList.size()), CAList);
2020 // If we didn't change the number of elements, don't create a new GV.
2021 if (CA->getType() == GCL->getInitializer()->getType()) {
2022 GCL->setInitializer(CA);
2026 // Create the new global and insert it next to the existing list.
2027 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
2028 GCL->getLinkage(), CA, "",
2029 GCL->isThreadLocal());
2030 GCL->getParent()->getGlobalList().insert(GCL, NGV);
2033 // Nuke the old list, replacing any uses with the new one.
2034 if (!GCL->use_empty()) {
2036 if (V->getType() != GCL->getType())
2037 V = ConstantExpr::getBitCast(V, GCL->getType());
2038 GCL->replaceAllUsesWith(V);
2040 GCL->eraseFromParent();
2049 static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues, Value *V) {
2050 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2051 Constant *R = ComputedValues[V];
2052 assert(R && "Reference to an uncomputed value!");
2057 isSimpleEnoughValueToCommit(Constant *C,
2058 SmallPtrSet<Constant*, 8> &SimpleConstants);
2061 /// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2062 /// handled by the code generator. We don't want to generate something like:
2063 /// void *X = &X/42;
2064 /// because the code generator doesn't have a relocation that can handle that.
2066 /// This function should be called if C was not found (but just got inserted)
2067 /// in SimpleConstants to avoid having to rescan the same constants all the
2069 static bool isSimpleEnoughValueToCommitHelper(Constant *C,
2070 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2071 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2073 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2074 isa<GlobalValue>(C))
2077 // Aggregate values are safe if all their elements are.
2078 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2079 isa<ConstantVector>(C)) {
2080 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2081 Constant *Op = cast<Constant>(C->getOperand(i));
2082 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants))
2088 // We don't know exactly what relocations are allowed in constant expressions,
2089 // so we allow &global+constantoffset, which is safe and uniformly supported
2091 ConstantExpr *CE = cast<ConstantExpr>(C);
2092 switch (CE->getOpcode()) {
2093 case Instruction::BitCast:
2094 case Instruction::IntToPtr:
2095 case Instruction::PtrToInt:
2096 // These casts are always fine if the casted value is.
2097 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2099 // GEP is fine if it is simple + constant offset.
2100 case Instruction::GetElementPtr:
2101 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2102 if (!isa<ConstantInt>(CE->getOperand(i)))
2104 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2106 case Instruction::Add:
2107 // We allow simple+cst.
2108 if (!isa<ConstantInt>(CE->getOperand(1)))
2110 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2116 isSimpleEnoughValueToCommit(Constant *C,
2117 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2118 // If we already checked this constant, we win.
2119 if (!SimpleConstants.insert(C)) return true;
2120 // Check the constant.
2121 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants);
2125 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2126 /// enough for us to understand. In particular, if it is a cast of something,
2127 /// we punt. We basically just support direct accesses to globals and GEP's of
2128 /// globals. This should be kept up to date with CommitValueTo.
2129 static bool isSimpleEnoughPointerToCommit(Constant *C) {
2130 // Conservatively, avoid aggregate types. This is because we don't
2131 // want to worry about them partially overlapping other stores.
2132 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2135 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2136 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2137 // external globals.
2138 return GV->hasUniqueInitializer();
2140 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2141 // Handle a constantexpr gep.
2142 if (CE->getOpcode() == Instruction::GetElementPtr &&
2143 isa<GlobalVariable>(CE->getOperand(0)) &&
2144 cast<GEPOperator>(CE)->isInBounds()) {
2145 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2146 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2147 // external globals.
2148 if (!GV->hasUniqueInitializer())
2151 // The first index must be zero.
2152 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
2153 if (!CI || !CI->isZero()) return false;
2155 // The remaining indices must be compile-time known integers within the
2156 // notional bounds of the corresponding static array types.
2157 if (!CE->isGEPWithNoNotionalOverIndexing())
2160 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2165 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2166 /// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2167 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2168 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2169 ConstantExpr *Addr, unsigned OpNo) {
2170 // Base case of the recursion.
2171 if (OpNo == Addr->getNumOperands()) {
2172 assert(Val->getType() == Init->getType() && "Type mismatch!");
2176 std::vector<Constant*> Elts;
2177 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2179 // Break up the constant into its elements.
2180 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2181 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2182 Elts.push_back(cast<Constant>(*i));
2183 } else if (isa<ConstantAggregateZero>(Init)) {
2184 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2185 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
2186 } else if (isa<UndefValue>(Init)) {
2187 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2188 Elts.push_back(UndefValue::get(STy->getElementType(i)));
2190 llvm_unreachable("This code is out of sync with "
2191 " ConstantFoldLoadThroughGEPConstantExpr");
2194 // Replace the element that we are supposed to.
2195 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2196 unsigned Idx = CU->getZExtValue();
2197 assert(Idx < STy->getNumElements() && "Struct index out of range!");
2198 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2200 // Return the modified struct.
2201 return ConstantStruct::get(Init->getContext(), &Elts[0], Elts.size(),
2204 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2205 const SequentialType *InitTy = cast<SequentialType>(Init->getType());
2208 if (const ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2209 NumElts = ATy->getNumElements();
2211 NumElts = cast<VectorType>(InitTy)->getNumElements();
2214 // Break up the array into elements.
2215 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2216 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2217 Elts.push_back(cast<Constant>(*i));
2218 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2219 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2220 Elts.push_back(cast<Constant>(*i));
2221 } else if (isa<ConstantAggregateZero>(Init)) {
2222 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
2224 assert(isa<UndefValue>(Init) && "This code is out of sync with "
2225 " ConstantFoldLoadThroughGEPConstantExpr");
2226 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
2229 assert(CI->getZExtValue() < NumElts);
2230 Elts[CI->getZExtValue()] =
2231 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2233 if (Init->getType()->isArrayTy())
2234 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2236 return ConstantVector::get(&Elts[0], Elts.size());
2240 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
2241 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2242 static void CommitValueTo(Constant *Val, Constant *Addr) {
2243 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2244 assert(GV->hasInitializer());
2245 GV->setInitializer(Val);
2249 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2250 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2251 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
2254 /// ComputeLoadResult - Return the value that would be computed by a load from
2255 /// P after the stores reflected by 'memory' have been performed. If we can't
2256 /// decide, return null.
2257 static Constant *ComputeLoadResult(Constant *P,
2258 const DenseMap<Constant*, Constant*> &Memory) {
2259 // If this memory location has been recently stored, use the stored value: it
2260 // is the most up-to-date.
2261 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
2262 if (I != Memory.end()) return I->second;
2265 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2266 if (GV->hasDefinitiveInitializer())
2267 return GV->getInitializer();
2271 // Handle a constantexpr getelementptr.
2272 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2273 if (CE->getOpcode() == Instruction::GetElementPtr &&
2274 isa<GlobalVariable>(CE->getOperand(0))) {
2275 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2276 if (GV->hasDefinitiveInitializer())
2277 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2280 return 0; // don't know how to evaluate.
2283 /// EvaluateFunction - Evaluate a call to function F, returning true if
2284 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2285 /// arguments for the function.
2286 static bool EvaluateFunction(Function *F, Constant *&RetVal,
2287 const SmallVectorImpl<Constant*> &ActualArgs,
2288 std::vector<Function*> &CallStack,
2289 DenseMap<Constant*, Constant*> &MutatedMemory,
2290 std::vector<GlobalVariable*> &AllocaTmps,
2291 SmallPtrSet<Constant*, 8> &SimpleConstants,
2292 const TargetData *TD) {
2293 // Check to see if this function is already executing (recursion). If so,
2294 // bail out. TODO: we might want to accept limited recursion.
2295 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2298 CallStack.push_back(F);
2300 /// Values - As we compute SSA register values, we store their contents here.
2301 DenseMap<Value*, Constant*> Values;
2303 // Initialize arguments to the incoming values specified.
2305 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2307 Values[AI] = ActualArgs[ArgNo];
2309 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2310 /// we can only evaluate any one basic block at most once. This set keeps
2311 /// track of what we have executed so we can detect recursive cases etc.
2312 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2314 // CurInst - The current instruction we're evaluating.
2315 BasicBlock::iterator CurInst = F->begin()->begin();
2317 // This is the main evaluation loop.
2319 Constant *InstResult = 0;
2321 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2322 if (SI->isVolatile()) return false; // no volatile accesses.
2323 Constant *Ptr = getVal(Values, SI->getOperand(1));
2324 if (!isSimpleEnoughPointerToCommit(Ptr))
2325 // If this is too complex for us to commit, reject it.
2328 Constant *Val = getVal(Values, SI->getOperand(0));
2330 // If this might be too difficult for the backend to handle (e.g. the addr
2331 // of one global variable divided by another) then we can't commit it.
2332 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants))
2334 MutatedMemory[Ptr] = Val;
2335 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2336 InstResult = ConstantExpr::get(BO->getOpcode(),
2337 getVal(Values, BO->getOperand(0)),
2338 getVal(Values, BO->getOperand(1)));
2339 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2340 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2341 getVal(Values, CI->getOperand(0)),
2342 getVal(Values, CI->getOperand(1)));
2343 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
2344 InstResult = ConstantExpr::getCast(CI->getOpcode(),
2345 getVal(Values, CI->getOperand(0)),
2347 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2348 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
2349 getVal(Values, SI->getOperand(1)),
2350 getVal(Values, SI->getOperand(2)));
2351 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2352 Constant *P = getVal(Values, GEP->getOperand(0));
2353 SmallVector<Constant*, 8> GEPOps;
2354 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2356 GEPOps.push_back(getVal(Values, *i));
2357 InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2358 ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2359 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
2360 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2361 if (LI->isVolatile()) return false; // no volatile accesses.
2362 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
2364 if (InstResult == 0) return false; // Could not evaluate load.
2365 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2366 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
2367 const Type *Ty = AI->getType()->getElementType();
2368 AllocaTmps.push_back(new GlobalVariable(Ty, false,
2369 GlobalValue::InternalLinkage,
2370 UndefValue::get(Ty),
2372 InstResult = AllocaTmps.back();
2373 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
2375 // Debug info can safely be ignored here.
2376 if (isa<DbgInfoIntrinsic>(CI)) {
2381 // Cannot handle inline asm.
2382 if (isa<InlineAsm>(CI->getCalledValue())) return false;
2384 // Resolve function pointers.
2385 Function *Callee = dyn_cast<Function>(getVal(Values,
2386 CI->getCalledValue()));
2387 if (!Callee) return false; // Cannot resolve.
2389 SmallVector<Constant*, 8> Formals;
2391 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end();
2393 Formals.push_back(getVal(Values, *i));
2395 if (Callee->isDeclaration()) {
2396 // If this is a function we can constant fold, do it.
2397 if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
2404 if (Callee->getFunctionType()->isVarArg())
2408 // Execute the call, if successful, use the return value.
2409 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2410 MutatedMemory, AllocaTmps, SimpleConstants, TD))
2412 InstResult = RetVal;
2414 } else if (isa<TerminatorInst>(CurInst)) {
2415 BasicBlock *NewBB = 0;
2416 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2417 if (BI->isUnconditional()) {
2418 NewBB = BI->getSuccessor(0);
2421 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
2422 if (!Cond) return false; // Cannot determine.
2424 NewBB = BI->getSuccessor(!Cond->getZExtValue());
2426 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2428 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
2429 if (!Val) return false; // Cannot determine.
2430 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2431 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2432 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2433 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2434 NewBB = BA->getBasicBlock();
2436 return false; // Cannot determine.
2437 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
2438 if (RI->getNumOperands())
2439 RetVal = getVal(Values, RI->getOperand(0));
2441 CallStack.pop_back(); // return from fn.
2442 return true; // We succeeded at evaluating this ctor!
2444 // invoke, unwind, unreachable.
2445 return false; // Cannot handle this terminator.
2448 // Okay, we succeeded in evaluating this control flow. See if we have
2449 // executed the new block before. If so, we have a looping function,
2450 // which we cannot evaluate in reasonable time.
2451 if (!ExecutedBlocks.insert(NewBB))
2452 return false; // looped!
2454 // Okay, we have never been in this block before. Check to see if there
2455 // are any PHI nodes. If so, evaluate them with information about where
2457 BasicBlock *OldBB = CurInst->getParent();
2458 CurInst = NewBB->begin();
2460 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2461 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2463 // Do NOT increment CurInst. We know that the terminator had no value.
2466 // Did not know how to evaluate this!
2470 if (!CurInst->use_empty()) {
2471 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
2472 InstResult = ConstantFoldConstantExpression(CE, TD);
2474 Values[CurInst] = InstResult;
2477 // Advance program counter.
2482 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2483 /// we can. Return true if we can, false otherwise.
2484 static bool EvaluateStaticConstructor(Function *F, const TargetData *TD) {
2485 /// MutatedMemory - For each store we execute, we update this map. Loads
2486 /// check this to get the most up-to-date value. If evaluation is successful,
2487 /// this state is committed to the process.
2488 DenseMap<Constant*, Constant*> MutatedMemory;
2490 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2491 /// to represent its body. This vector is needed so we can delete the
2492 /// temporary globals when we are done.
2493 std::vector<GlobalVariable*> AllocaTmps;
2495 /// CallStack - This is used to detect recursion. In pathological situations
2496 /// we could hit exponential behavior, but at least there is nothing
2498 std::vector<Function*> CallStack;
2500 /// SimpleConstants - These are constants we have checked and know to be
2501 /// simple enough to live in a static initializer of a global.
2502 SmallPtrSet<Constant*, 8> SimpleConstants;
2504 // Call the function.
2505 Constant *RetValDummy;
2506 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2507 SmallVector<Constant*, 0>(), CallStack,
2508 MutatedMemory, AllocaTmps,
2509 SimpleConstants, TD);
2512 // We succeeded at evaluation: commit the result.
2513 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2514 << F->getName() << "' to " << MutatedMemory.size()
2516 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
2517 E = MutatedMemory.end(); I != E; ++I)
2518 CommitValueTo(I->second, I->first);
2521 // At this point, we are done interpreting. If we created any 'alloca'
2522 // temporaries, release them now.
2523 while (!AllocaTmps.empty()) {
2524 GlobalVariable *Tmp = AllocaTmps.back();
2525 AllocaTmps.pop_back();
2527 // If there are still users of the alloca, the program is doing something
2528 // silly, e.g. storing the address of the alloca somewhere and using it
2529 // later. Since this is undefined, we'll just make it be null.
2530 if (!Tmp->use_empty())
2531 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2540 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2541 /// Return true if anything changed.
2542 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2543 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2544 bool MadeChange = false;
2545 if (Ctors.empty()) return false;
2547 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
2548 // Loop over global ctors, optimizing them when we can.
2549 for (unsigned i = 0; i != Ctors.size(); ++i) {
2550 Function *F = Ctors[i];
2551 // Found a null terminator in the middle of the list, prune off the rest of
2554 if (i != Ctors.size()-1) {
2561 // We cannot simplify external ctor functions.
2562 if (F->empty()) continue;
2564 // If we can evaluate the ctor at compile time, do.
2565 if (EvaluateStaticConstructor(F, TD)) {
2566 Ctors.erase(Ctors.begin()+i);
2569 ++NumCtorsEvaluated;
2574 if (!MadeChange) return false;
2576 GCL = InstallGlobalCtors(GCL, Ctors);
2580 bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
2581 bool Changed = false;
2583 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
2585 Module::alias_iterator J = I++;
2586 // Aliases without names cannot be referenced outside this module.
2587 if (!J->hasName() && !J->isDeclaration())
2588 J->setLinkage(GlobalValue::InternalLinkage);
2589 // If the aliasee may change at link time, nothing can be done - bail out.
2590 if (J->mayBeOverridden())
2593 Constant *Aliasee = J->getAliasee();
2594 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2595 Target->removeDeadConstantUsers();
2596 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2598 // Make all users of the alias use the aliasee instead.
2599 if (!J->use_empty()) {
2600 J->replaceAllUsesWith(Aliasee);
2601 ++NumAliasesResolved;
2605 // If the alias is externally visible, we may still be able to simplify it.
2606 if (!J->hasLocalLinkage()) {
2607 // If the aliasee has internal linkage, give it the name and linkage
2608 // of the alias, and delete the alias. This turns:
2609 // define internal ... @f(...)
2610 // @a = alias ... @f
2612 // define ... @a(...)
2613 if (!Target->hasLocalLinkage())
2616 // Do not perform the transform if multiple aliases potentially target the
2617 // aliasee. This check also ensures that it is safe to replace the section
2618 // and other attributes of the aliasee with those of the alias.
2622 // Give the aliasee the name, linkage and other attributes of the alias.
2623 Target->takeName(J);
2624 Target->setLinkage(J->getLinkage());
2625 Target->GlobalValue::copyAttributesFrom(J);
2628 // Delete the alias.
2629 M.getAliasList().erase(J);
2630 ++NumAliasesRemoved;
2637 bool GlobalOpt::runOnModule(Module &M) {
2638 bool Changed = false;
2640 // Try to find the llvm.globalctors list.
2641 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2643 bool LocalChange = true;
2644 while (LocalChange) {
2645 LocalChange = false;
2647 // Delete functions that are trivially dead, ccc -> fastcc
2648 LocalChange |= OptimizeFunctions(M);
2650 // Optimize global_ctors list.
2652 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2654 // Optimize non-address-taken globals.
2655 LocalChange |= OptimizeGlobalVars(M);
2657 // Resolve aliases, when possible.
2658 LocalChange |= OptimizeGlobalAliases(M);
2659 Changed |= LocalChange;
2662 // TODO: Move all global ctors functions to the end of the module for code