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/LLVMContext.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Support/CallSite.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/GetElementPtrTypeIterator.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/ADT/STLExtras.h"
43 STATISTIC(NumMarked , "Number of globals marked constant");
44 STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
45 STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
46 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
47 STATISTIC(NumDeleted , "Number of globals deleted");
48 STATISTIC(NumFnDeleted , "Number of functions deleted");
49 STATISTIC(NumGlobUses , "Number of global uses devirtualized");
50 STATISTIC(NumLocalized , "Number of globals localized");
51 STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
52 STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
53 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
54 STATISTIC(NumNestRemoved , "Number of nest attributes removed");
55 STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
56 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
59 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
60 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62 static char ID; // Pass identification, replacement for typeid
63 GlobalOpt() : ModulePass(&ID) {}
65 bool runOnModule(Module &M);
68 GlobalVariable *FindGlobalCtors(Module &M);
69 bool OptimizeFunctions(Module &M);
70 bool OptimizeGlobalVars(Module &M);
71 bool OptimizeGlobalAliases(Module &M);
72 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
73 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
77 char GlobalOpt::ID = 0;
78 static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
80 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
84 /// GlobalStatus - As we analyze each global, keep track of some information
85 /// about it. If we find out that the address of the global is taken, none of
86 /// this info will be accurate.
87 struct VISIBILITY_HIDDEN GlobalStatus {
88 /// isLoaded - True if the global is ever loaded. If the global isn't ever
89 /// loaded it can be deleted.
92 /// StoredType - Keep track of what stores to the global look like.
95 /// NotStored - There is no store to this global. It can thus be marked
99 /// isInitializerStored - This global is stored to, but the only thing
100 /// stored is the constant it was initialized with. This is only tracked
101 /// for scalar globals.
104 /// isStoredOnce - This global is stored to, but only its initializer and
105 /// one other value is ever stored to it. If this global isStoredOnce, we
106 /// track the value stored to it in StoredOnceValue below. This is only
107 /// tracked for scalar globals.
110 /// isStored - This global is stored to by multiple values or something else
111 /// that we cannot track.
115 /// StoredOnceValue - If only one value (besides the initializer constant) is
116 /// ever stored to this global, keep track of what value it is.
117 Value *StoredOnceValue;
119 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
120 /// null/false. When the first accessing function is noticed, it is recorded.
121 /// When a second different accessing function is noticed,
122 /// HasMultipleAccessingFunctions is set to true.
123 Function *AccessingFunction;
124 bool HasMultipleAccessingFunctions;
126 /// HasNonInstructionUser - Set to true if this global has a user that is not
127 /// an instruction (e.g. a constant expr or GV initializer).
128 bool HasNonInstructionUser;
130 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
133 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
134 AccessingFunction(0), HasMultipleAccessingFunctions(false),
135 HasNonInstructionUser(false), HasPHIUser(false) {}
140 // SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
141 // by constants itself. Note that constants cannot be cyclic, so this test is
142 // pretty easy to implement recursively.
144 static bool SafeToDestroyConstant(Constant *C) {
145 if (isa<GlobalValue>(C)) return false;
147 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
148 if (Constant *CU = dyn_cast<Constant>(*UI)) {
149 if (!SafeToDestroyConstant(CU)) return false;
156 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
157 /// structure. If the global has its address taken, return true to indicate we
158 /// can't do anything with it.
160 static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
161 SmallPtrSet<PHINode*, 16> &PHIUsers) {
162 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
163 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
164 GS.HasNonInstructionUser = true;
166 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
168 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
169 if (!GS.HasMultipleAccessingFunctions) {
170 Function *F = I->getParent()->getParent();
171 if (GS.AccessingFunction == 0)
172 GS.AccessingFunction = F;
173 else if (GS.AccessingFunction != F)
174 GS.HasMultipleAccessingFunctions = true;
176 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
178 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
179 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
180 // Don't allow a store OF the address, only stores TO the address.
181 if (SI->getOperand(0) == V) return true;
183 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
185 // If this is a direct store to the global (i.e., the global is a scalar
186 // value, not an aggregate), keep more specific information about
188 if (GS.StoredType != GlobalStatus::isStored) {
189 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
190 Value *StoredVal = SI->getOperand(0);
191 if (StoredVal == GV->getInitializer()) {
192 if (GS.StoredType < GlobalStatus::isInitializerStored)
193 GS.StoredType = GlobalStatus::isInitializerStored;
194 } else if (isa<LoadInst>(StoredVal) &&
195 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
197 if (GS.StoredType < GlobalStatus::isInitializerStored)
198 GS.StoredType = GlobalStatus::isInitializerStored;
199 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
200 GS.StoredType = GlobalStatus::isStoredOnce;
201 GS.StoredOnceValue = StoredVal;
202 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
203 GS.StoredOnceValue == StoredVal) {
206 GS.StoredType = GlobalStatus::isStored;
209 GS.StoredType = GlobalStatus::isStored;
212 } else if (isa<GetElementPtrInst>(I)) {
213 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
214 } else if (isa<SelectInst>(I)) {
215 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
216 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
217 // PHI nodes we can check just like select or GEP instructions, but we
218 // have to be careful about infinite recursion.
219 if (PHIUsers.insert(PN)) // Not already visited.
220 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
221 GS.HasPHIUser = true;
222 } else if (isa<CmpInst>(I)) {
223 } else if (isa<MemTransferInst>(I)) {
224 if (I->getOperand(1) == V)
225 GS.StoredType = GlobalStatus::isStored;
226 if (I->getOperand(2) == V)
228 } else if (isa<MemSetInst>(I)) {
229 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
230 GS.StoredType = GlobalStatus::isStored;
232 return true; // Any other non-load instruction might take address!
234 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
235 GS.HasNonInstructionUser = true;
236 // We might have a dead and dangling constant hanging off of here.
237 if (!SafeToDestroyConstant(C))
240 GS.HasNonInstructionUser = true;
241 // Otherwise must be some other user.
248 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx,
249 LLVMContext &Context) {
250 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
252 unsigned IdxV = CI->getZExtValue();
254 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
255 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
256 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
257 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
258 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
259 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
260 } else if (isa<ConstantAggregateZero>(Agg)) {
261 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
262 if (IdxV < STy->getNumElements())
263 return Constant::getNullValue(STy->getElementType(IdxV));
264 } else if (const SequentialType *STy =
265 dyn_cast<SequentialType>(Agg->getType())) {
266 return Constant::getNullValue(STy->getElementType());
268 } else if (isa<UndefValue>(Agg)) {
269 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
270 if (IdxV < STy->getNumElements())
271 return UndefValue::get(STy->getElementType(IdxV));
272 } else if (const SequentialType *STy =
273 dyn_cast<SequentialType>(Agg->getType())) {
274 return UndefValue::get(STy->getElementType());
281 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
282 /// users of the global, cleaning up the obvious ones. This is largely just a
283 /// quick scan over the use list to clean up the easy and obvious cruft. This
284 /// returns true if it made a change.
285 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
286 LLVMContext &Context) {
287 bool Changed = false;
288 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
291 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
293 // Replace the load with the initializer.
294 LI->replaceAllUsesWith(Init);
295 LI->eraseFromParent();
298 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
299 // Store must be unreachable or storing Init into the global.
300 SI->eraseFromParent();
302 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
303 if (CE->getOpcode() == Instruction::GetElementPtr) {
304 Constant *SubInit = 0;
306 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE, Context);
307 Changed |= CleanupConstantGlobalUsers(CE, SubInit, Context);
308 } else if (CE->getOpcode() == Instruction::BitCast &&
309 isa<PointerType>(CE->getType())) {
310 // Pointer cast, delete any stores and memsets to the global.
311 Changed |= CleanupConstantGlobalUsers(CE, 0, Context);
314 if (CE->use_empty()) {
315 CE->destroyConstant();
318 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
319 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
320 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
321 // and will invalidate our notion of what Init is.
322 Constant *SubInit = 0;
323 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
325 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, Context));
326 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
327 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE, Context);
329 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, Context);
331 if (GEP->use_empty()) {
332 GEP->eraseFromParent();
335 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
336 if (MI->getRawDest() == V) {
337 MI->eraseFromParent();
341 } else if (Constant *C = dyn_cast<Constant>(U)) {
342 // If we have a chain of dead constantexprs or other things dangling from
343 // us, and if they are all dead, nuke them without remorse.
344 if (SafeToDestroyConstant(C)) {
345 C->destroyConstant();
346 // This could have invalidated UI, start over from scratch.
347 CleanupConstantGlobalUsers(V, Init, Context);
355 /// isSafeSROAElementUse - Return true if the specified instruction is a safe
356 /// user of a derived expression from a global that we want to SROA.
357 static bool isSafeSROAElementUse(Value *V) {
358 // We might have a dead and dangling constant hanging off of here.
359 if (Constant *C = dyn_cast<Constant>(V))
360 return SafeToDestroyConstant(C);
362 Instruction *I = dyn_cast<Instruction>(V);
363 if (!I) return false;
366 if (isa<LoadInst>(I)) return true;
368 // Stores *to* the pointer are ok.
369 if (StoreInst *SI = dyn_cast<StoreInst>(I))
370 return SI->getOperand(0) != V;
372 // Otherwise, it must be a GEP.
373 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
374 if (GEPI == 0) return false;
376 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
377 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
380 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
382 if (!isSafeSROAElementUse(*I))
388 /// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
389 /// Look at it and its uses and decide whether it is safe to SROA this global.
391 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
392 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
393 if (!isa<GetElementPtrInst>(U) &&
394 (!isa<ConstantExpr>(U) ||
395 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
398 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
399 // don't like < 3 operand CE's, and we don't like non-constant integer
400 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
402 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
403 !cast<Constant>(U->getOperand(1))->isNullValue() ||
404 !isa<ConstantInt>(U->getOperand(2)))
407 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
408 ++GEPI; // Skip over the pointer index.
410 // If this is a use of an array allocation, do a bit more checking for sanity.
411 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
412 uint64_t NumElements = AT->getNumElements();
413 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
415 // Check to make sure that index falls within the array. If not,
416 // something funny is going on, so we won't do the optimization.
418 if (Idx->getZExtValue() >= NumElements)
421 // We cannot scalar repl this level of the array unless any array
422 // sub-indices are in-range constants. In particular, consider:
423 // A[0][i]. We cannot know that the user isn't doing invalid things like
424 // allowing i to index an out-of-range subscript that accesses A[1].
426 // Scalar replacing *just* the outer index of the array is probably not
427 // going to be a win anyway, so just give up.
428 for (++GEPI; // Skip array index.
429 GEPI != E && (isa<ArrayType>(*GEPI) || isa<VectorType>(*GEPI));
431 uint64_t NumElements;
432 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
433 NumElements = SubArrayTy->getNumElements();
435 NumElements = cast<VectorType>(*GEPI)->getNumElements();
437 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
438 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
443 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
444 if (!isSafeSROAElementUse(*I))
449 /// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
450 /// is safe for us to perform this transformation.
452 static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
453 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
455 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
462 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
463 /// variable. This opens the door for other optimizations by exposing the
464 /// behavior of the program in a more fine-grained way. We have determined that
465 /// this transformation is safe already. We return the first global variable we
466 /// insert so that the caller can reprocess it.
467 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD,
468 LLVMContext &Context) {
469 // Make sure this global only has simple uses that we can SRA.
470 if (!GlobalUsersSafeToSRA(GV))
473 assert(GV->hasLocalLinkage() && !GV->isConstant());
474 Constant *Init = GV->getInitializer();
475 const Type *Ty = Init->getType();
477 std::vector<GlobalVariable*> NewGlobals;
478 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
480 // Get the alignment of the global, either explicit or target-specific.
481 unsigned StartAlignment = GV->getAlignment();
482 if (StartAlignment == 0)
483 StartAlignment = TD.getABITypeAlignment(GV->getType());
485 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
486 NewGlobals.reserve(STy->getNumElements());
487 const StructLayout &Layout = *TD.getStructLayout(STy);
488 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
489 Constant *In = getAggregateConstantElement(Init,
490 ConstantInt::get(Type::getInt32Ty(Context), i),
492 assert(In && "Couldn't get element of initializer?");
493 GlobalVariable *NGV = new GlobalVariable(Context,
494 STy->getElementType(i), false,
495 GlobalVariable::InternalLinkage,
496 In, GV->getName()+"."+Twine(i),
498 GV->getType()->getAddressSpace());
499 Globals.insert(GV, NGV);
500 NewGlobals.push_back(NGV);
502 // Calculate the known alignment of the field. If the original aggregate
503 // had 256 byte alignment for example, something might depend on that:
504 // propagate info to each field.
505 uint64_t FieldOffset = Layout.getElementOffset(i);
506 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
507 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
508 NGV->setAlignment(NewAlign);
510 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
511 unsigned NumElements = 0;
512 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
513 NumElements = ATy->getNumElements();
515 NumElements = cast<VectorType>(STy)->getNumElements();
517 if (NumElements > 16 && GV->hasNUsesOrMore(16))
518 return 0; // It's not worth it.
519 NewGlobals.reserve(NumElements);
521 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
522 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
523 for (unsigned i = 0, e = NumElements; i != e; ++i) {
524 Constant *In = getAggregateConstantElement(Init,
525 ConstantInt::get(Type::getInt32Ty(Context), i),
527 assert(In && "Couldn't get element of initializer?");
529 GlobalVariable *NGV = new GlobalVariable(Context,
530 STy->getElementType(), false,
531 GlobalVariable::InternalLinkage,
532 In, GV->getName()+"."+Twine(i),
534 GV->getType()->getAddressSpace());
535 Globals.insert(GV, NGV);
536 NewGlobals.push_back(NGV);
538 // Calculate the known alignment of the field. If the original aggregate
539 // had 256 byte alignment for example, something might depend on that:
540 // propagate info to each field.
541 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
542 if (NewAlign > EltAlign)
543 NGV->setAlignment(NewAlign);
547 if (NewGlobals.empty())
550 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
552 Constant *NullInt = Constant::getNullValue(Type::getInt32Ty(Context));
554 // Loop over all of the uses of the global, replacing the constantexpr geps,
555 // with smaller constantexpr geps or direct references.
556 while (!GV->use_empty()) {
557 User *GEP = GV->use_back();
558 assert(((isa<ConstantExpr>(GEP) &&
559 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
560 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
562 // Ignore the 1th operand, which has to be zero or else the program is quite
563 // broken (undefined). Get the 2nd operand, which is the structure or array
565 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
566 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
568 Value *NewPtr = NewGlobals[Val];
570 // Form a shorter GEP if needed.
571 if (GEP->getNumOperands() > 3) {
572 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
573 SmallVector<Constant*, 8> Idxs;
574 Idxs.push_back(NullInt);
575 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
576 Idxs.push_back(CE->getOperand(i));
577 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
578 &Idxs[0], Idxs.size());
580 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
581 SmallVector<Value*, 8> Idxs;
582 Idxs.push_back(NullInt);
583 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
584 Idxs.push_back(GEPI->getOperand(i));
585 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
586 GEPI->getName()+"."+Twine(Val),GEPI);
589 GEP->replaceAllUsesWith(NewPtr);
591 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
592 GEPI->eraseFromParent();
594 cast<ConstantExpr>(GEP)->destroyConstant();
597 // Delete the old global, now that it is dead.
601 // Loop over the new globals array deleting any globals that are obviously
602 // dead. This can arise due to scalarization of a structure or an array that
603 // has elements that are dead.
604 unsigned FirstGlobal = 0;
605 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
606 if (NewGlobals[i]->use_empty()) {
607 Globals.erase(NewGlobals[i]);
608 if (FirstGlobal == i) ++FirstGlobal;
611 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
614 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
615 /// value will trap if the value is dynamically null. PHIs keeps track of any
616 /// phi nodes we've seen to avoid reprocessing them.
617 static bool AllUsesOfValueWillTrapIfNull(Value *V,
618 SmallPtrSet<PHINode*, 8> &PHIs) {
619 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
620 if (isa<LoadInst>(*UI)) {
622 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
623 if (SI->getOperand(0) == V) {
624 //cerr << "NONTRAPPING USE: " << **UI;
625 return false; // Storing the value.
627 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
628 if (CI->getOperand(0) != V) {
629 //cerr << "NONTRAPPING USE: " << **UI;
630 return false; // Not calling the ptr
632 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
633 if (II->getOperand(0) != V) {
634 //cerr << "NONTRAPPING USE: " << **UI;
635 return false; // Not calling the ptr
637 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
638 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
639 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
640 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
641 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
642 // If we've already seen this phi node, ignore it, it has already been
645 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
646 } else if (isa<ICmpInst>(*UI) &&
647 isa<ConstantPointerNull>(UI->getOperand(1))) {
648 // Ignore setcc X, null
650 //cerr << "NONTRAPPING USE: " << **UI;
656 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
657 /// from GV will trap if the loaded value is null. Note that this also permits
658 /// comparisons of the loaded value against null, as a special case.
659 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
660 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
661 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
662 SmallPtrSet<PHINode*, 8> PHIs;
663 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
665 } else if (isa<StoreInst>(*UI)) {
666 // Ignore stores to the global.
668 // We don't know or understand this user, bail out.
669 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
676 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV,
677 LLVMContext &Context) {
678 bool Changed = false;
679 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
680 Instruction *I = cast<Instruction>(*UI++);
681 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
682 LI->setOperand(0, NewV);
684 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
685 if (SI->getOperand(1) == V) {
686 SI->setOperand(1, NewV);
689 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
690 if (I->getOperand(0) == V) {
691 // Calling through the pointer! Turn into a direct call, but be careful
692 // that the pointer is not also being passed as an argument.
693 I->setOperand(0, NewV);
695 bool PassedAsArg = false;
696 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
697 if (I->getOperand(i) == V) {
699 I->setOperand(i, NewV);
703 // Being passed as an argument also. Be careful to not invalidate UI!
707 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
708 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
709 ConstantExpr::getCast(CI->getOpcode(),
710 NewV, CI->getType()), Context);
711 if (CI->use_empty()) {
713 CI->eraseFromParent();
715 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
716 // Should handle GEP here.
717 SmallVector<Constant*, 8> Idxs;
718 Idxs.reserve(GEPI->getNumOperands()-1);
719 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
721 if (Constant *C = dyn_cast<Constant>(*i))
725 if (Idxs.size() == GEPI->getNumOperands()-1)
726 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
727 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
728 Idxs.size()), Context);
729 if (GEPI->use_empty()) {
731 GEPI->eraseFromParent();
740 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
741 /// value stored into it. If there are uses of the loaded value that would trap
742 /// if the loaded value is dynamically null, then we know that they cannot be
743 /// reachable with a null optimize away the load.
744 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
745 LLVMContext &Context) {
746 bool Changed = false;
748 // Keep track of whether we are able to remove all the uses of the global
749 // other than the store that defines it.
750 bool AllNonStoreUsesGone = true;
752 // Replace all uses of loads with uses of uses of the stored value.
753 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
754 User *GlobalUser = *GUI++;
755 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
756 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV, Context);
757 // If we were able to delete all uses of the loads
758 if (LI->use_empty()) {
759 LI->eraseFromParent();
762 AllNonStoreUsesGone = false;
764 } else if (isa<StoreInst>(GlobalUser)) {
765 // Ignore the store that stores "LV" to the global.
766 assert(GlobalUser->getOperand(1) == GV &&
767 "Must be storing *to* the global");
769 AllNonStoreUsesGone = false;
771 // If we get here we could have other crazy uses that are transitively
773 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
774 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
779 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
783 // If we nuked all of the loads, then none of the stores are needed either,
784 // nor is the global.
785 if (AllNonStoreUsesGone) {
786 DOUT << " *** GLOBAL NOW DEAD!\n";
787 CleanupConstantGlobalUsers(GV, 0, Context);
788 if (GV->use_empty()) {
789 GV->eraseFromParent();
797 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
798 /// instructions that are foldable.
799 static void ConstantPropUsersOf(Value *V, LLVMContext &Context) {
800 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
801 if (Instruction *I = dyn_cast<Instruction>(*UI++))
802 if (Constant *NewC = ConstantFoldInstruction(I, Context)) {
803 I->replaceAllUsesWith(NewC);
805 // Advance UI to the next non-I use to avoid invalidating it!
806 // Instructions could multiply use V.
807 while (UI != E && *UI == I)
809 I->eraseFromParent();
813 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
814 /// variable, and transforms the program as if it always contained the result of
815 /// the specified malloc. Because it is always the result of the specified
816 /// malloc, there is no reason to actually DO the malloc. Instead, turn the
817 /// malloc into a global, and any loads of GV as uses of the new global.
818 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
820 LLVMContext &Context) {
821 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
822 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
824 if (NElements->getZExtValue() != 1) {
825 // If we have an array allocation, transform it to a single element
826 // allocation to make the code below simpler.
827 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
828 NElements->getZExtValue());
830 new MallocInst(NewTy, Constant::getNullValue(Type::getInt32Ty(Context)),
831 MI->getAlignment(), MI->getName(), MI);
833 Indices[0] = Indices[1] = Constant::getNullValue(Type::getInt32Ty(Context));
834 Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
835 NewMI->getName()+".el0", MI);
836 MI->replaceAllUsesWith(NewGEP);
837 MI->eraseFromParent();
841 // Create the new global variable. The contents of the malloc'd memory is
842 // undefined, so initialize with an undef value.
843 // FIXME: This new global should have the alignment returned by malloc. Code
844 // could depend on malloc returning large alignment (on the mac, 16 bytes) but
845 // this would only guarantee some lower alignment.
846 Constant *Init = UndefValue::get(MI->getAllocatedType());
847 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
848 MI->getAllocatedType(), false,
849 GlobalValue::InternalLinkage, Init,
850 GV->getName()+".body",
852 GV->isThreadLocal());
854 // Anything that used the malloc now uses the global directly.
855 MI->replaceAllUsesWith(NewGV);
857 Constant *RepValue = NewGV;
858 if (NewGV->getType() != GV->getType()->getElementType())
859 RepValue = ConstantExpr::getBitCast(RepValue,
860 GV->getType()->getElementType());
862 // If there is a comparison against null, we will insert a global bool to
863 // keep track of whether the global was initialized yet or not.
864 GlobalVariable *InitBool =
865 new GlobalVariable(Context, Type::getInt1Ty(Context), false,
866 GlobalValue::InternalLinkage,
867 ConstantInt::getFalse(Context), GV->getName()+".init",
868 GV->isThreadLocal());
869 bool InitBoolUsed = false;
871 // Loop over all uses of GV, processing them in turn.
872 std::vector<StoreInst*> Stores;
873 while (!GV->use_empty())
874 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
875 while (!LI->use_empty()) {
876 Use &LoadUse = LI->use_begin().getUse();
877 if (!isa<ICmpInst>(LoadUse.getUser()))
880 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
881 // Replace the cmp X, 0 with a use of the bool value.
882 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
884 switch (CI->getPredicate()) {
885 default: llvm_unreachable("Unknown ICmp Predicate!");
886 case ICmpInst::ICMP_ULT:
887 case ICmpInst::ICMP_SLT:
888 LV = ConstantInt::getFalse(Context); // X < null -> always false
890 case ICmpInst::ICMP_ULE:
891 case ICmpInst::ICMP_SLE:
892 case ICmpInst::ICMP_EQ:
893 LV = BinaryOperator::CreateNot(LV, "notinit", CI);
895 case ICmpInst::ICMP_NE:
896 case ICmpInst::ICMP_UGE:
897 case ICmpInst::ICMP_SGE:
898 case ICmpInst::ICMP_UGT:
899 case ICmpInst::ICMP_SGT:
902 CI->replaceAllUsesWith(LV);
903 CI->eraseFromParent();
906 LI->eraseFromParent();
908 StoreInst *SI = cast<StoreInst>(GV->use_back());
909 // The global is initialized when the store to it occurs.
910 new StoreInst(ConstantInt::getTrue(Context), InitBool, SI);
911 SI->eraseFromParent();
914 // If the initialization boolean was used, insert it, otherwise delete it.
916 while (!InitBool->use_empty()) // Delete initializations
917 cast<Instruction>(InitBool->use_back())->eraseFromParent();
920 GV->getParent()->getGlobalList().insert(GV, InitBool);
923 // Now the GV is dead, nuke it and the malloc.
924 GV->eraseFromParent();
925 MI->eraseFromParent();
927 // To further other optimizations, loop over all users of NewGV and try to
928 // constant prop them. This will promote GEP instructions with constant
929 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
930 ConstantPropUsersOf(NewGV, Context);
931 if (RepValue != NewGV)
932 ConstantPropUsersOf(RepValue, Context);
937 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
938 /// to make sure that there are no complex uses of V. We permit simple things
939 /// like dereferencing the pointer, but not storing through the address, unless
940 /// it is to the specified global.
941 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
943 SmallPtrSet<PHINode*, 8> &PHIs) {
944 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
945 Instruction *Inst = cast<Instruction>(*UI);
947 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
948 continue; // Fine, ignore.
951 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
952 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
953 return false; // Storing the pointer itself... bad.
954 continue; // Otherwise, storing through it, or storing into GV... fine.
957 if (isa<GetElementPtrInst>(Inst)) {
958 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
963 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
964 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
967 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
972 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
973 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
983 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
984 /// somewhere. Transform all uses of the allocation into loads from the
985 /// global and uses of the resultant pointer. Further, delete the store into
986 /// GV. This assumes that these value pass the
987 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
988 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
989 GlobalVariable *GV) {
990 while (!Alloc->use_empty()) {
991 Instruction *U = cast<Instruction>(*Alloc->use_begin());
992 Instruction *InsertPt = U;
993 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
994 // If this is the store of the allocation into the global, remove it.
995 if (SI->getOperand(1) == GV) {
996 SI->eraseFromParent();
999 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1000 // Insert the load in the corresponding predecessor, not right before the
1002 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
1003 } else if (isa<BitCastInst>(U)) {
1004 // Must be bitcast between the malloc and store to initialize the global.
1005 ReplaceUsesOfMallocWithGlobal(U, GV);
1006 U->eraseFromParent();
1008 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1009 // If this is a "GEP bitcast" and the user is a store to the global, then
1010 // just process it as a bitcast.
1011 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1012 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1013 if (SI->getOperand(1) == GV) {
1014 // Must be bitcast GEP between the malloc and store to initialize
1016 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1017 GEPI->eraseFromParent();
1022 // Insert a load from the global, and use it instead of the malloc.
1023 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
1024 U->replaceUsesOfWith(Alloc, NL);
1028 /// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1029 /// of a load) are simple enough to perform heap SRA on. This permits GEP's
1030 /// that index through the array and struct field, icmps of null, and PHIs.
1031 static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
1032 SmallPtrSet<PHINode*, 32> &LoadUsingPHIs,
1033 SmallPtrSet<PHINode*, 32> &LoadUsingPHIsPerLoad) {
1034 // We permit two users of the load: setcc comparing against the null
1035 // pointer, and a getelementptr of a specific form.
1036 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1037 Instruction *User = cast<Instruction>(*UI);
1039 // Comparison against null is ok.
1040 if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1041 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1046 // getelementptr is also ok, but only a simple form.
1047 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1048 // Must index into the array and into the struct.
1049 if (GEPI->getNumOperands() < 3)
1052 // Otherwise the GEP is ok.
1056 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1057 if (!LoadUsingPHIsPerLoad.insert(PN))
1058 // This means some phi nodes are dependent on each other.
1059 // Avoid infinite looping!
1061 if (!LoadUsingPHIs.insert(PN))
1062 // If we have already analyzed this PHI, then it is safe.
1065 // Make sure all uses of the PHI are simple enough to transform.
1066 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1067 LoadUsingPHIs, LoadUsingPHIsPerLoad))
1073 // Otherwise we don't know what this is, not ok.
1081 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1082 /// GV are simple enough to perform HeapSRA, return true.
1083 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
1085 SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
1086 SmallPtrSet<PHINode*, 32> LoadUsingPHIsPerLoad;
1087 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1089 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1090 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1091 LoadUsingPHIsPerLoad))
1093 LoadUsingPHIsPerLoad.clear();
1096 // If we reach here, we know that all uses of the loads and transitive uses
1097 // (through PHI nodes) are simple enough to transform. However, we don't know
1098 // that all inputs the to the PHI nodes are in the same equivalence sets.
1099 // Check to verify that all operands of the PHIs are either PHIS that can be
1100 // transformed, loads from GV, or MI itself.
1101 for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1102 E = LoadUsingPHIs.end(); I != E; ++I) {
1104 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1105 Value *InVal = PN->getIncomingValue(op);
1107 // PHI of the stored value itself is ok.
1108 if (InVal == MI) continue;
1110 if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1111 // One of the PHIs in our set is (optimistically) ok.
1112 if (LoadUsingPHIs.count(InPN))
1117 // Load from GV is ok.
1118 if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1119 if (LI->getOperand(0) == GV)
1124 // Anything else is rejected.
1132 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1133 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1134 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
1135 LLVMContext &Context) {
1136 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1138 if (FieldNo >= FieldVals.size())
1139 FieldVals.resize(FieldNo+1);
1141 // If we already have this value, just reuse the previously scalarized
1143 if (Value *FieldVal = FieldVals[FieldNo])
1146 // Depending on what instruction this is, we have several cases.
1148 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1149 // This is a scalarized version of the load from the global. Just create
1150 // a new Load of the scalarized global.
1151 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1152 InsertedScalarizedValues,
1153 PHIsToRewrite, Context),
1154 LI->getName()+".f"+Twine(FieldNo), LI);
1155 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1156 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1158 const StructType *ST =
1159 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1162 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1163 PN->getName()+".f"+Twine(FieldNo), PN);
1164 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1166 llvm_unreachable("Unknown usable value");
1170 return FieldVals[FieldNo] = Result;
1173 /// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1174 /// the load, rewrite the derived value to use the HeapSRoA'd load.
1175 static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1176 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1177 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
1178 LLVMContext &Context) {
1179 // If this is a comparison against null, handle it.
1180 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1181 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1182 // If we have a setcc of the loaded pointer, we can use a setcc of any
1184 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1185 InsertedScalarizedValues, PHIsToRewrite,
1188 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
1189 Constant::getNullValue(NPtr->getType()),
1191 SCI->replaceAllUsesWith(New);
1192 SCI->eraseFromParent();
1196 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
1197 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1198 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1199 && "Unexpected GEPI!");
1201 // Load the pointer for this field.
1202 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1203 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1204 InsertedScalarizedValues, PHIsToRewrite,
1207 // Create the new GEP idx vector.
1208 SmallVector<Value*, 8> GEPIdx;
1209 GEPIdx.push_back(GEPI->getOperand(1));
1210 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1212 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1213 GEPIdx.begin(), GEPIdx.end(),
1214 GEPI->getName(), GEPI);
1215 GEPI->replaceAllUsesWith(NGEPI);
1216 GEPI->eraseFromParent();
1220 // Recursively transform the users of PHI nodes. This will lazily create the
1221 // PHIs that are needed for individual elements. Keep track of what PHIs we
1222 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1223 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1224 // already been seen first by another load, so its uses have already been
1226 PHINode *PN = cast<PHINode>(LoadUser);
1228 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1229 tie(InsertPos, Inserted) =
1230 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1231 if (!Inserted) return;
1233 // If this is the first time we've seen this PHI, recursively process all
1235 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1236 Instruction *User = cast<Instruction>(*UI++);
1237 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1242 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1243 /// is a value loaded from the global. Eliminate all uses of Ptr, making them
1244 /// use FieldGlobals instead. All uses of loaded values satisfy
1245 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
1246 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
1247 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1248 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
1249 LLVMContext &Context) {
1250 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
1252 Instruction *User = cast<Instruction>(*UI++);
1253 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1257 if (Load->use_empty()) {
1258 Load->eraseFromParent();
1259 InsertedScalarizedValues.erase(Load);
1263 /// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1264 /// it up into multiple allocations of arrays of the fields.
1265 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI,
1266 LLVMContext &Context){
1267 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
1268 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1270 // There is guaranteed to be at least one use of the malloc (storing
1271 // it into GV). If there are other uses, change them to be uses of
1272 // the global to simplify later code. This also deletes the store
1274 ReplaceUsesOfMallocWithGlobal(MI, GV);
1276 // Okay, at this point, there are no users of the malloc. Insert N
1277 // new mallocs at the same place as MI, and N globals.
1278 std::vector<Value*> FieldGlobals;
1279 std::vector<MallocInst*> FieldMallocs;
1281 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1282 const Type *FieldTy = STy->getElementType(FieldNo);
1283 const Type *PFieldTy = PointerType::getUnqual(FieldTy);
1285 GlobalVariable *NGV =
1286 new GlobalVariable(*GV->getParent(),
1287 PFieldTy, false, GlobalValue::InternalLinkage,
1288 Constant::getNullValue(PFieldTy),
1289 GV->getName() + ".f" + Twine(FieldNo), GV,
1290 GV->isThreadLocal());
1291 FieldGlobals.push_back(NGV);
1293 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
1294 MI->getName() + ".f" + Twine(FieldNo), MI);
1295 FieldMallocs.push_back(NMI);
1296 new StoreInst(NMI, NGV, MI);
1299 // The tricky aspect of this transformation is handling the case when malloc
1300 // fails. In the original code, malloc failing would set the result pointer
1301 // of malloc to null. In this case, some mallocs could succeed and others
1302 // could fail. As such, we emit code that looks like this:
1303 // F0 = malloc(field0)
1304 // F1 = malloc(field1)
1305 // F2 = malloc(field2)
1306 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1307 // if (F0) { free(F0); F0 = 0; }
1308 // if (F1) { free(F1); F1 = 0; }
1309 // if (F2) { free(F2); F2 = 0; }
1311 Value *RunningOr = 0;
1312 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1313 Value *Cond = new ICmpInst(MI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1314 Constant::getNullValue(FieldMallocs[i]->getType()),
1317 RunningOr = Cond; // First seteq
1319 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
1322 // Split the basic block at the old malloc.
1323 BasicBlock *OrigBB = MI->getParent();
1324 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1326 // Create the block to check the first condition. Put all these blocks at the
1327 // end of the function as they are unlikely to be executed.
1328 BasicBlock *NullPtrBlock = BasicBlock::Create(Context, "malloc_ret_null",
1329 OrigBB->getParent());
1331 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1332 // branch on RunningOr.
1333 OrigBB->getTerminator()->eraseFromParent();
1334 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1336 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1337 // pointer, because some may be null while others are not.
1338 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1339 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1340 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1341 Constant::getNullValue(GVVal->getType()),
1343 BasicBlock *FreeBlock = BasicBlock::Create(Context, "free_it",
1344 OrigBB->getParent());
1345 BasicBlock *NextBlock = BasicBlock::Create(Context, "next",
1346 OrigBB->getParent());
1347 BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
1349 // Fill in FreeBlock.
1350 new FreeInst(GVVal, FreeBlock);
1351 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1353 BranchInst::Create(NextBlock, FreeBlock);
1355 NullPtrBlock = NextBlock;
1358 BranchInst::Create(ContBB, NullPtrBlock);
1360 // MI is no longer needed, remove it.
1361 MI->eraseFromParent();
1363 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1364 /// update all uses of the load, keep track of what scalarized loads are
1365 /// inserted for a given load.
1366 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1367 InsertedScalarizedValues[GV] = FieldGlobals;
1369 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1371 // Okay, the malloc site is completely handled. All of the uses of GV are now
1372 // loads, and all uses of those loads are simple. Rewrite them to use loads
1373 // of the per-field globals instead.
1374 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1375 Instruction *User = cast<Instruction>(*UI++);
1377 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1378 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite,
1383 // Must be a store of null.
1384 StoreInst *SI = cast<StoreInst>(User);
1385 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1386 "Unexpected heap-sra user!");
1388 // Insert a store of null into each global.
1389 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1390 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1391 Constant *Null = Constant::getNullValue(PT->getElementType());
1392 new StoreInst(Null, FieldGlobals[i], SI);
1394 // Erase the original store.
1395 SI->eraseFromParent();
1398 // While we have PHIs that are interesting to rewrite, do it.
1399 while (!PHIsToRewrite.empty()) {
1400 PHINode *PN = PHIsToRewrite.back().first;
1401 unsigned FieldNo = PHIsToRewrite.back().second;
1402 PHIsToRewrite.pop_back();
1403 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1404 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1406 // Add all the incoming values. This can materialize more phis.
1407 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1408 Value *InVal = PN->getIncomingValue(i);
1409 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1410 PHIsToRewrite, Context);
1411 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1415 // Drop all inter-phi links and any loads that made it this far.
1416 for (DenseMap<Value*, std::vector<Value*> >::iterator
1417 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1419 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1420 PN->dropAllReferences();
1421 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1422 LI->dropAllReferences();
1425 // Delete all the phis and loads now that inter-references are dead.
1426 for (DenseMap<Value*, std::vector<Value*> >::iterator
1427 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1429 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1430 PN->eraseFromParent();
1431 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1432 LI->eraseFromParent();
1435 // The old global is now dead, remove it.
1436 GV->eraseFromParent();
1439 return cast<GlobalVariable>(FieldGlobals[0]);
1442 /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1443 /// pointer global variable with a single value stored it that is a malloc or
1445 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1447 Module::global_iterator &GVI,
1449 LLVMContext &Context) {
1450 // If this is a malloc of an abstract type, don't touch it.
1451 if (!MI->getAllocatedType()->isSized())
1454 // We can't optimize this global unless all uses of it are *known* to be
1455 // of the malloc value, not of the null initializer value (consider a use
1456 // that compares the global's value against zero to see if the malloc has
1457 // been reached). To do this, we check to see if all uses of the global
1458 // would trap if the global were null: this proves that they must all
1459 // happen after the malloc.
1460 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1463 // We can't optimize this if the malloc itself is used in a complex way,
1464 // for example, being stored into multiple globals. This allows the
1465 // malloc to be stored into the specified global, loaded setcc'd, and
1466 // GEP'd. These are all things we could transform to using the global
1469 SmallPtrSet<PHINode*, 8> PHIs;
1470 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1475 // If we have a global that is only initialized with a fixed size malloc,
1476 // transform the program to use global memory instead of malloc'd memory.
1477 // This eliminates dynamic allocation, avoids an indirection accessing the
1478 // data, and exposes the resultant global to further GlobalOpt.
1479 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1480 // Restrict this transformation to only working on small allocations
1481 // (2048 bytes currently), as we don't want to introduce a 16M global or
1484 NElements->getZExtValue()*
1485 TD->getTypeAllocSize(MI->getAllocatedType()) < 2048) {
1486 GVI = OptimizeGlobalAddressOfMalloc(GV, MI, Context);
1491 // If the allocation is an array of structures, consider transforming this
1492 // into multiple malloc'd arrays, one for each field. This is basically
1493 // SRoA for malloc'd memory.
1494 const Type *AllocTy = MI->getAllocatedType();
1496 // If this is an allocation of a fixed size array of structs, analyze as a
1497 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1498 if (!MI->isArrayAllocation())
1499 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1500 AllocTy = AT->getElementType();
1502 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
1503 // This the structure has an unreasonable number of fields, leave it
1505 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1506 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
1508 // If this is a fixed size array, transform the Malloc to be an alloc of
1509 // structs. malloc [100 x struct],1 -> malloc struct, 100
1510 if (const ArrayType *AT = dyn_cast<ArrayType>(MI->getAllocatedType())) {
1512 new MallocInst(AllocSTy,
1513 ConstantInt::get(Type::getInt32Ty(Context),
1514 AT->getNumElements()),
1516 NewMI->takeName(MI);
1517 Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
1518 MI->replaceAllUsesWith(Cast);
1519 MI->eraseFromParent();
1523 GVI = PerformHeapAllocSRoA(GV, MI, Context);
1531 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1532 // that only one value (besides its initializer) is ever stored to the global.
1533 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1534 Module::global_iterator &GVI,
1535 TargetData *TD, LLVMContext &Context) {
1536 // Ignore no-op GEPs and bitcasts.
1537 StoredOnceVal = StoredOnceVal->stripPointerCasts();
1539 // If we are dealing with a pointer global that is initialized to null and
1540 // only has one (non-null) value stored into it, then we can optimize any
1541 // users of the loaded value (often calls and loads) that would trap if the
1543 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1544 GV->getInitializer()->isNullValue()) {
1545 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1546 if (GV->getInitializer()->getType() != SOVC->getType())
1548 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1550 // Optimize away any trapping uses of the loaded value.
1551 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, Context))
1553 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
1554 if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD, Context))
1562 /// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1563 /// two values ever stored into GV are its initializer and OtherVal. See if we
1564 /// can shrink the global into a boolean and select between the two values
1565 /// whenever it is used. This exposes the values to other scalar optimizations.
1566 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal,
1567 LLVMContext &Context) {
1568 const Type *GVElType = GV->getType()->getElementType();
1570 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1571 // an FP value, pointer or vector, don't do this optimization because a select
1572 // between them is very expensive and unlikely to lead to later
1573 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1574 // where v1 and v2 both require constant pool loads, a big loss.
1575 if (GVElType == Type::getInt1Ty(Context) || GVElType->isFloatingPoint() ||
1576 isa<PointerType>(GVElType) || isa<VectorType>(GVElType))
1579 // Walk the use list of the global seeing if all the uses are load or store.
1580 // If there is anything else, bail out.
1581 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
1582 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
1585 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1587 // Create the new global, initializing it to false.
1588 GlobalVariable *NewGV = new GlobalVariable(Context,
1589 Type::getInt1Ty(Context), false,
1590 GlobalValue::InternalLinkage, ConstantInt::getFalse(Context),
1592 GV->isThreadLocal());
1593 GV->getParent()->getGlobalList().insert(GV, NewGV);
1595 Constant *InitVal = GV->getInitializer();
1596 assert(InitVal->getType() != Type::getInt1Ty(Context) &&
1597 "No reason to shrink to bool!");
1599 // If initialized to zero and storing one into the global, we can use a cast
1600 // instead of a select to synthesize the desired value.
1601 bool IsOneZero = false;
1602 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1603 IsOneZero = InitVal->isNullValue() && CI->isOne();
1605 while (!GV->use_empty()) {
1606 Instruction *UI = cast<Instruction>(GV->use_back());
1607 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1608 // Change the store into a boolean store.
1609 bool StoringOther = SI->getOperand(0) == OtherVal;
1610 // Only do this if we weren't storing a loaded value.
1612 if (StoringOther || SI->getOperand(0) == InitVal)
1613 StoreVal = ConstantInt::get(Type::getInt1Ty(Context), StoringOther);
1615 // Otherwise, we are storing a previously loaded copy. To do this,
1616 // change the copy from copying the original value to just copying the
1618 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1620 // If we're already replaced the input, StoredVal will be a cast or
1621 // select instruction. If not, it will be a load of the original
1623 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1624 assert(LI->getOperand(0) == GV && "Not a copy!");
1625 // Insert a new load, to preserve the saved value.
1626 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1628 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1629 "This is not a form that we understand!");
1630 StoreVal = StoredVal->getOperand(0);
1631 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1634 new StoreInst(StoreVal, NewGV, SI);
1636 // Change the load into a load of bool then a select.
1637 LoadInst *LI = cast<LoadInst>(UI);
1638 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1641 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1643 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1645 LI->replaceAllUsesWith(NSI);
1647 UI->eraseFromParent();
1650 GV->eraseFromParent();
1655 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1656 /// it if possible. If we make a change, return true.
1657 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1658 Module::global_iterator &GVI) {
1659 SmallPtrSet<PHINode*, 16> PHIUsers;
1661 GV->removeDeadConstantUsers();
1663 if (GV->use_empty()) {
1664 DOUT << "GLOBAL DEAD: " << *GV;
1665 GV->eraseFromParent();
1670 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1672 cerr << "Global: " << *GV;
1673 cerr << " isLoaded = " << GS.isLoaded << "\n";
1674 cerr << " StoredType = ";
1675 switch (GS.StoredType) {
1676 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1677 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1678 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1679 case GlobalStatus::isStored: cerr << "stored\n"; break;
1681 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1682 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
1683 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1684 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
1686 cerr << " HasMultipleAccessingFunctions = "
1687 << GS.HasMultipleAccessingFunctions << "\n";
1688 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
1692 // If this is a first class global and has only one accessing function
1693 // and this function is main (which we know is not recursive we can make
1694 // this global a local variable) we replace the global with a local alloca
1695 // in this function.
1697 // NOTE: It doesn't make sense to promote non single-value types since we
1698 // are just replacing static memory to stack memory.
1700 // If the global is in different address space, don't bring it to stack.
1701 if (!GS.HasMultipleAccessingFunctions &&
1702 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1703 GV->getType()->getElementType()->isSingleValueType() &&
1704 GS.AccessingFunction->getName() == "main" &&
1705 GS.AccessingFunction->hasExternalLinkage() &&
1706 GV->getType()->getAddressSpace() == 0) {
1707 DOUT << "LOCALIZING GLOBAL: " << *GV;
1708 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1709 const Type* ElemTy = GV->getType()->getElementType();
1710 // FIXME: Pass Global's alignment when globals have alignment
1711 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1712 if (!isa<UndefValue>(GV->getInitializer()))
1713 new StoreInst(GV->getInitializer(), Alloca, FirstI);
1715 GV->replaceAllUsesWith(Alloca);
1716 GV->eraseFromParent();
1721 // If the global is never loaded (but may be stored to), it is dead.
1724 DOUT << "GLOBAL NEVER LOADED: " << *GV;
1726 // Delete any stores we can find to the global. We may not be able to
1727 // make it completely dead though.
1728 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(),
1731 // If the global is dead now, delete it.
1732 if (GV->use_empty()) {
1733 GV->eraseFromParent();
1739 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1740 DOUT << "MARKING CONSTANT: " << *GV;
1741 GV->setConstant(true);
1743 // Clean up any obviously simplifiable users now.
1744 CleanupConstantGlobalUsers(GV, GV->getInitializer(), GV->getContext());
1746 // If the global is dead now, just nuke it.
1747 if (GV->use_empty()) {
1748 DOUT << " *** Marking constant allowed us to simplify "
1749 << "all users and delete global!\n";
1750 GV->eraseFromParent();
1756 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1757 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1758 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD,
1759 GV->getContext())) {
1760 GVI = FirstNewGV; // Don't skip the newly produced globals!
1763 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1764 // If the initial value for the global was an undef value, and if only
1765 // one other value was stored into it, we can just change the
1766 // initializer to be the stored value, then delete all stores to the
1767 // global. This allows us to mark it constant.
1768 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1769 if (isa<UndefValue>(GV->getInitializer())) {
1770 // Change the initial value here.
1771 GV->setInitializer(SOVConstant);
1773 // Clean up any obviously simplifiable users now.
1774 CleanupConstantGlobalUsers(GV, GV->getInitializer(),
1777 if (GV->use_empty()) {
1778 DOUT << " *** Substituting initializer allowed us to "
1779 << "simplify all users and delete global!\n";
1780 GV->eraseFromParent();
1789 // Try to optimize globals based on the knowledge that only one value
1790 // (besides its initializer) is ever stored to the global.
1791 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1792 getAnalysisIfAvailable<TargetData>(),
1796 // Otherwise, if the global was not a boolean, we can shrink it to be a
1798 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1799 if (TryToShrinkGlobalToBoolean(GV, SOVConstant, GV->getContext())) {
1808 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1809 /// function, changing them to FastCC.
1810 static void ChangeCalleesToFastCall(Function *F) {
1811 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1812 CallSite User(cast<Instruction>(*UI));
1813 User.setCallingConv(CallingConv::Fast);
1817 static AttrListPtr StripNest(const AttrListPtr &Attrs) {
1818 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1819 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
1822 // There can be only one.
1823 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
1829 static void RemoveNestAttribute(Function *F) {
1830 F->setAttributes(StripNest(F->getAttributes()));
1831 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1832 CallSite User(cast<Instruction>(*UI));
1833 User.setAttributes(StripNest(User.getAttributes()));
1837 bool GlobalOpt::OptimizeFunctions(Module &M) {
1838 bool Changed = false;
1839 // Optimize functions.
1840 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1842 // Functions without names cannot be referenced outside this module.
1843 if (!F->hasName() && !F->isDeclaration())
1844 F->setLinkage(GlobalValue::InternalLinkage);
1845 F->removeDeadConstantUsers();
1846 if (F->use_empty() && (F->hasLocalLinkage() ||
1847 F->hasLinkOnceLinkage())) {
1848 M.getFunctionList().erase(F);
1851 } else if (F->hasLocalLinkage()) {
1852 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1853 !F->hasAddressTaken()) {
1854 // If this function has C calling conventions, is not a varargs
1855 // function, and is only called directly, promote it to use the Fast
1856 // calling convention.
1857 F->setCallingConv(CallingConv::Fast);
1858 ChangeCalleesToFastCall(F);
1863 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
1864 !F->hasAddressTaken()) {
1865 // The function is not used by a trampoline intrinsic, so it is safe
1866 // to remove the 'nest' attribute.
1867 RemoveNestAttribute(F);
1876 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1877 bool Changed = false;
1878 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1880 GlobalVariable *GV = GVI++;
1881 // Global variables without names cannot be referenced outside this module.
1882 if (!GV->hasName() && !GV->isDeclaration())
1883 GV->setLinkage(GlobalValue::InternalLinkage);
1884 if (!GV->isConstant() && GV->hasLocalLinkage() &&
1885 GV->hasInitializer())
1886 Changed |= ProcessInternalGlobal(GV, GVI);
1891 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1892 /// initializers have an init priority of 65535.
1893 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1894 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1896 if (I->getName() == "llvm.global_ctors") {
1897 // Found it, verify it's an array of { int, void()* }.
1898 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1900 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1901 if (!STy || STy->getNumElements() != 2 ||
1902 STy->getElementType(0) != Type::getInt32Ty(M.getContext())) return 0;
1903 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1904 if (!PFTy) return 0;
1905 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1906 if (!FTy || FTy->getReturnType() != Type::getVoidTy(M.getContext()) ||
1907 FTy->isVarArg() || FTy->getNumParams() != 0)
1910 // Verify that the initializer is simple enough for us to handle.
1911 if (!I->hasInitializer()) return 0;
1912 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1914 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1915 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
1916 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1919 // Must have a function or null ptr.
1920 if (!isa<Function>(CS->getOperand(1)))
1923 // Init priority must be standard.
1924 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1925 if (!CI || CI->getZExtValue() != 65535)
1936 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1937 /// return a list of the functions and null terminator as a vector.
1938 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1939 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1940 std::vector<Function*> Result;
1941 Result.reserve(CA->getNumOperands());
1942 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1943 ConstantStruct *CS = cast<ConstantStruct>(*i);
1944 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1949 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1950 /// specified array, returning the new global to use.
1951 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1952 const std::vector<Function*> &Ctors,
1953 LLVMContext &Context) {
1954 // If we made a change, reassemble the initializer list.
1955 std::vector<Constant*> CSVals;
1956 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(Context), 65535));
1957 CSVals.push_back(0);
1959 // Create the new init list.
1960 std::vector<Constant*> CAList;
1961 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1963 CSVals[1] = Ctors[i];
1965 const Type *FTy = FunctionType::get(Type::getVoidTy(Context), false);
1966 const PointerType *PFTy = PointerType::getUnqual(FTy);
1967 CSVals[1] = Constant::getNullValue(PFTy);
1968 CSVals[0] = ConstantInt::get(Type::getInt32Ty(Context), 2147483647);
1970 CAList.push_back(ConstantStruct::get(Context, CSVals));
1973 // Create the array initializer.
1974 const Type *StructTy =
1975 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1976 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
1977 CAList.size()), CAList);
1979 // If we didn't change the number of elements, don't create a new GV.
1980 if (CA->getType() == GCL->getInitializer()->getType()) {
1981 GCL->setInitializer(CA);
1985 // Create the new global and insert it next to the existing list.
1986 GlobalVariable *NGV = new GlobalVariable(Context, CA->getType(),
1988 GCL->getLinkage(), CA, "",
1989 GCL->isThreadLocal());
1990 GCL->getParent()->getGlobalList().insert(GCL, NGV);
1993 // Nuke the old list, replacing any uses with the new one.
1994 if (!GCL->use_empty()) {
1996 if (V->getType() != GCL->getType())
1997 V = ConstantExpr::getBitCast(V, GCL->getType());
1998 GCL->replaceAllUsesWith(V);
2000 GCL->eraseFromParent();
2009 static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
2011 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2012 Constant *R = ComputedValues[V];
2013 assert(R && "Reference to an uncomputed value!");
2017 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2018 /// enough for us to understand. In particular, if it is a cast of something,
2019 /// we punt. We basically just support direct accesses to globals and GEP's of
2020 /// globals. This should be kept up to date with CommitValueTo.
2021 static bool isSimpleEnoughPointerToCommit(Constant *C, LLVMContext &Context) {
2022 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
2023 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
2024 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
2025 return !GV->isDeclaration(); // reject external globals.
2027 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2028 // Handle a constantexpr gep.
2029 if (CE->getOpcode() == Instruction::GetElementPtr &&
2030 isa<GlobalVariable>(CE->getOperand(0))) {
2031 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2032 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
2033 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
2034 return GV->hasInitializer() &&
2035 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
2041 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2042 /// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2043 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2044 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2045 ConstantExpr *Addr, unsigned OpNo,
2046 LLVMContext &Context) {
2047 // Base case of the recursion.
2048 if (OpNo == Addr->getNumOperands()) {
2049 assert(Val->getType() == Init->getType() && "Type mismatch!");
2053 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2054 std::vector<Constant*> Elts;
2056 // Break up the constant into its elements.
2057 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2058 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2059 Elts.push_back(cast<Constant>(*i));
2060 } else if (isa<ConstantAggregateZero>(Init)) {
2061 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2062 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
2063 } else if (isa<UndefValue>(Init)) {
2064 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2065 Elts.push_back(UndefValue::get(STy->getElementType(i)));
2067 llvm_unreachable("This code is out of sync with "
2068 " ConstantFoldLoadThroughGEPConstantExpr");
2071 // Replace the element that we are supposed to.
2072 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2073 unsigned Idx = CU->getZExtValue();
2074 assert(Idx < STy->getNumElements() && "Struct index out of range!");
2075 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1, Context);
2077 // Return the modified struct.
2078 return ConstantStruct::get(Context, &Elts[0], Elts.size(), STy->isPacked());
2080 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2081 const ArrayType *ATy = cast<ArrayType>(Init->getType());
2083 // Break up the array into elements.
2084 std::vector<Constant*> Elts;
2085 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2086 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2087 Elts.push_back(cast<Constant>(*i));
2088 } else if (isa<ConstantAggregateZero>(Init)) {
2089 Constant *Elt = Constant::getNullValue(ATy->getElementType());
2090 Elts.assign(ATy->getNumElements(), Elt);
2091 } else if (isa<UndefValue>(Init)) {
2092 Constant *Elt = UndefValue::get(ATy->getElementType());
2093 Elts.assign(ATy->getNumElements(), Elt);
2095 llvm_unreachable("This code is out of sync with "
2096 " ConstantFoldLoadThroughGEPConstantExpr");
2099 assert(CI->getZExtValue() < ATy->getNumElements());
2100 Elts[CI->getZExtValue()] =
2101 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1, Context);
2102 return ConstantArray::get(ATy, Elts);
2106 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
2107 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2108 static void CommitValueTo(Constant *Val, Constant *Addr,
2109 LLVMContext &Context) {
2110 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2111 assert(GV->hasInitializer());
2112 GV->setInitializer(Val);
2116 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2117 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2119 Constant *Init = GV->getInitializer();
2120 Init = EvaluateStoreInto(Init, Val, CE, 2, Context);
2121 GV->setInitializer(Init);
2124 /// ComputeLoadResult - Return the value that would be computed by a load from
2125 /// P after the stores reflected by 'memory' have been performed. If we can't
2126 /// decide, return null.
2127 static Constant *ComputeLoadResult(Constant *P,
2128 const DenseMap<Constant*, Constant*> &Memory,
2129 LLVMContext &Context) {
2130 // If this memory location has been recently stored, use the stored value: it
2131 // is the most up-to-date.
2132 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
2133 if (I != Memory.end()) return I->second;
2136 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2137 if (GV->hasInitializer())
2138 return GV->getInitializer();
2142 // Handle a constantexpr getelementptr.
2143 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2144 if (CE->getOpcode() == Instruction::GetElementPtr &&
2145 isa<GlobalVariable>(CE->getOperand(0))) {
2146 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2147 if (GV->hasInitializer())
2148 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
2152 return 0; // don't know how to evaluate.
2155 /// EvaluateFunction - Evaluate a call to function F, returning true if
2156 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2157 /// arguments for the function.
2158 static bool EvaluateFunction(Function *F, Constant *&RetVal,
2159 const std::vector<Constant*> &ActualArgs,
2160 std::vector<Function*> &CallStack,
2161 DenseMap<Constant*, Constant*> &MutatedMemory,
2162 std::vector<GlobalVariable*> &AllocaTmps) {
2163 // Check to see if this function is already executing (recursion). If so,
2164 // bail out. TODO: we might want to accept limited recursion.
2165 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2168 LLVMContext &Context = F->getContext();
2170 CallStack.push_back(F);
2172 /// Values - As we compute SSA register values, we store their contents here.
2173 DenseMap<Value*, Constant*> Values;
2175 // Initialize arguments to the incoming values specified.
2177 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2179 Values[AI] = ActualArgs[ArgNo];
2181 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2182 /// we can only evaluate any one basic block at most once. This set keeps
2183 /// track of what we have executed so we can detect recursive cases etc.
2184 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2186 // CurInst - The current instruction we're evaluating.
2187 BasicBlock::iterator CurInst = F->begin()->begin();
2189 // This is the main evaluation loop.
2191 Constant *InstResult = 0;
2193 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2194 if (SI->isVolatile()) return false; // no volatile accesses.
2195 Constant *Ptr = getVal(Values, SI->getOperand(1));
2196 if (!isSimpleEnoughPointerToCommit(Ptr, Context))
2197 // If this is too complex for us to commit, reject it.
2199 Constant *Val = getVal(Values, SI->getOperand(0));
2200 MutatedMemory[Ptr] = Val;
2201 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2202 InstResult = ConstantExpr::get(BO->getOpcode(),
2203 getVal(Values, BO->getOperand(0)),
2204 getVal(Values, BO->getOperand(1)));
2205 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2206 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2207 getVal(Values, CI->getOperand(0)),
2208 getVal(Values, CI->getOperand(1)));
2209 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
2210 InstResult = ConstantExpr::getCast(CI->getOpcode(),
2211 getVal(Values, CI->getOperand(0)),
2213 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2215 ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
2216 getVal(Values, SI->getOperand(1)),
2217 getVal(Values, SI->getOperand(2)));
2218 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2219 Constant *P = getVal(Values, GEP->getOperand(0));
2220 SmallVector<Constant*, 8> GEPOps;
2221 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2223 GEPOps.push_back(getVal(Values, *i));
2225 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
2226 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2227 if (LI->isVolatile()) return false; // no volatile accesses.
2228 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
2229 MutatedMemory, Context);
2230 if (InstResult == 0) return false; // Could not evaluate load.
2231 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2232 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
2233 const Type *Ty = AI->getType()->getElementType();
2234 AllocaTmps.push_back(new GlobalVariable(Context, Ty, false,
2235 GlobalValue::InternalLinkage,
2236 UndefValue::get(Ty),
2238 InstResult = AllocaTmps.back();
2239 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
2241 // Debug info can safely be ignored here.
2242 if (isa<DbgInfoIntrinsic>(CI)) {
2247 // Cannot handle inline asm.
2248 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2250 // Resolve function pointers.
2251 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2252 if (!Callee) return false; // Cannot resolve.
2254 std::vector<Constant*> Formals;
2255 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2257 Formals.push_back(getVal(Values, *i));
2259 if (Callee->isDeclaration()) {
2260 // If this is a function we can constant fold, do it.
2261 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
2268 if (Callee->getFunctionType()->isVarArg())
2272 // Execute the call, if successful, use the return value.
2273 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2274 MutatedMemory, AllocaTmps))
2276 InstResult = RetVal;
2278 } else if (isa<TerminatorInst>(CurInst)) {
2279 BasicBlock *NewBB = 0;
2280 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2281 if (BI->isUnconditional()) {
2282 NewBB = BI->getSuccessor(0);
2285 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
2286 if (!Cond) return false; // Cannot determine.
2288 NewBB = BI->getSuccessor(!Cond->getZExtValue());
2290 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2292 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
2293 if (!Val) return false; // Cannot determine.
2294 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2295 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
2296 if (RI->getNumOperands())
2297 RetVal = getVal(Values, RI->getOperand(0));
2299 CallStack.pop_back(); // return from fn.
2300 return true; // We succeeded at evaluating this ctor!
2302 // invoke, unwind, unreachable.
2303 return false; // Cannot handle this terminator.
2306 // Okay, we succeeded in evaluating this control flow. See if we have
2307 // executed the new block before. If so, we have a looping function,
2308 // which we cannot evaluate in reasonable time.
2309 if (!ExecutedBlocks.insert(NewBB))
2310 return false; // looped!
2312 // Okay, we have never been in this block before. Check to see if there
2313 // are any PHI nodes. If so, evaluate them with information about where
2315 BasicBlock *OldBB = CurInst->getParent();
2316 CurInst = NewBB->begin();
2318 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2319 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2321 // Do NOT increment CurInst. We know that the terminator had no value.
2324 // Did not know how to evaluate this!
2328 if (!CurInst->use_empty())
2329 Values[CurInst] = InstResult;
2331 // Advance program counter.
2336 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2337 /// we can. Return true if we can, false otherwise.
2338 static bool EvaluateStaticConstructor(Function *F) {
2339 /// MutatedMemory - For each store we execute, we update this map. Loads
2340 /// check this to get the most up-to-date value. If evaluation is successful,
2341 /// this state is committed to the process.
2342 DenseMap<Constant*, Constant*> MutatedMemory;
2344 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2345 /// to represent its body. This vector is needed so we can delete the
2346 /// temporary globals when we are done.
2347 std::vector<GlobalVariable*> AllocaTmps;
2349 /// CallStack - This is used to detect recursion. In pathological situations
2350 /// we could hit exponential behavior, but at least there is nothing
2352 std::vector<Function*> CallStack;
2354 // Call the function.
2355 Constant *RetValDummy;
2356 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
2357 CallStack, MutatedMemory, AllocaTmps);
2359 // We succeeded at evaluation: commit the result.
2360 DEBUG(errs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2361 << F->getName() << "' to " << MutatedMemory.size()
2363 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
2364 E = MutatedMemory.end(); I != E; ++I)
2365 CommitValueTo(I->second, I->first, F->getContext());
2368 // At this point, we are done interpreting. If we created any 'alloca'
2369 // temporaries, release them now.
2370 while (!AllocaTmps.empty()) {
2371 GlobalVariable *Tmp = AllocaTmps.back();
2372 AllocaTmps.pop_back();
2374 // If there are still users of the alloca, the program is doing something
2375 // silly, e.g. storing the address of the alloca somewhere and using it
2376 // later. Since this is undefined, we'll just make it be null.
2377 if (!Tmp->use_empty())
2378 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2387 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2388 /// Return true if anything changed.
2389 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2390 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2391 bool MadeChange = false;
2392 if (Ctors.empty()) return false;
2394 // Loop over global ctors, optimizing them when we can.
2395 for (unsigned i = 0; i != Ctors.size(); ++i) {
2396 Function *F = Ctors[i];
2397 // Found a null terminator in the middle of the list, prune off the rest of
2400 if (i != Ctors.size()-1) {
2407 // We cannot simplify external ctor functions.
2408 if (F->empty()) continue;
2410 // If we can evaluate the ctor at compile time, do.
2411 if (EvaluateStaticConstructor(F)) {
2412 Ctors.erase(Ctors.begin()+i);
2415 ++NumCtorsEvaluated;
2420 if (!MadeChange) return false;
2422 GCL = InstallGlobalCtors(GCL, Ctors, GCL->getContext());
2426 bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
2427 bool Changed = false;
2429 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
2431 Module::alias_iterator J = I++;
2432 // Aliases without names cannot be referenced outside this module.
2433 if (!J->hasName() && !J->isDeclaration())
2434 J->setLinkage(GlobalValue::InternalLinkage);
2435 // If the aliasee may change at link time, nothing can be done - bail out.
2436 if (J->mayBeOverridden())
2439 Constant *Aliasee = J->getAliasee();
2440 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2441 Target->removeDeadConstantUsers();
2442 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2444 // Make all users of the alias use the aliasee instead.
2445 if (!J->use_empty()) {
2446 J->replaceAllUsesWith(Aliasee);
2447 ++NumAliasesResolved;
2451 // If the aliasee has internal linkage, give it the name and linkage
2452 // of the alias, and delete the alias. This turns:
2453 // define internal ... @f(...)
2454 // @a = alias ... @f
2456 // define ... @a(...)
2457 if (!Target->hasLocalLinkage())
2460 // The transform is only useful if the alias does not have internal linkage.
2461 if (J->hasLocalLinkage())
2464 // Do not perform the transform if multiple aliases potentially target the
2465 // aliasee. This check also ensures that it is safe to replace the section
2466 // and other attributes of the aliasee with those of the alias.
2470 // Give the aliasee the name, linkage and other attributes of the alias.
2471 Target->takeName(J);
2472 Target->setLinkage(J->getLinkage());
2473 Target->GlobalValue::copyAttributesFrom(J);
2475 // Delete the alias.
2476 M.getAliasList().erase(J);
2477 ++NumAliasesRemoved;
2484 bool GlobalOpt::runOnModule(Module &M) {
2485 bool Changed = false;
2487 // Try to find the llvm.globalctors list.
2488 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2490 bool LocalChange = true;
2491 while (LocalChange) {
2492 LocalChange = false;
2494 // Delete functions that are trivially dead, ccc -> fastcc
2495 LocalChange |= OptimizeFunctions(M);
2497 // Optimize global_ctors list.
2499 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2501 // Optimize non-address-taken globals.
2502 LocalChange |= OptimizeGlobalVars(M);
2504 // Resolve aliases, when possible.
2505 LocalChange |= OptimizeGlobalAliases(M);
2506 Changed |= LocalChange;
2509 // TODO: Move all global ctors functions to the end of the module for code