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 #include "llvm/Transforms/IPO.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/ConstantFolding.h"
24 #include "llvm/Analysis/MemoryBuiltins.h"
25 #include "llvm/Analysis/TargetLibraryInfo.h"
26 #include "llvm/IR/CallSite.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/GetElementPtrTypeIterator.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/IR/ValueHandle.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Transforms/Utils/CtorUtils.h"
43 #include "llvm/Transforms/Utils/GlobalStatus.h"
44 #include "llvm/Transforms/Utils/ModuleUtils.h"
49 #define DEBUG_TYPE "globalopt"
51 STATISTIC(NumMarked , "Number of globals marked constant");
52 STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
53 STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
54 STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
55 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
56 STATISTIC(NumDeleted , "Number of globals deleted");
57 STATISTIC(NumFnDeleted , "Number of functions deleted");
58 STATISTIC(NumGlobUses , "Number of global uses devirtualized");
59 STATISTIC(NumLocalized , "Number of globals localized");
60 STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
61 STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
62 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
63 STATISTIC(NumNestRemoved , "Number of nest attributes removed");
64 STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
65 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
66 STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
69 struct GlobalOpt : public ModulePass {
70 void getAnalysisUsage(AnalysisUsage &AU) const override {
71 AU.addRequired<TargetLibraryInfoWrapperPass>();
73 static char ID; // Pass identification, replacement for typeid
74 GlobalOpt() : ModulePass(ID) {
75 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
78 bool runOnModule(Module &M) override;
81 bool OptimizeFunctions(Module &M);
82 bool OptimizeGlobalVars(Module &M);
83 bool OptimizeGlobalAliases(Module &M);
84 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
85 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
86 const GlobalStatus &GS);
87 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
89 TargetLibraryInfo *TLI;
90 SmallSet<const Comdat *, 8> NotDiscardableComdats;
94 char GlobalOpt::ID = 0;
95 INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
96 "Global Variable Optimizer", false, false)
97 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
98 INITIALIZE_PASS_END(GlobalOpt, "globalopt",
99 "Global Variable Optimizer", false, false)
101 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
103 /// Is this global variable possibly used by a leak checker as a root? If so,
104 /// we might not really want to eliminate the stores to it.
105 static bool isLeakCheckerRoot(GlobalVariable *GV) {
106 // A global variable is a root if it is a pointer, or could plausibly contain
107 // a pointer. There are two challenges; one is that we could have a struct
108 // the has an inner member which is a pointer. We recurse through the type to
109 // detect these (up to a point). The other is that we may actually be a union
110 // of a pointer and another type, and so our LLVM type is an integer which
111 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
112 // potentially contained here.
114 if (GV->hasPrivateLinkage())
117 SmallVector<Type *, 4> Types;
118 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
122 Type *Ty = Types.pop_back_val();
123 switch (Ty->getTypeID()) {
125 case Type::PointerTyID: return true;
126 case Type::ArrayTyID:
127 case Type::VectorTyID: {
128 SequentialType *STy = cast<SequentialType>(Ty);
129 Types.push_back(STy->getElementType());
132 case Type::StructTyID: {
133 StructType *STy = cast<StructType>(Ty);
134 if (STy->isOpaque()) return true;
135 for (StructType::element_iterator I = STy->element_begin(),
136 E = STy->element_end(); I != E; ++I) {
138 if (isa<PointerType>(InnerTy)) return true;
139 if (isa<CompositeType>(InnerTy))
140 Types.push_back(InnerTy);
145 if (--Limit == 0) return true;
146 } while (!Types.empty());
150 /// Given a value that is stored to a global but never read, determine whether
151 /// it's safe to remove the store and the chain of computation that feeds the
153 static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
155 if (isa<Constant>(V))
159 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
162 if (isAllocationFn(V, TLI))
165 Instruction *I = cast<Instruction>(V);
166 if (I->mayHaveSideEffects())
168 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
169 if (!GEP->hasAllConstantIndices())
171 } else if (I->getNumOperands() != 1) {
175 V = I->getOperand(0);
179 /// This GV is a pointer root. Loop over all users of the global and clean up
180 /// any that obviously don't assign the global a value that isn't dynamically
182 static bool CleanupPointerRootUsers(GlobalVariable *GV,
183 const TargetLibraryInfo *TLI) {
184 // A brief explanation of leak checkers. The goal is to find bugs where
185 // pointers are forgotten, causing an accumulating growth in memory
186 // usage over time. The common strategy for leak checkers is to whitelist the
187 // memory pointed to by globals at exit. This is popular because it also
188 // solves another problem where the main thread of a C++ program may shut down
189 // before other threads that are still expecting to use those globals. To
190 // handle that case, we expect the program may create a singleton and never
193 bool Changed = false;
195 // If Dead[n].first is the only use of a malloc result, we can delete its
196 // chain of computation and the store to the global in Dead[n].second.
197 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
199 // Constants can't be pointers to dynamically allocated memory.
200 for (Value::user_iterator UI = GV->user_begin(), E = GV->user_end();
203 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
204 Value *V = SI->getValueOperand();
205 if (isa<Constant>(V)) {
207 SI->eraseFromParent();
208 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
210 Dead.push_back(std::make_pair(I, SI));
212 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
213 if (isa<Constant>(MSI->getValue())) {
215 MSI->eraseFromParent();
216 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
218 Dead.push_back(std::make_pair(I, MSI));
220 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
221 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
222 if (MemSrc && MemSrc->isConstant()) {
224 MTI->eraseFromParent();
225 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
227 Dead.push_back(std::make_pair(I, MTI));
229 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
230 if (CE->use_empty()) {
231 CE->destroyConstant();
234 } else if (Constant *C = dyn_cast<Constant>(U)) {
235 if (isSafeToDestroyConstant(C)) {
236 C->destroyConstant();
237 // This could have invalidated UI, start over from scratch.
239 CleanupPointerRootUsers(GV, TLI);
245 for (int i = 0, e = Dead.size(); i != e; ++i) {
246 if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
247 Dead[i].second->eraseFromParent();
248 Instruction *I = Dead[i].first;
250 if (isAllocationFn(I, TLI))
252 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
255 I->eraseFromParent();
258 I->eraseFromParent();
265 /// We just marked GV constant. Loop over all users of the global, cleaning up
266 /// the obvious ones. This is largely just a quick scan over the use list to
267 /// clean up the easy and obvious cruft. This returns true if it made a change.
268 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
269 const DataLayout &DL,
270 TargetLibraryInfo *TLI) {
271 bool Changed = false;
272 // Note that we need to use a weak value handle for the worklist items. When
273 // we delete a constant array, we may also be holding pointer to one of its
274 // elements (or an element of one of its elements if we're dealing with an
275 // array of arrays) in the worklist.
276 SmallVector<WeakVH, 8> WorkList(V->user_begin(), V->user_end());
277 while (!WorkList.empty()) {
278 Value *UV = WorkList.pop_back_val();
282 User *U = cast<User>(UV);
284 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
286 // Replace the load with the initializer.
287 LI->replaceAllUsesWith(Init);
288 LI->eraseFromParent();
291 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
292 // Store must be unreachable or storing Init into the global.
293 SI->eraseFromParent();
295 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
296 if (CE->getOpcode() == Instruction::GetElementPtr) {
297 Constant *SubInit = nullptr;
299 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
300 Changed |= CleanupConstantGlobalUsers(CE, SubInit, DL, TLI);
301 } else if ((CE->getOpcode() == Instruction::BitCast &&
302 CE->getType()->isPointerTy()) ||
303 CE->getOpcode() == Instruction::AddrSpaceCast) {
304 // Pointer cast, delete any stores and memsets to the global.
305 Changed |= CleanupConstantGlobalUsers(CE, nullptr, DL, TLI);
308 if (CE->use_empty()) {
309 CE->destroyConstant();
312 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
313 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
314 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
315 // and will invalidate our notion of what Init is.
316 Constant *SubInit = nullptr;
317 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
318 ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(
319 ConstantFoldInstruction(GEP, DL, TLI));
320 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
321 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
323 // If the initializer is an all-null value and we have an inbounds GEP,
324 // we already know what the result of any load from that GEP is.
325 // TODO: Handle splats.
326 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
327 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
329 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, DL, TLI);
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 (isSafeToDestroyConstant(C)) {
345 C->destroyConstant();
346 CleanupConstantGlobalUsers(V, Init, DL, TLI);
354 /// Return true if the specified instruction is a safe user of a derived
355 /// expression from a global that we want to SROA.
356 static bool isSafeSROAElementUse(Value *V) {
357 // We might have a dead and dangling constant hanging off of here.
358 if (Constant *C = dyn_cast<Constant>(V))
359 return isSafeToDestroyConstant(C);
361 Instruction *I = dyn_cast<Instruction>(V);
362 if (!I) return false;
365 if (isa<LoadInst>(I)) return true;
367 // Stores *to* the pointer are ok.
368 if (StoreInst *SI = dyn_cast<StoreInst>(I))
369 return SI->getOperand(0) != V;
371 // Otherwise, it must be a GEP.
372 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
373 if (!GEPI) return false;
375 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
376 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
379 for (User *U : GEPI->users())
380 if (!isSafeSROAElementUse(U))
386 /// U is a direct user of the specified global value. Look at it and its uses
387 /// and decide whether it is safe to SROA this global.
388 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
389 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
390 if (!isa<GetElementPtrInst>(U) &&
391 (!isa<ConstantExpr>(U) ||
392 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
395 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
396 // don't like < 3 operand CE's, and we don't like non-constant integer
397 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
399 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
400 !cast<Constant>(U->getOperand(1))->isNullValue() ||
401 !isa<ConstantInt>(U->getOperand(2)))
404 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
405 ++GEPI; // Skip over the pointer index.
407 // If this is a use of an array allocation, do a bit more checking for sanity.
408 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
409 uint64_t NumElements = AT->getNumElements();
410 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
412 // Check to make sure that index falls within the array. If not,
413 // something funny is going on, so we won't do the optimization.
415 if (Idx->getZExtValue() >= NumElements)
418 // We cannot scalar repl this level of the array unless any array
419 // sub-indices are in-range constants. In particular, consider:
420 // A[0][i]. We cannot know that the user isn't doing invalid things like
421 // allowing i to index an out-of-range subscript that accesses A[1].
423 // Scalar replacing *just* the outer index of the array is probably not
424 // going to be a win anyway, so just give up.
425 for (++GEPI; // Skip array index.
428 uint64_t NumElements;
429 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
430 NumElements = SubArrayTy->getNumElements();
431 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
432 NumElements = SubVectorTy->getNumElements();
434 assert((*GEPI)->isStructTy() &&
435 "Indexed GEP type is not array, vector, or struct!");
439 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
440 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
445 for (User *UU : U->users())
446 if (!isSafeSROAElementUse(UU))
452 /// Look at all uses of the global and decide whether it is safe for us to
453 /// perform this transformation.
454 static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
455 for (User *U : GV->users())
456 if (!IsUserOfGlobalSafeForSRA(U, GV))
463 /// Perform scalar replacement of aggregates on the specified global variable.
464 /// This opens the door for other optimizations by exposing the behavior of the
465 /// program in a more fine-grained way. We have determined that this
466 /// transformation is safe already. We return the first global variable we
467 /// insert so that the caller can reprocess it.
468 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &DL) {
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 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 = DL.getABITypeAlignment(GV->getType());
485 if (StructType *STy = dyn_cast<StructType>(Ty)) {
486 NewGlobals.reserve(STy->getNumElements());
487 const StructLayout &Layout = *DL.getStructLayout(STy);
488 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
489 Constant *In = Init->getAggregateElement(i);
490 assert(In && "Couldn't get element of initializer?");
491 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
492 GlobalVariable::InternalLinkage,
493 In, GV->getName()+"."+Twine(i),
494 GV->getThreadLocalMode(),
495 GV->getType()->getAddressSpace());
496 NGV->setExternallyInitialized(GV->isExternallyInitialized());
497 Globals.insert(GV->getIterator(), NGV);
498 NewGlobals.push_back(NGV);
500 // Calculate the known alignment of the field. If the original aggregate
501 // had 256 byte alignment for example, something might depend on that:
502 // propagate info to each field.
503 uint64_t FieldOffset = Layout.getElementOffset(i);
504 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
505 if (NewAlign > DL.getABITypeAlignment(STy->getElementType(i)))
506 NGV->setAlignment(NewAlign);
508 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
509 unsigned NumElements = 0;
510 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
511 NumElements = ATy->getNumElements();
513 NumElements = cast<VectorType>(STy)->getNumElements();
515 if (NumElements > 16 && GV->hasNUsesOrMore(16))
516 return nullptr; // It's not worth it.
517 NewGlobals.reserve(NumElements);
519 uint64_t EltSize = DL.getTypeAllocSize(STy->getElementType());
520 unsigned EltAlign = DL.getABITypeAlignment(STy->getElementType());
521 for (unsigned i = 0, e = NumElements; i != e; ++i) {
522 Constant *In = Init->getAggregateElement(i);
523 assert(In && "Couldn't get element of initializer?");
525 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
526 GlobalVariable::InternalLinkage,
527 In, GV->getName()+"."+Twine(i),
528 GV->getThreadLocalMode(),
529 GV->getType()->getAddressSpace());
530 NGV->setExternallyInitialized(GV->isExternallyInitialized());
531 Globals.insert(GV->getIterator(), NGV);
532 NewGlobals.push_back(NGV);
534 // Calculate the known alignment of the field. If the original aggregate
535 // had 256 byte alignment for example, something might depend on that:
536 // propagate info to each field.
537 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
538 if (NewAlign > EltAlign)
539 NGV->setAlignment(NewAlign);
543 if (NewGlobals.empty())
546 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV << "\n");
548 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
550 // Loop over all of the uses of the global, replacing the constantexpr geps,
551 // with smaller constantexpr geps or direct references.
552 while (!GV->use_empty()) {
553 User *GEP = GV->user_back();
554 assert(((isa<ConstantExpr>(GEP) &&
555 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
556 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
558 // Ignore the 1th operand, which has to be zero or else the program is quite
559 // broken (undefined). Get the 2nd operand, which is the structure or array
561 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
562 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
564 Value *NewPtr = NewGlobals[Val];
565 Type *NewTy = NewGlobals[Val]->getValueType();
567 // Form a shorter GEP if needed.
568 if (GEP->getNumOperands() > 3) {
569 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
570 SmallVector<Constant*, 8> Idxs;
571 Idxs.push_back(NullInt);
572 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
573 Idxs.push_back(CE->getOperand(i));
575 ConstantExpr::getGetElementPtr(NewTy, cast<Constant>(NewPtr), Idxs);
577 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
578 SmallVector<Value*, 8> Idxs;
579 Idxs.push_back(NullInt);
580 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
581 Idxs.push_back(GEPI->getOperand(i));
582 NewPtr = GetElementPtrInst::Create(
583 NewTy, NewPtr, Idxs, GEPI->getName() + "." + Twine(Val), GEPI);
586 GEP->replaceAllUsesWith(NewPtr);
588 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
589 GEPI->eraseFromParent();
591 cast<ConstantExpr>(GEP)->destroyConstant();
594 // Delete the old global, now that it is dead.
598 // Loop over the new globals array deleting any globals that are obviously
599 // dead. This can arise due to scalarization of a structure or an array that
600 // has elements that are dead.
601 unsigned FirstGlobal = 0;
602 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
603 if (NewGlobals[i]->use_empty()) {
604 Globals.erase(NewGlobals[i]);
605 if (FirstGlobal == i) ++FirstGlobal;
608 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : nullptr;
611 /// Return true if all users of the specified value will trap if the value is
612 /// dynamically null. PHIs keeps track of any phi nodes we've seen to avoid
613 /// reprocessing them.
614 static bool AllUsesOfValueWillTrapIfNull(const Value *V,
615 SmallPtrSetImpl<const PHINode*> &PHIs) {
616 for (const User *U : V->users())
617 if (isa<LoadInst>(U)) {
619 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
620 if (SI->getOperand(0) == V) {
621 //cerr << "NONTRAPPING USE: " << *U;
622 return false; // Storing the value.
624 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
625 if (CI->getCalledValue() != V) {
626 //cerr << "NONTRAPPING USE: " << *U;
627 return false; // Not calling the ptr
629 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
630 if (II->getCalledValue() != V) {
631 //cerr << "NONTRAPPING USE: " << *U;
632 return false; // Not calling the ptr
634 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
635 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
636 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
637 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
638 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
639 // If we've already seen this phi node, ignore it, it has already been
641 if (PHIs.insert(PN).second && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
643 } else if (isa<ICmpInst>(U) &&
644 isa<ConstantPointerNull>(U->getOperand(1))) {
645 // Ignore icmp X, null
647 //cerr << "NONTRAPPING USE: " << *U;
654 /// Return true if all uses of any loads from GV will trap if the loaded value
655 /// is null. Note that this also permits comparisons of the loaded value
656 /// against null, as a special case.
657 static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
658 for (const User *U : GV->users())
659 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
660 SmallPtrSet<const PHINode*, 8> PHIs;
661 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
663 } else if (isa<StoreInst>(U)) {
664 // Ignore stores to the global.
666 // We don't know or understand this user, bail out.
667 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
673 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
674 bool Changed = false;
675 for (auto UI = V->user_begin(), E = V->user_end(); UI != E; ) {
676 Instruction *I = cast<Instruction>(*UI++);
677 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
678 LI->setOperand(0, NewV);
680 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
681 if (SI->getOperand(1) == V) {
682 SI->setOperand(1, NewV);
685 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
687 if (CS.getCalledValue() == V) {
688 // Calling through the pointer! Turn into a direct call, but be careful
689 // that the pointer is not also being passed as an argument.
690 CS.setCalledFunction(NewV);
692 bool PassedAsArg = false;
693 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
694 if (CS.getArgument(i) == V) {
696 CS.setArgument(i, NewV);
700 // Being passed as an argument also. Be careful to not invalidate UI!
701 UI = V->user_begin();
704 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
705 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
706 ConstantExpr::getCast(CI->getOpcode(),
707 NewV, CI->getType()));
708 if (CI->use_empty()) {
710 CI->eraseFromParent();
712 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
713 // Should handle GEP here.
714 SmallVector<Constant*, 8> Idxs;
715 Idxs.reserve(GEPI->getNumOperands()-1);
716 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
718 if (Constant *C = dyn_cast<Constant>(*i))
722 if (Idxs.size() == GEPI->getNumOperands()-1)
723 Changed |= OptimizeAwayTrappingUsesOfValue(
724 GEPI, ConstantExpr::getGetElementPtr(nullptr, NewV, Idxs));
725 if (GEPI->use_empty()) {
727 GEPI->eraseFromParent();
736 /// The specified global has only one non-null value stored into it. If there
737 /// are uses of the loaded value that would trap if the loaded value is
738 /// dynamically null, then we know that they cannot be reachable with a null
739 /// optimize away the load.
740 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
741 const DataLayout &DL,
742 TargetLibraryInfo *TLI) {
743 bool Changed = false;
745 // Keep track of whether we are able to remove all the uses of the global
746 // other than the store that defines it.
747 bool AllNonStoreUsesGone = true;
749 // Replace all uses of loads with uses of uses of the stored value.
750 for (Value::user_iterator GUI = GV->user_begin(), E = GV->user_end(); GUI != E;){
751 User *GlobalUser = *GUI++;
752 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
753 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
754 // If we were able to delete all uses of the loads
755 if (LI->use_empty()) {
756 LI->eraseFromParent();
759 AllNonStoreUsesGone = false;
761 } else if (isa<StoreInst>(GlobalUser)) {
762 // Ignore the store that stores "LV" to the global.
763 assert(GlobalUser->getOperand(1) == GV &&
764 "Must be storing *to* the global");
766 AllNonStoreUsesGone = false;
768 // If we get here we could have other crazy uses that are transitively
770 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
771 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
772 isa<BitCastInst>(GlobalUser) ||
773 isa<GetElementPtrInst>(GlobalUser)) &&
774 "Only expect load and stores!");
779 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV << "\n");
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 if (isLeakCheckerRoot(GV)) {
787 Changed |= CleanupPointerRootUsers(GV, TLI);
790 CleanupConstantGlobalUsers(GV, nullptr, DL, TLI);
792 if (GV->use_empty()) {
793 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
795 GV->eraseFromParent();
802 /// Walk the use list of V, constant folding all of the instructions that are
804 static void ConstantPropUsersOf(Value *V, const DataLayout &DL,
805 TargetLibraryInfo *TLI) {
806 for (Value::user_iterator UI = V->user_begin(), E = V->user_end(); UI != E; )
807 if (Instruction *I = dyn_cast<Instruction>(*UI++))
808 if (Constant *NewC = ConstantFoldInstruction(I, DL, TLI)) {
809 I->replaceAllUsesWith(NewC);
811 // Advance UI to the next non-I use to avoid invalidating it!
812 // Instructions could multiply use V.
813 while (UI != E && *UI == I)
815 I->eraseFromParent();
819 /// This function takes the specified global variable, and transforms the
820 /// program as if it always contained the result of the specified malloc.
821 /// Because it is always the result of the specified malloc, there is no reason
822 /// to actually DO the malloc. Instead, turn the malloc into a global, and any
823 /// loads of GV as uses of the new global.
824 static GlobalVariable *
825 OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, CallInst *CI, Type *AllocTy,
826 ConstantInt *NElements, const DataLayout &DL,
827 TargetLibraryInfo *TLI) {
828 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
831 if (NElements->getZExtValue() == 1)
832 GlobalType = AllocTy;
834 // If we have an array allocation, the global variable is of an array.
835 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
837 // Create the new global variable. The contents of the malloc'd memory is
838 // undefined, so initialize with an undef value.
839 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
841 GlobalValue::InternalLinkage,
842 UndefValue::get(GlobalType),
843 GV->getName()+".body",
845 GV->getThreadLocalMode());
847 // If there are bitcast users of the malloc (which is typical, usually we have
848 // a malloc + bitcast) then replace them with uses of the new global. Update
849 // other users to use the global as well.
850 BitCastInst *TheBC = nullptr;
851 while (!CI->use_empty()) {
852 Instruction *User = cast<Instruction>(CI->user_back());
853 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
854 if (BCI->getType() == NewGV->getType()) {
855 BCI->replaceAllUsesWith(NewGV);
856 BCI->eraseFromParent();
858 BCI->setOperand(0, NewGV);
862 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
863 User->replaceUsesOfWith(CI, TheBC);
867 Constant *RepValue = NewGV;
868 if (NewGV->getType() != GV->getType()->getElementType())
869 RepValue = ConstantExpr::getBitCast(RepValue,
870 GV->getType()->getElementType());
872 // If there is a comparison against null, we will insert a global bool to
873 // keep track of whether the global was initialized yet or not.
874 GlobalVariable *InitBool =
875 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
876 GlobalValue::InternalLinkage,
877 ConstantInt::getFalse(GV->getContext()),
878 GV->getName()+".init", GV->getThreadLocalMode());
879 bool InitBoolUsed = false;
881 // Loop over all uses of GV, processing them in turn.
882 while (!GV->use_empty()) {
883 if (StoreInst *SI = dyn_cast<StoreInst>(GV->user_back())) {
884 // The global is initialized when the store to it occurs.
885 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
886 SI->getOrdering(), SI->getSynchScope(), SI);
887 SI->eraseFromParent();
891 LoadInst *LI = cast<LoadInst>(GV->user_back());
892 while (!LI->use_empty()) {
893 Use &LoadUse = *LI->use_begin();
894 ICmpInst *ICI = dyn_cast<ICmpInst>(LoadUse.getUser());
900 // Replace the cmp X, 0 with a use of the bool value.
901 // Sink the load to where the compare was, if atomic rules allow us to.
902 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
903 LI->getOrdering(), LI->getSynchScope(),
904 LI->isUnordered() ? (Instruction*)ICI : LI);
906 switch (ICI->getPredicate()) {
907 default: llvm_unreachable("Unknown ICmp Predicate!");
908 case ICmpInst::ICMP_ULT:
909 case ICmpInst::ICMP_SLT: // X < null -> always false
910 LV = ConstantInt::getFalse(GV->getContext());
912 case ICmpInst::ICMP_ULE:
913 case ICmpInst::ICMP_SLE:
914 case ICmpInst::ICMP_EQ:
915 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
917 case ICmpInst::ICMP_NE:
918 case ICmpInst::ICMP_UGE:
919 case ICmpInst::ICMP_SGE:
920 case ICmpInst::ICMP_UGT:
921 case ICmpInst::ICMP_SGT:
924 ICI->replaceAllUsesWith(LV);
925 ICI->eraseFromParent();
927 LI->eraseFromParent();
930 // If the initialization boolean was used, insert it, otherwise delete it.
932 while (!InitBool->use_empty()) // Delete initializations
933 cast<StoreInst>(InitBool->user_back())->eraseFromParent();
936 GV->getParent()->getGlobalList().insert(GV->getIterator(), InitBool);
938 // Now the GV is dead, nuke it and the malloc..
939 GV->eraseFromParent();
940 CI->eraseFromParent();
942 // To further other optimizations, loop over all users of NewGV and try to
943 // constant prop them. This will promote GEP instructions with constant
944 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
945 ConstantPropUsersOf(NewGV, DL, TLI);
946 if (RepValue != NewGV)
947 ConstantPropUsersOf(RepValue, DL, TLI);
952 /// Scan the use-list of V checking to make sure that there are no complex uses
953 /// of V. We permit simple things like dereferencing the pointer, but not
954 /// storing through the address, unless it is to the specified global.
955 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
956 const GlobalVariable *GV,
957 SmallPtrSetImpl<const PHINode*> &PHIs) {
958 for (const User *U : V->users()) {
959 const Instruction *Inst = cast<Instruction>(U);
961 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
962 continue; // Fine, ignore.
965 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
966 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
967 return false; // Storing the pointer itself... bad.
968 continue; // Otherwise, storing through it, or storing into GV... fine.
971 // Must index into the array and into the struct.
972 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
973 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
978 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
979 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
981 if (PHIs.insert(PN).second)
982 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
987 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
988 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
998 /// The Alloc pointer is stored into GV somewhere. Transform all uses of the
999 /// allocation into loads from the global and uses of the resultant pointer.
1000 /// Further, delete the store into GV. This assumes that these value pass the
1001 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
1002 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
1003 GlobalVariable *GV) {
1004 while (!Alloc->use_empty()) {
1005 Instruction *U = cast<Instruction>(*Alloc->user_begin());
1006 Instruction *InsertPt = U;
1007 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1008 // If this is the store of the allocation into the global, remove it.
1009 if (SI->getOperand(1) == GV) {
1010 SI->eraseFromParent();
1013 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1014 // Insert the load in the corresponding predecessor, not right before the
1016 InsertPt = PN->getIncomingBlock(*Alloc->use_begin())->getTerminator();
1017 } else if (isa<BitCastInst>(U)) {
1018 // Must be bitcast between the malloc and store to initialize the global.
1019 ReplaceUsesOfMallocWithGlobal(U, GV);
1020 U->eraseFromParent();
1022 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1023 // If this is a "GEP bitcast" and the user is a store to the global, then
1024 // just process it as a bitcast.
1025 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1026 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->user_back()))
1027 if (SI->getOperand(1) == GV) {
1028 // Must be bitcast GEP between the malloc and store to initialize
1030 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1031 GEPI->eraseFromParent();
1036 // Insert a load from the global, and use it instead of the malloc.
1037 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
1038 U->replaceUsesOfWith(Alloc, NL);
1042 /// Verify that all uses of V (a load, or a phi of a load) are simple enough to
1043 /// perform heap SRA on. This permits GEP's that index through the array and
1044 /// struct field, icmps of null, and PHIs.
1045 static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
1046 SmallPtrSetImpl<const PHINode*> &LoadUsingPHIs,
1047 SmallPtrSetImpl<const PHINode*> &LoadUsingPHIsPerLoad) {
1048 // We permit two users of the load: setcc comparing against the null
1049 // pointer, and a getelementptr of a specific form.
1050 for (const User *U : V->users()) {
1051 const Instruction *UI = cast<Instruction>(U);
1053 // Comparison against null is ok.
1054 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UI)) {
1055 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1060 // getelementptr is also ok, but only a simple form.
1061 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
1062 // Must index into the array and into the struct.
1063 if (GEPI->getNumOperands() < 3)
1066 // Otherwise the GEP is ok.
1070 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
1071 if (!LoadUsingPHIsPerLoad.insert(PN).second)
1072 // This means some phi nodes are dependent on each other.
1073 // Avoid infinite looping!
1075 if (!LoadUsingPHIs.insert(PN).second)
1076 // If we have already analyzed this PHI, then it is safe.
1079 // Make sure all uses of the PHI are simple enough to transform.
1080 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1081 LoadUsingPHIs, LoadUsingPHIsPerLoad))
1087 // Otherwise we don't know what this is, not ok.
1095 /// If all users of values loaded from GV are simple enough to perform HeapSRA,
1097 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
1098 Instruction *StoredVal) {
1099 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1100 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
1101 for (const User *U : GV->users())
1102 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
1103 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1104 LoadUsingPHIsPerLoad))
1106 LoadUsingPHIsPerLoad.clear();
1109 // If we reach here, we know that all uses of the loads and transitive uses
1110 // (through PHI nodes) are simple enough to transform. However, we don't know
1111 // that all inputs the to the PHI nodes are in the same equivalence sets.
1112 // Check to verify that all operands of the PHIs are either PHIS that can be
1113 // transformed, loads from GV, or MI itself.
1114 for (const PHINode *PN : LoadUsingPHIs) {
1115 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1116 Value *InVal = PN->getIncomingValue(op);
1118 // PHI of the stored value itself is ok.
1119 if (InVal == StoredVal) continue;
1121 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1122 // One of the PHIs in our set is (optimistically) ok.
1123 if (LoadUsingPHIs.count(InPN))
1128 // Load from GV is ok.
1129 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
1130 if (LI->getOperand(0) == GV)
1135 // Anything else is rejected.
1143 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1144 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1145 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1146 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1148 if (FieldNo >= FieldVals.size())
1149 FieldVals.resize(FieldNo+1);
1151 // If we already have this value, just reuse the previously scalarized
1153 if (Value *FieldVal = FieldVals[FieldNo])
1156 // Depending on what instruction this is, we have several cases.
1158 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1159 // This is a scalarized version of the load from the global. Just create
1160 // a new Load of the scalarized global.
1161 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1162 InsertedScalarizedValues,
1164 LI->getName()+".f"+Twine(FieldNo), LI);
1166 PHINode *PN = cast<PHINode>(V);
1167 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1170 PointerType *PTy = cast<PointerType>(PN->getType());
1171 StructType *ST = cast<StructType>(PTy->getElementType());
1173 unsigned AS = PTy->getAddressSpace();
1175 PHINode::Create(PointerType::get(ST->getElementType(FieldNo), AS),
1176 PN->getNumIncomingValues(),
1177 PN->getName()+".f"+Twine(FieldNo), PN);
1179 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1182 return FieldVals[FieldNo] = Result;
1185 /// Given a load instruction and a value derived from the load, rewrite the
1186 /// derived value to use the HeapSRoA'd load.
1187 static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1188 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1189 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1190 // If this is a comparison against null, handle it.
1191 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1192 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1193 // If we have a setcc of the loaded pointer, we can use a setcc of any
1195 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1196 InsertedScalarizedValues, PHIsToRewrite);
1198 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
1199 Constant::getNullValue(NPtr->getType()),
1201 SCI->replaceAllUsesWith(New);
1202 SCI->eraseFromParent();
1206 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
1207 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1208 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1209 && "Unexpected GEPI!");
1211 // Load the pointer for this field.
1212 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1213 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1214 InsertedScalarizedValues, PHIsToRewrite);
1216 // Create the new GEP idx vector.
1217 SmallVector<Value*, 8> GEPIdx;
1218 GEPIdx.push_back(GEPI->getOperand(1));
1219 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1221 Value *NGEPI = GetElementPtrInst::Create(GEPI->getResultElementType(), NewPtr, GEPIdx,
1222 GEPI->getName(), GEPI);
1223 GEPI->replaceAllUsesWith(NGEPI);
1224 GEPI->eraseFromParent();
1228 // Recursively transform the users of PHI nodes. This will lazily create the
1229 // PHIs that are needed for individual elements. Keep track of what PHIs we
1230 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1231 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1232 // already been seen first by another load, so its uses have already been
1234 PHINode *PN = cast<PHINode>(LoadUser);
1235 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1236 std::vector<Value*>())).second)
1239 // If this is the first time we've seen this PHI, recursively process all
1241 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
1242 Instruction *User = cast<Instruction>(*UI++);
1243 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1247 /// We are performing Heap SRoA on a global. Ptr is a value loaded from the
1248 /// global. Eliminate all uses of Ptr, making them use FieldGlobals instead.
1249 /// All uses of loaded values satisfy AllGlobalLoadUsesSimpleEnoughForHeapSRA.
1250 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
1251 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1252 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1253 for (auto UI = Load->user_begin(), E = Load->user_end(); UI != E;) {
1254 Instruction *User = cast<Instruction>(*UI++);
1255 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1258 if (Load->use_empty()) {
1259 Load->eraseFromParent();
1260 InsertedScalarizedValues.erase(Load);
1264 /// CI is an allocation of an array of structures. Break it up into multiple
1265 /// allocations of arrays of the fields.
1266 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1267 Value *NElems, const DataLayout &DL,
1268 const TargetLibraryInfo *TLI) {
1269 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
1270 Type *MAT = getMallocAllocatedType(CI, TLI);
1271 StructType *STy = cast<StructType>(MAT);
1273 // There is guaranteed to be at least one use of the malloc (storing
1274 // it into GV). If there are other uses, change them to be uses of
1275 // the global to simplify later code. This also deletes the store
1277 ReplaceUsesOfMallocWithGlobal(CI, GV);
1279 // Okay, at this point, there are no users of the malloc. Insert N
1280 // new mallocs at the same place as CI, and N globals.
1281 std::vector<Value*> FieldGlobals;
1282 std::vector<Value*> FieldMallocs;
1284 unsigned AS = GV->getType()->getPointerAddressSpace();
1285 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1286 Type *FieldTy = STy->getElementType(FieldNo);
1287 PointerType *PFieldTy = PointerType::get(FieldTy, AS);
1289 GlobalVariable *NGV =
1290 new GlobalVariable(*GV->getParent(),
1291 PFieldTy, false, GlobalValue::InternalLinkage,
1292 Constant::getNullValue(PFieldTy),
1293 GV->getName() + ".f" + Twine(FieldNo), GV,
1294 GV->getThreadLocalMode());
1295 FieldGlobals.push_back(NGV);
1297 unsigned TypeSize = DL.getTypeAllocSize(FieldTy);
1298 if (StructType *ST = dyn_cast<StructType>(FieldTy))
1299 TypeSize = DL.getStructLayout(ST)->getSizeInBytes();
1300 Type *IntPtrTy = DL.getIntPtrType(CI->getType());
1301 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1302 ConstantInt::get(IntPtrTy, TypeSize),
1304 CI->getName() + ".f" + Twine(FieldNo));
1305 FieldMallocs.push_back(NMI);
1306 new StoreInst(NMI, NGV, CI);
1309 // The tricky aspect of this transformation is handling the case when malloc
1310 // fails. In the original code, malloc failing would set the result pointer
1311 // of malloc to null. In this case, some mallocs could succeed and others
1312 // could fail. As such, we emit code that looks like this:
1313 // F0 = malloc(field0)
1314 // F1 = malloc(field1)
1315 // F2 = malloc(field2)
1316 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1317 // if (F0) { free(F0); F0 = 0; }
1318 // if (F1) { free(F1); F1 = 0; }
1319 // if (F2) { free(F2); F2 = 0; }
1321 // The malloc can also fail if its argument is too large.
1322 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1323 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
1324 ConstantZero, "isneg");
1325 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1326 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1327 Constant::getNullValue(FieldMallocs[i]->getType()),
1329 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
1332 // Split the basic block at the old malloc.
1333 BasicBlock *OrigBB = CI->getParent();
1334 BasicBlock *ContBB =
1335 OrigBB->splitBasicBlock(CI->getIterator(), "malloc_cont");
1337 // Create the block to check the first condition. Put all these blocks at the
1338 // end of the function as they are unlikely to be executed.
1339 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1341 OrigBB->getParent());
1343 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1344 // branch on RunningOr.
1345 OrigBB->getTerminator()->eraseFromParent();
1346 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1348 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1349 // pointer, because some may be null while others are not.
1350 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1351 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1352 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1353 Constant::getNullValue(GVVal->getType()));
1354 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
1355 OrigBB->getParent());
1356 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
1357 OrigBB->getParent());
1358 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1361 // Fill in FreeBlock.
1362 CallInst::CreateFree(GVVal, BI);
1363 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1365 BranchInst::Create(NextBlock, FreeBlock);
1367 NullPtrBlock = NextBlock;
1370 BranchInst::Create(ContBB, NullPtrBlock);
1372 // CI is no longer needed, remove it.
1373 CI->eraseFromParent();
1375 /// As we process loads, if we can't immediately update all uses of the load,
1376 /// keep track of what scalarized loads are inserted for a given load.
1377 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1378 InsertedScalarizedValues[GV] = FieldGlobals;
1380 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1382 // Okay, the malloc site is completely handled. All of the uses of GV are now
1383 // loads, and all uses of those loads are simple. Rewrite them to use loads
1384 // of the per-field globals instead.
1385 for (auto UI = GV->user_begin(), E = GV->user_end(); UI != E;) {
1386 Instruction *User = cast<Instruction>(*UI++);
1388 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1389 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
1393 // Must be a store of null.
1394 StoreInst *SI = cast<StoreInst>(User);
1395 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1396 "Unexpected heap-sra user!");
1398 // Insert a store of null into each global.
1399 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1400 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1401 Constant *Null = Constant::getNullValue(PT->getElementType());
1402 new StoreInst(Null, FieldGlobals[i], SI);
1404 // Erase the original store.
1405 SI->eraseFromParent();
1408 // While we have PHIs that are interesting to rewrite, do it.
1409 while (!PHIsToRewrite.empty()) {
1410 PHINode *PN = PHIsToRewrite.back().first;
1411 unsigned FieldNo = PHIsToRewrite.back().second;
1412 PHIsToRewrite.pop_back();
1413 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1414 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1416 // Add all the incoming values. This can materialize more phis.
1417 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1418 Value *InVal = PN->getIncomingValue(i);
1419 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1421 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1425 // Drop all inter-phi links and any loads that made it this far.
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->dropAllReferences();
1431 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1432 LI->dropAllReferences();
1435 // Delete all the phis and loads now that inter-references are dead.
1436 for (DenseMap<Value*, std::vector<Value*> >::iterator
1437 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1439 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1440 PN->eraseFromParent();
1441 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1442 LI->eraseFromParent();
1445 // The old global is now dead, remove it.
1446 GV->eraseFromParent();
1449 return cast<GlobalVariable>(FieldGlobals[0]);
1452 /// This function is called when we see a pointer global variable with a single
1453 /// value stored it that is a malloc or cast of malloc.
1454 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV, CallInst *CI,
1456 AtomicOrdering Ordering,
1457 Module::global_iterator &GVI,
1458 const DataLayout &DL,
1459 TargetLibraryInfo *TLI) {
1460 // If this is a malloc of an abstract type, don't touch it.
1461 if (!AllocTy->isSized())
1464 // We can't optimize this global unless all uses of it are *known* to be
1465 // of the malloc value, not of the null initializer value (consider a use
1466 // that compares the global's value against zero to see if the malloc has
1467 // been reached). To do this, we check to see if all uses of the global
1468 // would trap if the global were null: this proves that they must all
1469 // happen after the malloc.
1470 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1473 // We can't optimize this if the malloc itself is used in a complex way,
1474 // for example, being stored into multiple globals. This allows the
1475 // malloc to be stored into the specified global, loaded icmp'd, and
1476 // GEP'd. These are all things we could transform to using the global
1478 SmallPtrSet<const PHINode*, 8> PHIs;
1479 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1482 // If we have a global that is only initialized with a fixed size malloc,
1483 // transform the program to use global memory instead of malloc'd memory.
1484 // This eliminates dynamic allocation, avoids an indirection accessing the
1485 // data, and exposes the resultant global to further GlobalOpt.
1486 // We cannot optimize the malloc if we cannot determine malloc array size.
1487 Value *NElems = getMallocArraySize(CI, DL, TLI, true);
1491 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1492 // Restrict this transformation to only working on small allocations
1493 // (2048 bytes currently), as we don't want to introduce a 16M global or
1495 if (NElements->getZExtValue() * DL.getTypeAllocSize(AllocTy) < 2048) {
1496 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, DL, TLI)
1501 // If the allocation is an array of structures, consider transforming this
1502 // into multiple malloc'd arrays, one for each field. This is basically
1503 // SRoA for malloc'd memory.
1505 if (Ordering != NotAtomic)
1508 // If this is an allocation of a fixed size array of structs, analyze as a
1509 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1510 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
1511 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1512 AllocTy = AT->getElementType();
1514 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
1518 // This the structure has an unreasonable number of fields, leave it
1520 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1521 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1523 // If this is a fixed size array, transform the Malloc to be an alloc of
1524 // structs. malloc [100 x struct],1 -> malloc struct, 100
1525 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
1526 Type *IntPtrTy = DL.getIntPtrType(CI->getType());
1527 unsigned TypeSize = DL.getStructLayout(AllocSTy)->getSizeInBytes();
1528 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1529 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1530 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1531 AllocSize, NumElements,
1532 nullptr, CI->getName());
1533 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1534 CI->replaceAllUsesWith(Cast);
1535 CI->eraseFromParent();
1536 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1537 CI = cast<CallInst>(BCI->getOperand(0));
1539 CI = cast<CallInst>(Malloc);
1542 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, DL, TLI, true),
1551 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1552 // that only one value (besides its initializer) is ever stored to the global.
1553 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1554 AtomicOrdering Ordering,
1555 Module::global_iterator &GVI,
1556 const DataLayout &DL,
1557 TargetLibraryInfo *TLI) {
1558 // Ignore no-op GEPs and bitcasts.
1559 StoredOnceVal = StoredOnceVal->stripPointerCasts();
1561 // If we are dealing with a pointer global that is initialized to null and
1562 // only has one (non-null) value stored into it, then we can optimize any
1563 // users of the loaded value (often calls and loads) that would trap if the
1565 if (GV->getInitializer()->getType()->isPointerTy() &&
1566 GV->getInitializer()->isNullValue()) {
1567 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1568 if (GV->getInitializer()->getType() != SOVC->getType())
1569 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1571 // Optimize away any trapping uses of the loaded value.
1572 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, DL, TLI))
1574 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1575 Type *MallocType = getMallocAllocatedType(CI, TLI);
1577 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1586 /// At this point, we have learned that the only two values ever stored into GV
1587 /// are its initializer and OtherVal. See if we can shrink the global into a
1588 /// boolean and select between the two values whenever it is used. This exposes
1589 /// the values to other scalar optimizations.
1590 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1591 Type *GVElType = GV->getType()->getElementType();
1593 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1594 // an FP value, pointer or vector, don't do this optimization because a select
1595 // between them is very expensive and unlikely to lead to later
1596 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1597 // where v1 and v2 both require constant pool loads, a big loss.
1598 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
1599 GVElType->isFloatingPointTy() ||
1600 GVElType->isPointerTy() || GVElType->isVectorTy())
1603 // Walk the use list of the global seeing if all the uses are load or store.
1604 // If there is anything else, bail out.
1605 for (User *U : GV->users())
1606 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
1609 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV << "\n");
1611 // Create the new global, initializing it to false.
1612 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1614 GlobalValue::InternalLinkage,
1615 ConstantInt::getFalse(GV->getContext()),
1617 GV->getThreadLocalMode(),
1618 GV->getType()->getAddressSpace());
1619 GV->getParent()->getGlobalList().insert(GV->getIterator(), NewGV);
1621 Constant *InitVal = GV->getInitializer();
1622 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
1623 "No reason to shrink to bool!");
1625 // If initialized to zero and storing one into the global, we can use a cast
1626 // instead of a select to synthesize the desired value.
1627 bool IsOneZero = false;
1628 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1629 IsOneZero = InitVal->isNullValue() && CI->isOne();
1631 while (!GV->use_empty()) {
1632 Instruction *UI = cast<Instruction>(GV->user_back());
1633 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1634 // Change the store into a boolean store.
1635 bool StoringOther = SI->getOperand(0) == OtherVal;
1636 // Only do this if we weren't storing a loaded value.
1638 if (StoringOther || SI->getOperand(0) == InitVal) {
1639 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1642 // Otherwise, we are storing a previously loaded copy. To do this,
1643 // change the copy from copying the original value to just copying the
1645 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1647 // If we've already replaced the input, StoredVal will be a cast or
1648 // select instruction. If not, it will be a load of the original
1650 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1651 assert(LI->getOperand(0) == GV && "Not a copy!");
1652 // Insert a new load, to preserve the saved value.
1653 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1654 LI->getOrdering(), LI->getSynchScope(), LI);
1656 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1657 "This is not a form that we understand!");
1658 StoreVal = StoredVal->getOperand(0);
1659 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1662 new StoreInst(StoreVal, NewGV, false, 0,
1663 SI->getOrdering(), SI->getSynchScope(), SI);
1665 // Change the load into a load of bool then a select.
1666 LoadInst *LI = cast<LoadInst>(UI);
1667 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1668 LI->getOrdering(), LI->getSynchScope(), LI);
1671 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1673 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1675 LI->replaceAllUsesWith(NSI);
1677 UI->eraseFromParent();
1680 // Retain the name of the old global variable. People who are debugging their
1681 // programs may expect these variables to be named the same.
1682 NewGV->takeName(GV);
1683 GV->eraseFromParent();
1688 /// Analyze the specified global variable and optimize it if possible. If we
1689 /// make a change, return true.
1690 bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1691 Module::global_iterator &GVI) {
1692 // Do more involved optimizations if the global is internal.
1693 GV->removeDeadConstantUsers();
1695 if (GV->use_empty()) {
1696 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV << "\n");
1697 GV->eraseFromParent();
1702 if (!GV->hasLocalLinkage())
1707 if (GlobalStatus::analyzeGlobal(GV, GS))
1710 if (!GS.IsCompared && !GV->hasUnnamedAddr()) {
1711 GV->setUnnamedAddr(true);
1715 if (GV->isConstant() || !GV->hasInitializer())
1718 return ProcessInternalGlobal(GV, GVI, GS);
1721 /// Analyze the specified global variable and optimize
1722 /// it if possible. If we make a change, return true.
1723 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1724 Module::global_iterator &GVI,
1725 const GlobalStatus &GS) {
1726 auto &DL = GV->getParent()->getDataLayout();
1727 // If this is a first class global and has only one accessing function
1728 // and this function is main (which we know is not recursive), we replace
1729 // the global with a local alloca 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 Type *ElemTy = GV->getType()->getElementType();
1745 // FIXME: Pass Global's alignment when globals have alignment
1746 AllocaInst *Alloca = new AllocaInst(ElemTy, nullptr,
1747 GV->getName(), &FirstI);
1748 if (!isa<UndefValue>(GV->getInitializer()))
1749 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1751 GV->replaceAllUsesWith(Alloca);
1752 GV->eraseFromParent();
1757 // If the global is never loaded (but may be stored to), it is dead.
1760 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1763 if (isLeakCheckerRoot(GV)) {
1764 // Delete any constant stores to the global.
1765 Changed = CleanupPointerRootUsers(GV, TLI);
1767 // Delete any stores we can find to the global. We may not be able to
1768 // make it completely dead though.
1769 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
1772 // If the global is dead now, delete it.
1773 if (GV->use_empty()) {
1774 GV->eraseFromParent();
1780 } else if (GS.StoredType <= GlobalStatus::InitializerStored) {
1781 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
1782 GV->setConstant(true);
1784 // Clean up any obviously simplifiable users now.
1785 CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
1787 // If the global is dead now, just nuke it.
1788 if (GV->use_empty()) {
1789 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1790 << "all users and delete global!\n");
1791 GV->eraseFromParent();
1797 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1798 const DataLayout &DL = GV->getParent()->getDataLayout();
1799 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, DL)) {
1800 GVI = FirstNewGV->getIterator(); // Don't skip the newly produced globals!
1803 } else if (GS.StoredType == GlobalStatus::StoredOnce && GS.StoredOnceValue) {
1804 // If the initial value for the global was an undef value, and if only
1805 // one other value was stored into it, we can just change the
1806 // initializer to be the stored value, then delete all stores to the
1807 // global. This allows us to mark it constant.
1808 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1809 if (isa<UndefValue>(GV->getInitializer())) {
1810 // Change the initial value here.
1811 GV->setInitializer(SOVConstant);
1813 // Clean up any obviously simplifiable users now.
1814 CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
1816 if (GV->use_empty()) {
1817 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1818 << "simplify all users and delete global!\n");
1819 GV->eraseFromParent();
1822 GVI = GV->getIterator();
1828 // Try to optimize globals based on the knowledge that only one value
1829 // (besides its initializer) is ever stored to the global.
1830 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
1834 // Otherwise, if the global was not a boolean, we can shrink it to be a
1836 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) {
1837 if (GS.Ordering == NotAtomic) {
1838 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1849 /// Walk all of the direct calls of the specified function, changing them to
1851 static void ChangeCalleesToFastCall(Function *F) {
1852 for (User *U : F->users()) {
1853 if (isa<BlockAddress>(U))
1855 CallSite CS(cast<Instruction>(U));
1856 CS.setCallingConv(CallingConv::Fast);
1860 static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
1861 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1862 unsigned Index = Attrs.getSlotIndex(i);
1863 if (!Attrs.getSlotAttributes(i).hasAttribute(Index, Attribute::Nest))
1866 // There can be only one.
1867 return Attrs.removeAttribute(C, Index, Attribute::Nest);
1873 static void RemoveNestAttribute(Function *F) {
1874 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
1875 for (User *U : F->users()) {
1876 if (isa<BlockAddress>(U))
1878 CallSite CS(cast<Instruction>(U));
1879 CS.setAttributes(StripNest(F->getContext(), CS.getAttributes()));
1883 /// Return true if this is a calling convention that we'd like to change. The
1884 /// idea here is that we don't want to mess with the convention if the user
1885 /// explicitly requested something with performance implications like coldcc,
1886 /// GHC, or anyregcc.
1887 static bool isProfitableToMakeFastCC(Function *F) {
1888 CallingConv::ID CC = F->getCallingConv();
1889 // FIXME: Is it worth transforming x86_stdcallcc and x86_fastcallcc?
1890 return CC == CallingConv::C || CC == CallingConv::X86_ThisCall;
1893 bool GlobalOpt::OptimizeFunctions(Module &M) {
1894 bool Changed = false;
1895 // Optimize functions.
1896 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1897 Function *F = &*FI++;
1898 // Functions without names cannot be referenced outside this module.
1899 if (!F->hasName() && !F->isDeclaration() && !F->hasLocalLinkage())
1900 F->setLinkage(GlobalValue::InternalLinkage);
1902 const Comdat *C = F->getComdat();
1903 bool inComdat = C && NotDiscardableComdats.count(C);
1904 F->removeDeadConstantUsers();
1905 if ((!inComdat || F->hasLocalLinkage()) && F->isDefTriviallyDead()) {
1906 F->eraseFromParent();
1909 } else if (F->hasLocalLinkage()) {
1910 if (isProfitableToMakeFastCC(F) && !F->isVarArg() &&
1911 !F->hasAddressTaken()) {
1912 // If this function has a calling convention worth changing, is not a
1913 // varargs function, and is only called directly, promote it to use the
1914 // Fast calling convention.
1915 F->setCallingConv(CallingConv::Fast);
1916 ChangeCalleesToFastCall(F);
1921 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
1922 !F->hasAddressTaken()) {
1923 // The function is not used by a trampoline intrinsic, so it is safe
1924 // to remove the 'nest' attribute.
1925 RemoveNestAttribute(F);
1934 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1935 bool Changed = false;
1937 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1939 GlobalVariable *GV = &*GVI++;
1940 // Global variables without names cannot be referenced outside this module.
1941 if (!GV->hasName() && !GV->isDeclaration() && !GV->hasLocalLinkage())
1942 GV->setLinkage(GlobalValue::InternalLinkage);
1943 // Simplify the initializer.
1944 if (GV->hasInitializer())
1945 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
1946 auto &DL = M.getDataLayout();
1947 Constant *New = ConstantFoldConstantExpression(CE, DL, TLI);
1948 if (New && New != CE)
1949 GV->setInitializer(New);
1952 if (GV->isDiscardableIfUnused()) {
1953 if (const Comdat *C = GV->getComdat())
1954 if (NotDiscardableComdats.count(C) && !GV->hasLocalLinkage())
1956 Changed |= ProcessGlobal(GV, GVI);
1963 isSimpleEnoughValueToCommit(Constant *C,
1964 SmallPtrSetImpl<Constant *> &SimpleConstants,
1965 const DataLayout &DL);
1967 /// Return true if the specified constant can be handled by the code generator.
1968 /// We don't want to generate something like:
1969 /// void *X = &X/42;
1970 /// because the code generator doesn't have a relocation that can handle that.
1972 /// This function should be called if C was not found (but just got inserted)
1973 /// in SimpleConstants to avoid having to rescan the same constants all the
1976 isSimpleEnoughValueToCommitHelper(Constant *C,
1977 SmallPtrSetImpl<Constant *> &SimpleConstants,
1978 const DataLayout &DL) {
1979 // Simple global addresses are supported, do not allow dllimport or
1980 // thread-local globals.
1981 if (auto *GV = dyn_cast<GlobalValue>(C))
1982 return !GV->hasDLLImportStorageClass() && !GV->isThreadLocal();
1984 // Simple integer, undef, constant aggregate zero, etc are all supported.
1985 if (C->getNumOperands() == 0 || isa<BlockAddress>(C))
1988 // Aggregate values are safe if all their elements are.
1989 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1990 isa<ConstantVector>(C)) {
1991 for (Value *Op : C->operands())
1992 if (!isSimpleEnoughValueToCommit(cast<Constant>(Op), SimpleConstants, DL))
1997 // We don't know exactly what relocations are allowed in constant expressions,
1998 // so we allow &global+constantoffset, which is safe and uniformly supported
2000 ConstantExpr *CE = cast<ConstantExpr>(C);
2001 switch (CE->getOpcode()) {
2002 case Instruction::BitCast:
2003 // Bitcast is fine if the casted value is fine.
2004 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
2006 case Instruction::IntToPtr:
2007 case Instruction::PtrToInt:
2008 // int <=> ptr is fine if the int type is the same size as the
2010 if (DL.getTypeSizeInBits(CE->getType()) !=
2011 DL.getTypeSizeInBits(CE->getOperand(0)->getType()))
2013 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
2015 // GEP is fine if it is simple + constant offset.
2016 case Instruction::GetElementPtr:
2017 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2018 if (!isa<ConstantInt>(CE->getOperand(i)))
2020 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
2022 case Instruction::Add:
2023 // We allow simple+cst.
2024 if (!isa<ConstantInt>(CE->getOperand(1)))
2026 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
2032 isSimpleEnoughValueToCommit(Constant *C,
2033 SmallPtrSetImpl<Constant *> &SimpleConstants,
2034 const DataLayout &DL) {
2035 // If we already checked this constant, we win.
2036 if (!SimpleConstants.insert(C).second)
2038 // Check the constant.
2039 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, DL);
2043 /// Return true if this constant is simple enough for us to understand. In
2044 /// particular, if it is a cast to anything other than from one pointer type to
2045 /// another pointer type, we punt. We basically just support direct accesses to
2046 /// globals and GEP's of globals. This should be kept up to date with
2048 static bool isSimpleEnoughPointerToCommit(Constant *C) {
2049 // Conservatively, avoid aggregate types. This is because we don't
2050 // want to worry about them partially overlapping other stores.
2051 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2054 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2055 // Do not allow weak/*_odr/linkonce linkage or external globals.
2056 return GV->hasUniqueInitializer();
2058 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2059 // Handle a constantexpr gep.
2060 if (CE->getOpcode() == Instruction::GetElementPtr &&
2061 isa<GlobalVariable>(CE->getOperand(0)) &&
2062 cast<GEPOperator>(CE)->isInBounds()) {
2063 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2064 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2065 // external globals.
2066 if (!GV->hasUniqueInitializer())
2069 // The first index must be zero.
2070 ConstantInt *CI = dyn_cast<ConstantInt>(*std::next(CE->op_begin()));
2071 if (!CI || !CI->isZero()) return false;
2073 // The remaining indices must be compile-time known integers within the
2074 // notional bounds of the corresponding static array types.
2075 if (!CE->isGEPWithNoNotionalOverIndexing())
2078 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2080 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2081 // and we know how to evaluate it by moving the bitcast from the pointer
2082 // operand to the value operand.
2083 } else if (CE->getOpcode() == Instruction::BitCast &&
2084 isa<GlobalVariable>(CE->getOperand(0))) {
2085 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2086 // external globals.
2087 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
2094 /// Evaluate a piece of a constantexpr store into a global initializer. This
2095 /// returns 'Init' modified to reflect 'Val' stored into it. At this point, the
2096 /// GEP operands of Addr [0, OpNo) have been stepped into.
2097 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2098 ConstantExpr *Addr, unsigned OpNo) {
2099 // Base case of the recursion.
2100 if (OpNo == Addr->getNumOperands()) {
2101 assert(Val->getType() == Init->getType() && "Type mismatch!");
2105 SmallVector<Constant*, 32> Elts;
2106 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
2107 // Break up the constant into its elements.
2108 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2109 Elts.push_back(Init->getAggregateElement(i));
2111 // Replace the element that we are supposed to.
2112 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2113 unsigned Idx = CU->getZExtValue();
2114 assert(Idx < STy->getNumElements() && "Struct index out of range!");
2115 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2117 // Return the modified struct.
2118 return ConstantStruct::get(STy, Elts);
2121 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2122 SequentialType *InitTy = cast<SequentialType>(Init->getType());
2125 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2126 NumElts = ATy->getNumElements();
2128 NumElts = InitTy->getVectorNumElements();
2130 // Break up the array into elements.
2131 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2132 Elts.push_back(Init->getAggregateElement(i));
2134 assert(CI->getZExtValue() < NumElts);
2135 Elts[CI->getZExtValue()] =
2136 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2138 if (Init->getType()->isArrayTy())
2139 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2140 return ConstantVector::get(Elts);
2143 /// We have decided that Addr (which satisfies the predicate
2144 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2145 static void CommitValueTo(Constant *Val, Constant *Addr) {
2146 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2147 assert(GV->hasInitializer());
2148 GV->setInitializer(Val);
2152 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2153 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2154 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
2159 /// This class evaluates LLVM IR, producing the Constant representing each SSA
2160 /// instruction. Changes to global variables are stored in a mapping that can
2161 /// be iterated over after the evaluation is complete. Once an evaluation call
2162 /// fails, the evaluation object should not be reused.
2165 Evaluator(const DataLayout &DL, const TargetLibraryInfo *TLI)
2166 : DL(DL), TLI(TLI) {
2167 ValueStack.emplace_back();
2171 for (auto &Tmp : AllocaTmps)
2172 // If there are still users of the alloca, the program is doing something
2173 // silly, e.g. storing the address of the alloca somewhere and using it
2174 // later. Since this is undefined, we'll just make it be null.
2175 if (!Tmp->use_empty())
2176 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2179 /// Evaluate a call to function F, returning true if successful, false if we
2180 /// can't evaluate it. ActualArgs contains the formal arguments for the
2182 bool EvaluateFunction(Function *F, Constant *&RetVal,
2183 const SmallVectorImpl<Constant*> &ActualArgs);
2185 /// Evaluate all instructions in block BB, returning true if successful, false
2186 /// if we can't evaluate it. NewBB returns the next BB that control flows
2187 /// into, or null upon return.
2188 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2190 Constant *getVal(Value *V) {
2191 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2192 Constant *R = ValueStack.back().lookup(V);
2193 assert(R && "Reference to an uncomputed value!");
2197 void setVal(Value *V, Constant *C) {
2198 ValueStack.back()[V] = C;
2201 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2202 return MutatedMemory;
2205 const SmallPtrSetImpl<GlobalVariable*> &getInvariants() const {
2210 Constant *ComputeLoadResult(Constant *P);
2212 /// As we compute SSA register values, we store their contents here. The back
2213 /// of the deque contains the current function and the stack contains the
2214 /// values in the calling frames.
2215 std::deque<DenseMap<Value*, Constant*>> ValueStack;
2217 /// This is used to detect recursion. In pathological situations we could hit
2218 /// exponential behavior, but at least there is nothing unbounded.
2219 SmallVector<Function*, 4> CallStack;
2221 /// For each store we execute, we update this map. Loads check this to get
2222 /// the most up-to-date value. If evaluation is successful, this state is
2223 /// committed to the process.
2224 DenseMap<Constant*, Constant*> MutatedMemory;
2226 /// To 'execute' an alloca, we create a temporary global variable to represent
2227 /// its body. This vector is needed so we can delete the temporary globals
2228 /// when we are done.
2229 SmallVector<std::unique_ptr<GlobalVariable>, 32> AllocaTmps;
2231 /// These global variables have been marked invariant by the static
2233 SmallPtrSet<GlobalVariable*, 8> Invariants;
2235 /// These are constants we have checked and know to be simple enough to live
2236 /// in a static initializer of a global.
2237 SmallPtrSet<Constant*, 8> SimpleConstants;
2239 const DataLayout &DL;
2240 const TargetLibraryInfo *TLI;
2243 } // anonymous namespace
2245 /// Return the value that would be computed by a load from P after the stores
2246 /// reflected by 'memory' have been performed. If we can't decide, return null.
2247 Constant *Evaluator::ComputeLoadResult(Constant *P) {
2248 // If this memory location has been recently stored, use the stored value: it
2249 // is the most up-to-date.
2250 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2251 if (I != MutatedMemory.end()) return I->second;
2254 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2255 if (GV->hasDefinitiveInitializer())
2256 return GV->getInitializer();
2260 // Handle a constantexpr getelementptr.
2261 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2262 if (CE->getOpcode() == Instruction::GetElementPtr &&
2263 isa<GlobalVariable>(CE->getOperand(0))) {
2264 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2265 if (GV->hasDefinitiveInitializer())
2266 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2269 return nullptr; // don't know how to evaluate.
2272 /// Evaluate all instructions in block BB, returning true if successful, false
2273 /// if we can't evaluate it. NewBB returns the next BB that control flows into,
2274 /// or null upon return.
2275 bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2276 BasicBlock *&NextBB) {
2277 // This is the main evaluation loop.
2279 Constant *InstResult = nullptr;
2281 DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
2283 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2284 if (!SI->isSimple()) {
2285 DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
2286 return false; // no volatile/atomic accesses.
2288 Constant *Ptr = getVal(SI->getOperand(1));
2289 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
2290 DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
2291 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
2292 DEBUG(dbgs() << "; To: " << *Ptr << "\n");
2294 if (!isSimpleEnoughPointerToCommit(Ptr)) {
2295 // If this is too complex for us to commit, reject it.
2296 DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
2300 Constant *Val = getVal(SI->getOperand(0));
2302 // If this might be too difficult for the backend to handle (e.g. the addr
2303 // of one global variable divided by another) then we can't commit it.
2304 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {
2305 DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
2310 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
2311 if (CE->getOpcode() == Instruction::BitCast) {
2312 DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
2313 // If we're evaluating a store through a bitcast, then we need
2314 // to pull the bitcast off the pointer type and push it onto the
2316 Ptr = CE->getOperand(0);
2318 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
2320 // In order to push the bitcast onto the stored value, a bitcast
2321 // from NewTy to Val's type must be legal. If it's not, we can try
2322 // introspecting NewTy to find a legal conversion.
2323 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2324 // If NewTy is a struct, we can convert the pointer to the struct
2325 // into a pointer to its first member.
2326 // FIXME: This could be extended to support arrays as well.
2327 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
2328 NewTy = STy->getTypeAtIndex(0U);
2330 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
2331 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2332 Constant * const IdxList[] = {IdxZero, IdxZero};
2334 Ptr = ConstantExpr::getGetElementPtr(nullptr, Ptr, IdxList);
2335 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2336 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
2338 // If we can't improve the situation by introspecting NewTy,
2339 // we have to give up.
2341 DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
2347 // If we found compatible types, go ahead and push the bitcast
2348 // onto the stored value.
2349 Val = ConstantExpr::getBitCast(Val, NewTy);
2351 DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
2355 MutatedMemory[Ptr] = Val;
2356 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2357 InstResult = ConstantExpr::get(BO->getOpcode(),
2358 getVal(BO->getOperand(0)),
2359 getVal(BO->getOperand(1)));
2360 DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
2362 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2363 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2364 getVal(CI->getOperand(0)),
2365 getVal(CI->getOperand(1)));
2366 DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
2368 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
2369 InstResult = ConstantExpr::getCast(CI->getOpcode(),
2370 getVal(CI->getOperand(0)),
2372 DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
2374 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2375 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2376 getVal(SI->getOperand(1)),
2377 getVal(SI->getOperand(2)));
2378 DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
2380 } else if (auto *EVI = dyn_cast<ExtractValueInst>(CurInst)) {
2381 InstResult = ConstantExpr::getExtractValue(
2382 getVal(EVI->getAggregateOperand()), EVI->getIndices());
2383 DEBUG(dbgs() << "Found an ExtractValueInst! Simplifying: " << *InstResult
2385 } else if (auto *IVI = dyn_cast<InsertValueInst>(CurInst)) {
2386 InstResult = ConstantExpr::getInsertValue(
2387 getVal(IVI->getAggregateOperand()),
2388 getVal(IVI->getInsertedValueOperand()), IVI->getIndices());
2389 DEBUG(dbgs() << "Found an InsertValueInst! Simplifying: " << *InstResult
2391 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2392 Constant *P = getVal(GEP->getOperand(0));
2393 SmallVector<Constant*, 8> GEPOps;
2394 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2396 GEPOps.push_back(getVal(*i));
2398 ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), P, GEPOps,
2399 cast<GEPOperator>(GEP)->isInBounds());
2400 DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
2402 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2404 if (!LI->isSimple()) {
2405 DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
2406 return false; // no volatile/atomic accesses.
2409 Constant *Ptr = getVal(LI->getOperand(0));
2410 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
2411 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
2412 DEBUG(dbgs() << "Found a constant pointer expression, constant "
2413 "folding: " << *Ptr << "\n");
2415 InstResult = ComputeLoadResult(Ptr);
2417 DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
2419 return false; // Could not evaluate load.
2422 DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
2423 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2424 if (AI->isArrayAllocation()) {
2425 DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
2426 return false; // Cannot handle array allocs.
2428 Type *Ty = AI->getType()->getElementType();
2429 AllocaTmps.push_back(
2430 make_unique<GlobalVariable>(Ty, false, GlobalValue::InternalLinkage,
2431 UndefValue::get(Ty), AI->getName()));
2432 InstResult = AllocaTmps.back().get();
2433 DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
2434 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2435 CallSite CS(&*CurInst);
2437 // Debug info can safely be ignored here.
2438 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
2439 DEBUG(dbgs() << "Ignoring debug info.\n");
2444 // Cannot handle inline asm.
2445 if (isa<InlineAsm>(CS.getCalledValue())) {
2446 DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
2450 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2451 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2452 if (MSI->isVolatile()) {
2453 DEBUG(dbgs() << "Can not optimize a volatile memset " <<
2457 Constant *Ptr = getVal(MSI->getDest());
2458 Constant *Val = getVal(MSI->getValue());
2459 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
2460 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2461 // This memset is a no-op.
2462 DEBUG(dbgs() << "Ignoring no-op memset.\n");
2468 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2469 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2470 DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
2475 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2476 // We don't insert an entry into Values, as it doesn't have a
2477 // meaningful return value.
2478 if (!II->use_empty()) {
2479 DEBUG(dbgs() << "Found unused invariant_start. Can't evaluate.\n");
2482 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
2483 Value *PtrArg = getVal(II->getArgOperand(1));
2484 Value *Ptr = PtrArg->stripPointerCasts();
2485 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2486 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
2487 if (!Size->isAllOnesValue() &&
2488 Size->getValue().getLimitedValue() >=
2489 DL.getTypeStoreSize(ElemTy)) {
2490 Invariants.insert(GV);
2491 DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
2494 DEBUG(dbgs() << "Found a global var, but can not treat it as an "
2498 // Continue even if we do nothing.
2501 } else if (II->getIntrinsicID() == Intrinsic::assume) {
2502 DEBUG(dbgs() << "Skipping assume intrinsic.\n");
2507 DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
2511 // Resolve function pointers.
2512 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
2513 if (!Callee || Callee->mayBeOverridden()) {
2514 DEBUG(dbgs() << "Can not resolve function pointer.\n");
2515 return false; // Cannot resolve.
2518 SmallVector<Constant*, 8> Formals;
2519 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
2520 Formals.push_back(getVal(*i));
2522 if (Callee->isDeclaration()) {
2523 // If this is a function we can constant fold, do it.
2524 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
2526 DEBUG(dbgs() << "Constant folded function call. Result: " <<
2527 *InstResult << "\n");
2529 DEBUG(dbgs() << "Can not constant fold function call.\n");
2533 if (Callee->getFunctionType()->isVarArg()) {
2534 DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
2538 Constant *RetVal = nullptr;
2539 // Execute the call, if successful, use the return value.
2540 ValueStack.emplace_back();
2541 if (!EvaluateFunction(Callee, RetVal, Formals)) {
2542 DEBUG(dbgs() << "Failed to evaluate function.\n");
2545 ValueStack.pop_back();
2546 InstResult = RetVal;
2549 DEBUG(dbgs() << "Successfully evaluated function. Result: " <<
2550 InstResult << "\n\n");
2552 DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
2555 } else if (isa<TerminatorInst>(CurInst)) {
2556 DEBUG(dbgs() << "Found a terminator instruction.\n");
2558 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2559 if (BI->isUnconditional()) {
2560 NextBB = BI->getSuccessor(0);
2563 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
2564 if (!Cond) return false; // Cannot determine.
2566 NextBB = BI->getSuccessor(!Cond->getZExtValue());
2568 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2570 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
2571 if (!Val) return false; // Cannot determine.
2572 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
2573 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2574 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
2575 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2576 NextBB = BA->getBasicBlock();
2578 return false; // Cannot determine.
2579 } else if (isa<ReturnInst>(CurInst)) {
2582 // invoke, unwind, resume, unreachable.
2583 DEBUG(dbgs() << "Can not handle terminator.");
2584 return false; // Cannot handle this terminator.
2587 // We succeeded at evaluating this block!
2588 DEBUG(dbgs() << "Successfully evaluated block.\n");
2591 // Did not know how to evaluate this!
2592 DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
2597 if (!CurInst->use_empty()) {
2598 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
2599 InstResult = ConstantFoldConstantExpression(CE, DL, TLI);
2601 setVal(&*CurInst, InstResult);
2604 // If we just processed an invoke, we finished evaluating the block.
2605 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2606 NextBB = II->getNormalDest();
2607 DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
2611 // Advance program counter.
2616 /// Evaluate a call to function F, returning true if successful, false if we
2617 /// can't evaluate it. ActualArgs contains the formal arguments for the
2619 bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2620 const SmallVectorImpl<Constant*> &ActualArgs) {
2621 // Check to see if this function is already executing (recursion). If so,
2622 // bail out. TODO: we might want to accept limited recursion.
2623 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2626 CallStack.push_back(F);
2628 // Initialize arguments to the incoming values specified.
2630 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2632 setVal(&*AI, ActualArgs[ArgNo]);
2634 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2635 // we can only evaluate any one basic block at most once. This set keeps
2636 // track of what we have executed so we can detect recursive cases etc.
2637 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2639 // CurBB - The current basic block we're evaluating.
2640 BasicBlock *CurBB = &F->front();
2642 BasicBlock::iterator CurInst = CurBB->begin();
2645 BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings.
2646 DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
2648 if (!EvaluateBlock(CurInst, NextBB))
2652 // Successfully running until there's no next block means that we found
2653 // the return. Fill it the return value and pop the call stack.
2654 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2655 if (RI->getNumOperands())
2656 RetVal = getVal(RI->getOperand(0));
2657 CallStack.pop_back();
2661 // Okay, we succeeded in evaluating this control flow. See if we have
2662 // executed the new block before. If so, we have a looping function,
2663 // which we cannot evaluate in reasonable time.
2664 if (!ExecutedBlocks.insert(NextBB).second)
2665 return false; // looped!
2667 // Okay, we have never been in this block before. Check to see if there
2668 // are any PHI nodes. If so, evaluate them with information about where
2670 PHINode *PN = nullptr;
2671 for (CurInst = NextBB->begin();
2672 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2673 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
2675 // Advance to the next block.
2680 /// Evaluate static constructors in the function, if we can. Return true if we
2681 /// can, false otherwise.
2682 static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL,
2683 const TargetLibraryInfo *TLI) {
2684 // Call the function.
2685 Evaluator Eval(DL, TLI);
2686 Constant *RetValDummy;
2687 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2688 SmallVector<Constant*, 0>());
2691 ++NumCtorsEvaluated;
2693 // We succeeded at evaluation: commit the result.
2694 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2695 << F->getName() << "' to " << Eval.getMutatedMemory().size()
2697 for (DenseMap<Constant*, Constant*>::const_iterator I =
2698 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
2700 CommitValueTo(I->second, I->first);
2701 for (GlobalVariable *GV : Eval.getInvariants())
2702 GV->setConstant(true);
2708 static int compareNames(Constant *const *A, Constant *const *B) {
2709 return (*A)->stripPointerCasts()->getName().compare(
2710 (*B)->stripPointerCasts()->getName());
2713 static void setUsedInitializer(GlobalVariable &V,
2714 const SmallPtrSet<GlobalValue *, 8> &Init) {
2716 V.eraseFromParent();
2720 // Type of pointer to the array of pointers.
2721 PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext(), 0);
2723 SmallVector<llvm::Constant *, 8> UsedArray;
2724 for (GlobalValue *GV : Init) {
2726 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, Int8PtrTy);
2727 UsedArray.push_back(Cast);
2729 // Sort to get deterministic order.
2730 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
2731 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
2733 Module *M = V.getParent();
2734 V.removeFromParent();
2735 GlobalVariable *NV =
2736 new GlobalVariable(*M, ATy, false, llvm::GlobalValue::AppendingLinkage,
2737 llvm::ConstantArray::get(ATy, UsedArray), "");
2739 NV->setSection("llvm.metadata");
2744 /// An easy to access representation of llvm.used and llvm.compiler.used.
2746 SmallPtrSet<GlobalValue *, 8> Used;
2747 SmallPtrSet<GlobalValue *, 8> CompilerUsed;
2748 GlobalVariable *UsedV;
2749 GlobalVariable *CompilerUsedV;
2752 LLVMUsed(Module &M) {
2753 UsedV = collectUsedGlobalVariables(M, Used, false);
2754 CompilerUsedV = collectUsedGlobalVariables(M, CompilerUsed, true);
2756 typedef SmallPtrSet<GlobalValue *, 8>::iterator iterator;
2757 typedef iterator_range<iterator> used_iterator_range;
2758 iterator usedBegin() { return Used.begin(); }
2759 iterator usedEnd() { return Used.end(); }
2760 used_iterator_range used() {
2761 return used_iterator_range(usedBegin(), usedEnd());
2763 iterator compilerUsedBegin() { return CompilerUsed.begin(); }
2764 iterator compilerUsedEnd() { return CompilerUsed.end(); }
2765 used_iterator_range compilerUsed() {
2766 return used_iterator_range(compilerUsedBegin(), compilerUsedEnd());
2768 bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
2769 bool compilerUsedCount(GlobalValue *GV) const {
2770 return CompilerUsed.count(GV);
2772 bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
2773 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
2774 bool usedInsert(GlobalValue *GV) { return Used.insert(GV).second; }
2775 bool compilerUsedInsert(GlobalValue *GV) {
2776 return CompilerUsed.insert(GV).second;
2779 void syncVariablesAndSets() {
2781 setUsedInitializer(*UsedV, Used);
2783 setUsedInitializer(*CompilerUsedV, CompilerUsed);
2788 static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
2789 if (GA.use_empty()) // No use at all.
2792 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2793 "We should have removed the duplicated "
2794 "element from llvm.compiler.used");
2795 if (!GA.hasOneUse())
2796 // Strictly more than one use. So at least one is not in llvm.used and
2797 // llvm.compiler.used.
2800 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
2801 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
2804 static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
2805 const LLVMUsed &U) {
2807 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2808 "We should have removed the duplicated "
2809 "element from llvm.compiler.used");
2810 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2812 return V.hasNUsesOrMore(N);
2815 static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
2816 if (!GA.hasLocalLinkage())
2819 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2822 static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U,
2823 bool &RenameTarget) {
2824 RenameTarget = false;
2826 if (hasUseOtherThanLLVMUsed(GA, U))
2829 // If the alias is externally visible, we may still be able to simplify it.
2830 if (!mayHaveOtherReferences(GA, U))
2833 // If the aliasee has internal linkage, give it the name and linkage
2834 // of the alias, and delete the alias. This turns:
2835 // define internal ... @f(...)
2836 // @a = alias ... @f
2838 // define ... @a(...)
2839 Constant *Aliasee = GA.getAliasee();
2840 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2841 if (!Target->hasLocalLinkage())
2844 // Do not perform the transform if multiple aliases potentially target the
2845 // aliasee. This check also ensures that it is safe to replace the section
2846 // and other attributes of the aliasee with those of the alias.
2847 if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
2850 RenameTarget = true;
2854 bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
2855 bool Changed = false;
2858 for (GlobalValue *GV : Used.used())
2859 Used.compilerUsedErase(GV);
2861 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
2863 Module::alias_iterator J = I++;
2864 // Aliases without names cannot be referenced outside this module.
2865 if (!J->hasName() && !J->isDeclaration() && !J->hasLocalLinkage())
2866 J->setLinkage(GlobalValue::InternalLinkage);
2867 // If the aliasee may change at link time, nothing can be done - bail out.
2868 if (J->mayBeOverridden())
2871 Constant *Aliasee = J->getAliasee();
2872 GlobalValue *Target = dyn_cast<GlobalValue>(Aliasee->stripPointerCasts());
2873 // We can't trivially replace the alias with the aliasee if the aliasee is
2874 // non-trivial in some way.
2875 // TODO: Try to handle non-zero GEPs of local aliasees.
2878 Target->removeDeadConstantUsers();
2880 // Make all users of the alias use the aliasee instead.
2882 if (!hasUsesToReplace(*J, Used, RenameTarget))
2885 J->replaceAllUsesWith(ConstantExpr::getBitCast(Aliasee, J->getType()));
2886 ++NumAliasesResolved;
2890 // Give the aliasee the name, linkage and other attributes of the alias.
2891 Target->takeName(&*J);
2892 Target->setLinkage(J->getLinkage());
2893 Target->setVisibility(J->getVisibility());
2894 Target->setDLLStorageClass(J->getDLLStorageClass());
2896 if (Used.usedErase(&*J))
2897 Used.usedInsert(Target);
2899 if (Used.compilerUsedErase(&*J))
2900 Used.compilerUsedInsert(Target);
2901 } else if (mayHaveOtherReferences(*J, Used))
2904 // Delete the alias.
2905 M.getAliasList().erase(J);
2906 ++NumAliasesRemoved;
2910 Used.syncVariablesAndSets();
2915 static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
2916 if (!TLI->has(LibFunc::cxa_atexit))
2919 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
2924 FunctionType *FTy = Fn->getFunctionType();
2926 // Checking that the function has the right return type, the right number of
2927 // parameters and that they all have pointer types should be enough.
2928 if (!FTy->getReturnType()->isIntegerTy() ||
2929 FTy->getNumParams() != 3 ||
2930 !FTy->getParamType(0)->isPointerTy() ||
2931 !FTy->getParamType(1)->isPointerTy() ||
2932 !FTy->getParamType(2)->isPointerTy())
2938 /// Returns whether the given function is an empty C++ destructor and can
2939 /// therefore be eliminated.
2940 /// Note that we assume that other optimization passes have already simplified
2941 /// the code so we only look for a function with a single basic block, where
2942 /// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
2943 /// other side-effect free instructions.
2944 static bool cxxDtorIsEmpty(const Function &Fn,
2945 SmallPtrSet<const Function *, 8> &CalledFunctions) {
2946 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
2947 // nounwind, but that doesn't seem worth doing.
2948 if (Fn.isDeclaration())
2951 if (++Fn.begin() != Fn.end())
2954 const BasicBlock &EntryBlock = Fn.getEntryBlock();
2955 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
2957 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
2958 // Ignore debug intrinsics.
2959 if (isa<DbgInfoIntrinsic>(CI))
2962 const Function *CalledFn = CI->getCalledFunction();
2967 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
2969 // Don't treat recursive functions as empty.
2970 if (!NewCalledFunctions.insert(CalledFn).second)
2973 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
2975 } else if (isa<ReturnInst>(*I))
2976 return true; // We're done.
2977 else if (I->mayHaveSideEffects())
2978 return false; // Destructor with side effects, bail.
2984 bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
2985 /// Itanium C++ ABI p3.3.5:
2987 /// After constructing a global (or local static) object, that will require
2988 /// destruction on exit, a termination function is registered as follows:
2990 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
2992 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
2993 /// call f(p) when DSO d is unloaded, before all such termination calls
2994 /// registered before this one. It returns zero if registration is
2995 /// successful, nonzero on failure.
2997 // This pass will look for calls to __cxa_atexit where the function is trivial
2999 bool Changed = false;
3001 for (auto I = CXAAtExitFn->user_begin(), E = CXAAtExitFn->user_end();
3003 // We're only interested in calls. Theoretically, we could handle invoke
3004 // instructions as well, but neither llvm-gcc nor clang generate invokes
3006 CallInst *CI = dyn_cast<CallInst>(*I++);
3011 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
3015 SmallPtrSet<const Function *, 8> CalledFunctions;
3016 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
3019 // Just remove the call.
3020 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3021 CI->eraseFromParent();
3023 ++NumCXXDtorsRemoved;
3031 bool GlobalOpt::runOnModule(Module &M) {
3032 bool Changed = false;
3034 auto &DL = M.getDataLayout();
3035 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3037 bool LocalChange = true;
3038 while (LocalChange) {
3039 LocalChange = false;
3041 NotDiscardableComdats.clear();
3042 for (const GlobalVariable &GV : M.globals())
3043 if (const Comdat *C = GV.getComdat())
3044 if (!GV.isDiscardableIfUnused() || !GV.use_empty())
3045 NotDiscardableComdats.insert(C);
3046 for (Function &F : M)
3047 if (const Comdat *C = F.getComdat())
3048 if (!F.isDefTriviallyDead())
3049 NotDiscardableComdats.insert(C);
3050 for (GlobalAlias &GA : M.aliases())
3051 if (const Comdat *C = GA.getComdat())
3052 if (!GA.isDiscardableIfUnused() || !GA.use_empty())
3053 NotDiscardableComdats.insert(C);
3055 // Delete functions that are trivially dead, ccc -> fastcc
3056 LocalChange |= OptimizeFunctions(M);
3058 // Optimize global_ctors list.
3059 LocalChange |= optimizeGlobalCtorsList(M, [&](Function *F) {
3060 return EvaluateStaticConstructor(F, DL, TLI);
3063 // Optimize non-address-taken globals.
3064 LocalChange |= OptimizeGlobalVars(M);
3066 // Resolve aliases, when possible.
3067 LocalChange |= OptimizeGlobalAliases(M);
3069 // Try to remove trivial global destructors if they are not removed
3071 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
3073 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3075 Changed |= LocalChange;
3078 // TODO: Move all global ctors functions to the end of the module for code