blob: 6e8b434ce3dd159403c287aba8360180479e863f [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// 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.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000019#include "llvm/Constants.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000020#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000021#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner079236d2004-02-25 21:34:36 +000023#include "llvm/Module.h"
Jay Foad562b84b2011-04-11 09:35:34 +000024#include "llvm/Operator.h"
Chris Lattner079236d2004-02-25 21:34:36 +000025#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000026#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000027#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000028#include "llvm/Target/TargetData.h"
Chad Rosier00737bd2011-12-01 21:29:16 +000029#include "llvm/Target/TargetLibraryInfo.h"
Duncan Sands548448a2008-02-18 17:32:13 +000030#include "llvm/Support/CallSite.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000031#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner941db492008-01-14 02:09:12 +000033#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner998182b2008-04-26 07:40:11 +000034#include "llvm/Support/MathExtras.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner5a6bb6a2008-12-16 07:34:30 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattner81686182007-09-13 16:30:19 +000037#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000038#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/ADT/Statistic.h"
Chris Lattnerbce4afe2008-12-17 05:28:49 +000040#include "llvm/ADT/STLExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000041#include <algorithm>
Chris Lattner079236d2004-02-25 21:34:36 +000042using namespace llvm;
43
Chris Lattner86453c52006-12-19 22:09:18 +000044STATISTIC(NumMarked , "Number of globals marked constant");
Rafael Espindolac4440e32011-01-19 16:32:21 +000045STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
Chris Lattner86453c52006-12-19 22:09:18 +000046STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
47STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
48STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
49STATISTIC(NumDeleted , "Number of globals deleted");
50STATISTIC(NumFnDeleted , "Number of functions deleted");
51STATISTIC(NumGlobUses , "Number of global uses devirtualized");
52STATISTIC(NumLocalized , "Number of globals localized");
53STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
54STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
55STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000056STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sands4782b302009-02-15 09:56:08 +000057STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
58STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Anders Carlssona201c4c2011-03-20 17:59:11 +000059STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
Chris Lattner079236d2004-02-25 21:34:36 +000060
Chris Lattner86453c52006-12-19 22:09:18 +000061namespace {
Rafael Espindolac4440e32011-01-19 16:32:21 +000062 struct GlobalStatus;
Nick Lewycky6726b6d2009-10-25 06:33:48 +000063 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000064 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier00737bd2011-12-01 21:29:16 +000065 AU.addRequired<TargetLibraryInfo>();
Chris Lattner30ba5692004-10-11 05:54:41 +000066 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000067 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000068 GlobalOpt() : ModulePass(ID) {
69 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
70 }
Misha Brukmanfd939082005-04-21 23:48:37 +000071
Chris Lattnerb12914b2004-09-20 04:48:05 +000072 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000073
74 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000075 GlobalVariable *FindGlobalCtors(Module &M);
76 bool OptimizeFunctions(Module &M);
77 bool OptimizeGlobalVars(Module &M);
Duncan Sandsfc5940d2009-03-06 10:21:56 +000078 bool OptimizeGlobalAliases(Module &M);
Chris Lattnerb1ab4582005-09-26 01:43:45 +000079 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Rafael Espindolac4440e32011-01-19 16:32:21 +000080 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
81 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
82 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
83 const GlobalStatus &GS);
Anders Carlssona201c4c2011-03-20 17:59:11 +000084 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
Chris Lattner079236d2004-02-25 21:34:36 +000085 };
Chris Lattner079236d2004-02-25 21:34:36 +000086}
87
Dan Gohman844731a2008-05-13 00:00:25 +000088char GlobalOpt::ID = 0;
Chad Rosier00737bd2011-12-01 21:29:16 +000089INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
90 "Global Variable Optimizer", false, false)
91INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
92INITIALIZE_PASS_END(GlobalOpt, "globalopt",
Owen Andersonce665bd2010-10-07 22:25:06 +000093 "Global Variable Optimizer", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000094
Chris Lattner7a90b682004-10-07 04:16:33 +000095ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000096
Dan Gohman844731a2008-05-13 00:00:25 +000097namespace {
98
Chris Lattner7a90b682004-10-07 04:16:33 +000099/// GlobalStatus - As we analyze each global, keep track of some information
100/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000101/// this info will be accurate.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000102struct GlobalStatus {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000103 /// isCompared - True if the global's address is used in a comparison.
104 bool isCompared;
105
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000106 /// isLoaded - True if the global is ever loaded. If the global isn't ever
107 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +0000108 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000109
110 /// StoredType - Keep track of what stores to the global look like.
111 ///
Chris Lattner7a90b682004-10-07 04:16:33 +0000112 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000113 /// NotStored - There is no store to this global. It can thus be marked
114 /// constant.
115 NotStored,
116
117 /// isInitializerStored - This global is stored to, but the only thing
118 /// stored is the constant it was initialized with. This is only tracked
119 /// for scalar globals.
120 isInitializerStored,
121
122 /// isStoredOnce - This global is stored to, but only its initializer and
123 /// one other value is ever stored to it. If this global isStoredOnce, we
124 /// track the value stored to it in StoredOnceValue below. This is only
125 /// tracked for scalar globals.
126 isStoredOnce,
127
128 /// isStored - This global is stored to by multiple values or something else
129 /// that we cannot track.
130 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000131 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000132
133 /// StoredOnceValue - If only one value (besides the initializer constant) is
134 /// ever stored to this global, keep track of what value it is.
135 Value *StoredOnceValue;
136
Chris Lattner25de4e52006-11-01 18:03:33 +0000137 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
138 /// null/false. When the first accessing function is noticed, it is recorded.
139 /// When a second different accessing function is noticed,
140 /// HasMultipleAccessingFunctions is set to true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000141 const Function *AccessingFunction;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000142 bool HasMultipleAccessingFunctions;
143
Chris Lattner25de4e52006-11-01 18:03:33 +0000144 /// HasNonInstructionUser - Set to true if this global has a user that is not
145 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000146 bool HasNonInstructionUser;
147
Chris Lattner25de4e52006-11-01 18:03:33 +0000148 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
149 bool HasPHIUser;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000150
Rafael Espindolac4440e32011-01-19 16:32:21 +0000151 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
152 StoredOnceValue(0), AccessingFunction(0),
153 HasMultipleAccessingFunctions(false), HasNonInstructionUser(false),
154 HasPHIUser(false) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000155};
Chris Lattnere47ba742004-10-06 20:57:02 +0000156
Dan Gohman844731a2008-05-13 00:00:25 +0000157}
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000158
Jay Foade3acf152009-06-09 21:37:11 +0000159// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
160// by constants itself. Note that constants cannot be cyclic, so this test is
161// pretty easy to implement recursively.
162//
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000163static bool SafeToDestroyConstant(const Constant *C) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000164 if (isa<GlobalValue>(C)) return false;
165
Gabor Greif27236912010-04-07 18:59:26 +0000166 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
167 ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000168 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade3acf152009-06-09 21:37:11 +0000169 if (!SafeToDestroyConstant(CU)) return false;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000170 } else
171 return false;
172 return true;
173}
174
175
Chris Lattner7a90b682004-10-07 04:16:33 +0000176/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
177/// structure. If the global has its address taken, return true to indicate we
178/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000179///
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000180static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
181 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
Gabor Greif27236912010-04-07 18:59:26 +0000182 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greife6642672010-07-09 16:51:20 +0000183 ++UI) {
184 const User *U = *UI;
185 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000186 GS.HasNonInstructionUser = true;
Chris Lattnerd91ed102011-01-01 22:31:46 +0000187
188 // If the result of the constantexpr isn't pointer type, then we won't
189 // know to expect it in various places. Just reject early.
190 if (!isa<PointerType>(CE->getType())) return true;
191
Chris Lattner7a90b682004-10-07 04:16:33 +0000192 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Gabor Greife6642672010-07-09 16:51:20 +0000193 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000194 if (!GS.HasMultipleAccessingFunctions) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000195 const Function *F = I->getParent()->getParent();
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000196 if (GS.AccessingFunction == 0)
197 GS.AccessingFunction = F;
198 else if (GS.AccessingFunction != F)
199 GS.HasMultipleAccessingFunctions = true;
200 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000201 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000202 GS.isLoaded = true;
Eli Friedman33cb4452011-08-16 00:20:11 +0000203 // Don't hack on volatile/atomic loads.
204 if (!LI->isSimple()) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000205 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000206 // Don't allow a store OF the address, only stores TO the address.
207 if (SI->getOperand(0) == V) return true;
208
Eli Friedman33cb4452011-08-16 00:20:11 +0000209 // Don't hack on volatile/atomic stores.
210 if (!SI->isSimple()) return true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000211
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000212 // If this is a direct store to the global (i.e., the global is a scalar
213 // value, not an aggregate), keep more specific information about
214 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000215 if (GS.StoredType != GlobalStatus::isStored) {
Gabor Greif27236912010-04-07 18:59:26 +0000216 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
217 SI->getOperand(1))) {
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000218 Value *StoredVal = SI->getOperand(0);
219 if (StoredVal == GV->getInitializer()) {
220 if (GS.StoredType < GlobalStatus::isInitializerStored)
221 GS.StoredType = GlobalStatus::isInitializerStored;
222 } else if (isa<LoadInst>(StoredVal) &&
223 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000224 if (GS.StoredType < GlobalStatus::isInitializerStored)
225 GS.StoredType = GlobalStatus::isInitializerStored;
226 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
227 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000228 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000229 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000230 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000231 // noop.
232 } else {
233 GS.StoredType = GlobalStatus::isStored;
234 }
235 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000236 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000237 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000238 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000239 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000240 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000241 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000242 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000243 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000244 // PHI nodes we can check just like select or GEP instructions, but we
245 // have to be careful about infinite recursion.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +0000246 if (PHIUsers.insert(PN)) // Not already visited.
Chris Lattner7a90b682004-10-07 04:16:33 +0000247 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000248 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000249 } else if (isa<CmpInst>(I)) {
Rafael Espindolac4440e32011-01-19 16:32:21 +0000250 GS.isCompared = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000251 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
252 if (MTI->isVolatile()) return true;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000253 if (MTI->getArgOperand(0) == V)
Eric Christopher551754c2010-04-16 23:37:20 +0000254 GS.StoredType = GlobalStatus::isStored;
Gabor Greif9e4f2432010-06-24 14:42:01 +0000255 if (MTI->getArgOperand(1) == V)
Chris Lattner35c81b02005-02-27 18:58:52 +0000256 GS.isLoaded = true;
Nick Lewycky1f237b02011-05-29 18:41:56 +0000257 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
258 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
259 if (MSI->isVolatile()) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000260 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000261 } else {
262 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000263 }
Gabor Greife6642672010-07-09 16:51:20 +0000264 } else if (const Constant *C = dyn_cast<Constant>(U)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000265 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000266 // We might have a dead and dangling constant hanging off of here.
Jay Foade3acf152009-06-09 21:37:11 +0000267 if (!SafeToDestroyConstant(C))
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000268 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000269 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000270 GS.HasNonInstructionUser = true;
271 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000272 return true;
273 }
Gabor Greife6642672010-07-09 16:51:20 +0000274 }
Chris Lattner079236d2004-02-25 21:34:36 +0000275
276 return false;
277}
278
Chris Lattnere47ba742004-10-06 20:57:02 +0000279/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
280/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000281/// quick scan over the use list to clean up the easy and obvious cruft. This
282/// returns true if it made a change.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000283static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
Chris Lattner031955d2004-10-10 16:43:46 +0000284 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000285 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
286 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000287
Chris Lattner7a90b682004-10-07 04:16:33 +0000288 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000289 if (Init) {
290 // Replace the load with the initializer.
291 LI->replaceAllUsesWith(Init);
292 LI->eraseFromParent();
293 Changed = true;
294 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000295 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000296 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000297 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000298 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000299 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
300 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000301 Constant *SubInit = 0;
302 if (Init)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000303 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b550cc2009-11-06 04:27:31 +0000304 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000305 } else if (CE->getOpcode() == Instruction::BitCast &&
Duncan Sands1df98592010-02-16 11:11:14 +0000306 CE->getType()->isPointerTy()) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000307 // Pointer cast, delete any stores and memsets to the global.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000308 Changed |= CleanupConstantGlobalUsers(CE, 0);
Chris Lattner35c81b02005-02-27 18:58:52 +0000309 }
310
311 if (CE->use_empty()) {
312 CE->destroyConstant();
313 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000314 }
315 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000316 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
317 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
318 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000319 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000320 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
Chad Rosieraab8e282011-12-02 01:26:24 +0000321 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000322 ConstantExpr *CE =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000323 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattner7b52fe72007-11-09 17:33:02 +0000324 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000325 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000326 }
Chris Lattner7b550cc2009-11-06 04:27:31 +0000327 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000328
Chris Lattner031955d2004-10-10 16:43:46 +0000329 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000330 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000331 Changed = true;
332 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000333 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
334 if (MI->getRawDest() == V) {
335 MI->eraseFromParent();
336 Changed = true;
337 }
338
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000339 } else if (Constant *C = dyn_cast<Constant>(U)) {
340 // If we have a chain of dead constantexprs or other things dangling from
341 // us, and if they are all dead, nuke them without remorse.
Jay Foade3acf152009-06-09 21:37:11 +0000342 if (SafeToDestroyConstant(C)) {
Devang Patel743cdf82009-03-06 01:37:41 +0000343 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000344 // This could have invalidated UI, start over from scratch.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000345 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000346 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000347 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000348 }
349 }
Chris Lattner031955d2004-10-10 16:43:46 +0000350 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000351}
352
Chris Lattner941db492008-01-14 02:09:12 +0000353/// isSafeSROAElementUse - Return true if the specified instruction is a safe
354/// user of a derived expression from a global that we want to SROA.
355static bool isSafeSROAElementUse(Value *V) {
356 // We might have a dead and dangling constant hanging off of here.
357 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade3acf152009-06-09 21:37:11 +0000358 return SafeToDestroyConstant(C);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000359
Chris Lattner941db492008-01-14 02:09:12 +0000360 Instruction *I = dyn_cast<Instruction>(V);
361 if (!I) return false;
362
363 // Loads are ok.
364 if (isa<LoadInst>(I)) return true;
365
366 // Stores *to* the pointer are ok.
367 if (StoreInst *SI = dyn_cast<StoreInst>(I))
368 return SI->getOperand(0) != V;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000369
Chris Lattner941db492008-01-14 02:09:12 +0000370 // Otherwise, it must be a GEP.
371 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
372 if (GEPI == 0) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000373
Chris Lattner941db492008-01-14 02:09:12 +0000374 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
375 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
376 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000377
Chris Lattner941db492008-01-14 02:09:12 +0000378 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
379 I != E; ++I)
380 if (!isSafeSROAElementUse(*I))
381 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000382 return true;
383}
384
Chris Lattner941db492008-01-14 02:09:12 +0000385
386/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
387/// Look at it and its uses and decide whether it is safe to SROA this global.
388///
389static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
390 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000391 if (!isa<GetElementPtrInst>(U) &&
392 (!isa<ConstantExpr>(U) ||
Chris Lattner941db492008-01-14 02:09:12 +0000393 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
394 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000395
Chris Lattner941db492008-01-14 02:09:12 +0000396 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
397 // don't like < 3 operand CE's, and we don't like non-constant integer
398 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
399 // value of C.
400 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
401 !cast<Constant>(U->getOperand(1))->isNullValue() ||
402 !isa<ConstantInt>(U->getOperand(2)))
403 return false;
404
405 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
406 ++GEPI; // Skip over the pointer index.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000407
Chris Lattner941db492008-01-14 02:09:12 +0000408 // If this is a use of an array allocation, do a bit more checking for sanity.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000409 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
Chris Lattner941db492008-01-14 02:09:12 +0000410 uint64_t NumElements = AT->getNumElements();
411 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000412
Chris Lattner941db492008-01-14 02:09:12 +0000413 // Check to make sure that index falls within the array. If not,
414 // something funny is going on, so we won't do the optimization.
415 //
416 if (Idx->getZExtValue() >= NumElements)
417 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000418
Chris Lattner941db492008-01-14 02:09:12 +0000419 // We cannot scalar repl this level of the array unless any array
420 // sub-indices are in-range constants. In particular, consider:
421 // A[0][i]. We cannot know that the user isn't doing invalid things like
422 // allowing i to index an out-of-range subscript that accesses A[1].
423 //
424 // Scalar replacing *just* the outer index of the array is probably not
425 // going to be a win anyway, so just give up.
426 for (++GEPI; // Skip array index.
Dan Gohman6874a2a2009-08-18 14:58:19 +0000427 GEPI != E;
Chris Lattner941db492008-01-14 02:09:12 +0000428 ++GEPI) {
429 uint64_t NumElements;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000430 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
Chris Lattner941db492008-01-14 02:09:12 +0000431 NumElements = SubArrayTy->getNumElements();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000432 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
Dan Gohman6874a2a2009-08-18 14:58:19 +0000433 NumElements = SubVectorTy->getNumElements();
434 else {
Duncan Sands1df98592010-02-16 11:11:14 +0000435 assert((*GEPI)->isStructTy() &&
Dan Gohman6874a2a2009-08-18 14:58:19 +0000436 "Indexed GEP type is not array, vector, or struct!");
437 continue;
438 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000439
Chris Lattner941db492008-01-14 02:09:12 +0000440 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
441 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
442 return false;
443 }
444 }
445
446 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
447 if (!isSafeSROAElementUse(*I))
448 return false;
449 return true;
450}
451
452/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
453/// is safe for us to perform this transformation.
454///
455static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
456 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
457 UI != E; ++UI) {
458 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
459 return false;
460 }
461 return true;
462}
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000463
Chris Lattner941db492008-01-14 02:09:12 +0000464
Chris Lattner670c8892004-10-08 17:32:09 +0000465/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
466/// variable. This opens the door for other optimizations by exposing the
467/// behavior of the program in a more fine-grained way. We have determined that
468/// this transformation is safe already. We return the first global variable we
469/// insert so that the caller can reprocess it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000470static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
Chris Lattner727c2102008-01-14 01:31:05 +0000471 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000472 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000473 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000474
Rafael Espindolabb46f522009-01-15 20:18:42 +0000475 assert(GV->hasLocalLinkage() && !GV->isConstant());
Chris Lattner670c8892004-10-08 17:32:09 +0000476 Constant *Init = GV->getInitializer();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000477 Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000478
Chris Lattner670c8892004-10-08 17:32:09 +0000479 std::vector<GlobalVariable*> NewGlobals;
480 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
481
Chris Lattner998182b2008-04-26 07:40:11 +0000482 // Get the alignment of the global, either explicit or target-specific.
483 unsigned StartAlignment = GV->getAlignment();
484 if (StartAlignment == 0)
485 StartAlignment = TD.getABITypeAlignment(GV->getType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000486
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000487 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000488 NewGlobals.reserve(STy->getNumElements());
Chris Lattner998182b2008-04-26 07:40:11 +0000489 const StructLayout &Layout = *TD.getStructLayout(STy);
Chris Lattner670c8892004-10-08 17:32:09 +0000490 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000491 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000492 assert(In && "Couldn't get element of initializer?");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000493 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000494 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000495 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000496 GV->isThreadLocal(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000497 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000498 Globals.insert(GV, NGV);
499 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000500
Chris Lattner998182b2008-04-26 07:40:11 +0000501 // Calculate the known alignment of the field. If the original aggregate
502 // had 256 byte alignment for example, something might depend on that:
503 // propagate info to each field.
504 uint64_t FieldOffset = Layout.getElementOffset(i);
505 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
506 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
507 NGV->setAlignment(NewAlign);
Chris Lattner670c8892004-10-08 17:32:09 +0000508 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000509 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000510 unsigned NumElements = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000511 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000512 NumElements = ATy->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000513 else
Chris Lattner998182b2008-04-26 07:40:11 +0000514 NumElements = cast<VectorType>(STy)->getNumElements();
Chris Lattner670c8892004-10-08 17:32:09 +0000515
Chris Lattner1f21ef12005-02-23 16:53:04 +0000516 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000517 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000518 NewGlobals.reserve(NumElements);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000519
Duncan Sands777d2302009-05-09 07:06:46 +0000520 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner998182b2008-04-26 07:40:11 +0000521 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Chris Lattner670c8892004-10-08 17:32:09 +0000522 for (unsigned i = 0, e = NumElements; i != e; ++i) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000523 Constant *In = Init->getAggregateElement(i);
Chris Lattner670c8892004-10-08 17:32:09 +0000524 assert(In && "Couldn't get element of initializer?");
525
Chris Lattner7b550cc2009-11-06 04:27:31 +0000526 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
Chris Lattner670c8892004-10-08 17:32:09 +0000527 GlobalVariable::InternalLinkage,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000528 In, GV->getName()+"."+Twine(i),
Matthijs Kooijmanbc1f9892008-07-17 11:59:53 +0000529 GV->isThreadLocal(),
Owen Andersone9b11b42009-07-08 19:03:57 +0000530 GV->getType()->getAddressSpace());
Chris Lattner670c8892004-10-08 17:32:09 +0000531 Globals.insert(GV, NGV);
532 NewGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000533
Chris Lattner998182b2008-04-26 07:40:11 +0000534 // 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);
Chris Lattner670c8892004-10-08 17:32:09 +0000540 }
541 }
542
543 if (NewGlobals.empty())
544 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000545
David Greene3215b0e2010-01-05 01:28:05 +0000546 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000547
Chris Lattner7b550cc2009-11-06 04:27:31 +0000548 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
Chris Lattner670c8892004-10-08 17:32:09 +0000549
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()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000553 User *GEP = GV->use_back();
554 assert(((isa<ConstantExpr>(GEP) &&
555 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
556 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000557
Chris Lattner670c8892004-10-08 17:32:09 +0000558 // 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
560 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000561 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000562 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
563
Chris Lattner30ba5692004-10-11 05:54:41 +0000564 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000565
566 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000567 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000568 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000569 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000570 Idxs.push_back(NullInt);
571 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
572 Idxs.push_back(CE->getOperand(i));
Jay Foaddab3d292011-07-21 14:31:17 +0000573 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
Chris Lattner30ba5692004-10-11 05:54:41 +0000574 } else {
575 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000576 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000577 Idxs.push_back(NullInt);
578 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
579 Idxs.push_back(GEPI->getOperand(i));
Jay Foada9203102011-07-25 09:48:08 +0000580 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000581 GEPI->getName()+"."+Twine(Val),GEPI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000582 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000583 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000584 GEP->replaceAllUsesWith(NewPtr);
585
586 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000587 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000588 else
589 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000590 }
591
Chris Lattnere40e2d12004-10-08 20:25:55 +0000592 // Delete the old global, now that it is dead.
593 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000594 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000595
596 // Loop over the new globals array deleting any globals that are obviously
597 // dead. This can arise due to scalarization of a structure or an array that
598 // has elements that are dead.
599 unsigned FirstGlobal = 0;
600 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
601 if (NewGlobals[i]->use_empty()) {
602 Globals.erase(NewGlobals[i]);
603 if (FirstGlobal == i) ++FirstGlobal;
604 }
605
606 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000607}
608
Chris Lattner9b34a612004-10-09 21:48:45 +0000609/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000610/// value will trap if the value is dynamically null. PHIs keeps track of any
Chris Lattner81686182007-09-13 16:30:19 +0000611/// phi nodes we've seen to avoid reprocessing them.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000612static bool AllUsesOfValueWillTrapIfNull(const Value *V,
613 SmallPtrSet<const PHINode*, 8> &PHIs) {
614 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000615 ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000616 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000617
618 if (isa<LoadInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000619 // Will trap.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000620 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000621 if (SI->getOperand(0) == V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000622 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000623 return false; // Storing the value.
624 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000625 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000626 if (CI->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000627 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000628 return false; // Not calling the ptr
629 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000630 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
Gabor Greif654c06f2010-03-20 21:00:25 +0000631 if (II->getCalledValue() != V) {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000632 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000633 return false; // Not calling the ptr
634 }
Gabor Greif6ce02b52010-04-06 19:24:18 +0000635 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000636 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000637 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000638 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
Gabor Greif6ce02b52010-04-06 19:24:18 +0000639 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
Chris Lattner81686182007-09-13 16:30:19 +0000640 // If we've already seen this phi node, ignore it, it has already been
641 // checked.
Jakob Stoklund Olesenb489d0f2010-01-29 23:54:14 +0000642 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
643 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000644 } else if (isa<ICmpInst>(U) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000645 isa<ConstantPointerNull>(UI->getOperand(1))) {
Nick Lewyckye7ee59b2010-02-25 06:39:10 +0000646 // Ignore icmp X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000647 } else {
Gabor Greifa01d6db2010-04-06 19:14:05 +0000648 //cerr << "NONTRAPPING USE: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000649 return false;
650 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000651 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000652 return true;
653}
654
655/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000656/// from GV will trap if the loaded value is null. Note that this also permits
657/// comparisons of the loaded value against null, as a special case.
Gabor Greif6ce02b52010-04-06 19:24:18 +0000658static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
659 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000660 UI != E; ++UI) {
Gabor Greif6ce02b52010-04-06 19:24:18 +0000661 const User *U = *UI;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000662
Gabor Greif6ce02b52010-04-06 19:24:18 +0000663 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
664 SmallPtrSet<const PHINode*, 8> PHIs;
Chris Lattner81686182007-09-13 16:30:19 +0000665 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000666 return false;
Gabor Greifa01d6db2010-04-06 19:14:05 +0000667 } else if (isa<StoreInst>(U)) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000668 // Ignore stores to the global.
669 } else {
670 // We don't know or understand this user, bail out.
Gabor Greifa01d6db2010-04-06 19:14:05 +0000671 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
Chris Lattner9b34a612004-10-09 21:48:45 +0000672 return false;
673 }
Gabor Greifa01d6db2010-04-06 19:14:05 +0000674 }
Chris Lattner9b34a612004-10-09 21:48:45 +0000675 return true;
676}
677
Chris Lattner7b550cc2009-11-06 04:27:31 +0000678static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000679 bool Changed = false;
680 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
681 Instruction *I = cast<Instruction>(*UI++);
682 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
683 LI->setOperand(0, NewV);
684 Changed = true;
685 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
686 if (SI->getOperand(1) == V) {
687 SI->setOperand(1, NewV);
688 Changed = true;
689 }
690 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000691 CallSite CS(I);
692 if (CS.getCalledValue() == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000693 // Calling through the pointer! Turn into a direct call, but be careful
694 // that the pointer is not also being passed as an argument.
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000695 CS.setCalledFunction(NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000696 Changed = true;
697 bool PassedAsArg = false;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000698 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
699 if (CS.getArgument(i) == V) {
Chris Lattner708148e2004-10-10 23:14:11 +0000700 PassedAsArg = true;
Gabor Greiffa1f5c22010-04-06 18:45:08 +0000701 CS.setArgument(i, NewV);
Chris Lattner708148e2004-10-10 23:14:11 +0000702 }
703
704 if (PassedAsArg) {
705 // Being passed as an argument also. Be careful to not invalidate UI!
706 UI = V->use_begin();
707 }
708 }
709 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
710 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000711 ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner7b550cc2009-11-06 04:27:31 +0000712 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000713 if (CI->use_empty()) {
714 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000715 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000716 }
717 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
718 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000719 SmallVector<Constant*, 8> Idxs;
720 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif5e463212008-05-29 01:59:18 +0000721 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
722 i != e; ++i)
723 if (Constant *C = dyn_cast<Constant>(*i))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000724 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000725 else
726 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000727 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000728 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Jay Foaddab3d292011-07-21 14:31:17 +0000729 ConstantExpr::getGetElementPtr(NewV, Idxs));
Chris Lattner708148e2004-10-10 23:14:11 +0000730 if (GEPI->use_empty()) {
731 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000732 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000733 }
734 }
735 }
736
737 return Changed;
738}
739
740
741/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
742/// value stored into it. If there are uses of the loaded value that would trap
743/// if the loaded value is dynamically null, then we know that they cannot be
744/// reachable with a null optimize away the load.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000745static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
Chris Lattner708148e2004-10-10 23:14:11 +0000746 bool Changed = false;
747
Chris Lattner92c6bd22009-01-14 00:12:58 +0000748 // Keep track of whether we are able to remove all the uses of the global
749 // other than the store that defines it.
750 bool AllNonStoreUsesGone = true;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000751
Chris Lattner708148e2004-10-10 23:14:11 +0000752 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000753 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
754 User *GlobalUser = *GUI++;
755 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000756 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
Chris Lattner92c6bd22009-01-14 00:12:58 +0000757 // If we were able to delete all uses of the loads
758 if (LI->use_empty()) {
759 LI->eraseFromParent();
760 Changed = true;
761 } else {
762 AllNonStoreUsesGone = false;
763 }
764 } else if (isa<StoreInst>(GlobalUser)) {
765 // Ignore the store that stores "LV" to the global.
766 assert(GlobalUser->getOperand(1) == GV &&
767 "Must be storing *to* the global");
Chris Lattner708148e2004-10-10 23:14:11 +0000768 } else {
Chris Lattner92c6bd22009-01-14 00:12:58 +0000769 AllNonStoreUsesGone = false;
770
771 // If we get here we could have other crazy uses that are transitively
772 // loaded.
773 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
Chris Lattner98a42b22011-05-22 07:15:13 +0000774 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser)) &&
775 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000776 }
Chris Lattner92c6bd22009-01-14 00:12:58 +0000777 }
Chris Lattner708148e2004-10-10 23:14:11 +0000778
779 if (Changed) {
David Greene3215b0e2010-01-05 01:28:05 +0000780 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Chris Lattner708148e2004-10-10 23:14:11 +0000781 ++NumGlobUses;
782 }
783
Chris Lattner708148e2004-10-10 23:14:11 +0000784 // If we nuked all of the loads, then none of the stores are needed either,
785 // nor is the global.
Chris Lattner92c6bd22009-01-14 00:12:58 +0000786 if (AllNonStoreUsesGone) {
David Greene3215b0e2010-01-05 01:28:05 +0000787 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
Chris Lattner7b550cc2009-11-06 04:27:31 +0000788 CleanupConstantGlobalUsers(GV, 0);
Chris Lattner708148e2004-10-10 23:14:11 +0000789 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000790 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000791 ++NumDeleted;
792 }
793 Changed = true;
794 }
795 return Changed;
796}
797
Chris Lattner30ba5692004-10-11 05:54:41 +0000798/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
799/// instructions that are foldable.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000800static void ConstantPropUsersOf(Value *V) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000801 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
802 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Chad Rosieraab8e282011-12-02 01:26:24 +0000803 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000804 if (Constant *NewC = ConstantFoldInstruction(I)) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000805 I->replaceAllUsesWith(NewC);
806
Chris Lattnerd514d822005-02-01 01:23:31 +0000807 // Advance UI to the next non-I use to avoid invalidating it!
808 // Instructions could multiply use V.
809 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000810 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000811 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000812 }
813}
814
815/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
816/// variable, and transforms the program as if it always contained the result of
817/// the specified malloc. Because it is always the result of the specified
818/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000819/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000820static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +0000821 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000822 Type *AllocTy,
Chris Lattnera6874652010-02-25 22:33:52 +0000823 ConstantInt *NElements,
Victor Hernandez83d63912009-09-18 22:35:49 +0000824 TargetData* TD) {
Chris Lattnera6874652010-02-25 22:33:52 +0000825 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000826
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000827 Type *GlobalType;
Chris Lattnera6874652010-02-25 22:33:52 +0000828 if (NElements->getZExtValue() == 1)
829 GlobalType = AllocTy;
830 else
831 // If we have an array allocation, the global variable is of an array.
832 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
Victor Hernandez83d63912009-09-18 22:35:49 +0000833
834 // Create the new global variable. The contents of the malloc'd memory is
835 // undefined, so initialize with an undef value.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000836 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
Chris Lattnere9fd4442010-02-26 23:42:13 +0000837 GlobalType, false,
Chris Lattnera6874652010-02-25 22:33:52 +0000838 GlobalValue::InternalLinkage,
Chris Lattnere9fd4442010-02-26 23:42:13 +0000839 UndefValue::get(GlobalType),
Victor Hernandez83d63912009-09-18 22:35:49 +0000840 GV->getName()+".body",
841 GV,
842 GV->isThreadLocal());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000843
Chris Lattnera6874652010-02-25 22:33:52 +0000844 // If there are bitcast users of the malloc (which is typical, usually we have
845 // a malloc + bitcast) then replace them with uses of the new global. Update
846 // other users to use the global as well.
847 BitCastInst *TheBC = 0;
848 while (!CI->use_empty()) {
849 Instruction *User = cast<Instruction>(CI->use_back());
850 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
851 if (BCI->getType() == NewGV->getType()) {
852 BCI->replaceAllUsesWith(NewGV);
853 BCI->eraseFromParent();
854 } else {
855 BCI->setOperand(0, NewGV);
856 }
857 } else {
858 if (TheBC == 0)
859 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
860 User->replaceUsesOfWith(CI, TheBC);
861 }
862 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000863
Victor Hernandez83d63912009-09-18 22:35:49 +0000864 Constant *RepValue = NewGV;
865 if (NewGV->getType() != GV->getType()->getElementType())
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000866 RepValue = ConstantExpr::getBitCast(RepValue,
Victor Hernandez83d63912009-09-18 22:35:49 +0000867 GV->getType()->getElementType());
868
869 // If there is a comparison against null, we will insert a global bool to
870 // keep track of whether the global was initialized yet or not.
871 GlobalVariable *InitBool =
Chris Lattner7b550cc2009-11-06 04:27:31 +0000872 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
Victor Hernandez83d63912009-09-18 22:35:49 +0000873 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000874 ConstantInt::getFalse(GV->getContext()),
875 GV->getName()+".init", GV->isThreadLocal());
Victor Hernandez83d63912009-09-18 22:35:49 +0000876 bool InitBoolUsed = false;
877
878 // Loop over all uses of GV, processing them in turn.
Chris Lattnera6874652010-02-25 22:33:52 +0000879 while (!GV->use_empty()) {
880 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000881 // The global is initialized when the store to it occurs.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000882 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
Victor Hernandez83d63912009-09-18 22:35:49 +0000883 SI->eraseFromParent();
Chris Lattnera6874652010-02-25 22:33:52 +0000884 continue;
Victor Hernandez83d63912009-09-18 22:35:49 +0000885 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000886
Chris Lattnera6874652010-02-25 22:33:52 +0000887 LoadInst *LI = cast<LoadInst>(GV->use_back());
888 while (!LI->use_empty()) {
889 Use &LoadUse = LI->use_begin().getUse();
890 if (!isa<ICmpInst>(LoadUse.getUser())) {
891 LoadUse = RepValue;
892 continue;
893 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000894
Chris Lattnera6874652010-02-25 22:33:52 +0000895 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
896 // Replace the cmp X, 0 with a use of the bool value.
897 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
898 InitBoolUsed = true;
899 switch (ICI->getPredicate()) {
900 default: llvm_unreachable("Unknown ICmp Predicate!");
901 case ICmpInst::ICMP_ULT:
902 case ICmpInst::ICMP_SLT: // X < null -> always false
903 LV = ConstantInt::getFalse(GV->getContext());
904 break;
905 case ICmpInst::ICMP_ULE:
906 case ICmpInst::ICMP_SLE:
907 case ICmpInst::ICMP_EQ:
908 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
909 break;
910 case ICmpInst::ICMP_NE:
911 case ICmpInst::ICMP_UGE:
912 case ICmpInst::ICMP_SGE:
913 case ICmpInst::ICMP_UGT:
914 case ICmpInst::ICMP_SGT:
915 break; // no change.
916 }
917 ICI->replaceAllUsesWith(LV);
918 ICI->eraseFromParent();
919 }
920 LI->eraseFromParent();
921 }
Victor Hernandez83d63912009-09-18 22:35:49 +0000922
923 // If the initialization boolean was used, insert it, otherwise delete it.
924 if (!InitBoolUsed) {
925 while (!InitBool->use_empty()) // Delete initializations
Chris Lattnera6874652010-02-25 22:33:52 +0000926 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000927 delete InitBool;
928 } else
929 GV->getParent()->getGlobalList().insert(GV, InitBool);
930
Chris Lattnera6874652010-02-25 22:33:52 +0000931 // Now the GV is dead, nuke it and the malloc..
Victor Hernandez83d63912009-09-18 22:35:49 +0000932 GV->eraseFromParent();
Victor Hernandez83d63912009-09-18 22:35:49 +0000933 CI->eraseFromParent();
934
935 // To further other optimizations, loop over all users of NewGV and try to
936 // constant prop them. This will promote GEP instructions with constant
937 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000938 ConstantPropUsersOf(NewGV);
Victor Hernandez83d63912009-09-18 22:35:49 +0000939 if (RepValue != NewGV)
Chris Lattner7b550cc2009-11-06 04:27:31 +0000940 ConstantPropUsersOf(RepValue);
Victor Hernandez83d63912009-09-18 22:35:49 +0000941
942 return NewGV;
943}
944
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000945/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
946/// to make sure that there are no complex uses of V. We permit simple things
947/// like dereferencing the pointer, but not storing through the address, unless
948/// it is to the specified global.
Gabor Greif0b520db2010-04-06 18:58:22 +0000949static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
950 const GlobalVariable *GV,
Gabor Greifa01d6db2010-04-06 19:14:05 +0000951 SmallPtrSet<const PHINode*, 8> &PHIs) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000952 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greifa01d6db2010-04-06 19:14:05 +0000953 UI != E; ++UI) {
Gabor Greif0b520db2010-04-06 18:58:22 +0000954 const Instruction *Inst = cast<Instruction>(*UI);
Gabor Greifa01d6db2010-04-06 19:14:05 +0000955
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000956 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
957 continue; // Fine, ignore.
958 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000959
Gabor Greif0b520db2010-04-06 18:58:22 +0000960 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000961 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
962 return false; // Storing the pointer itself... bad.
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000963 continue; // Otherwise, storing through it, or storing into GV... fine.
964 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000965
Chris Lattnera2fb2342010-04-10 18:19:22 +0000966 // Must index into the array and into the struct.
967 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000968 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000969 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000970 continue;
971 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000972
Gabor Greif0b520db2010-04-06 18:58:22 +0000973 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000974 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
975 // cycles.
976 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000977 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
978 return false;
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000979 continue;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000980 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000981
Gabor Greif0b520db2010-04-06 18:58:22 +0000982 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000983 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
984 return false;
985 continue;
986 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000987
Chris Lattner49b6d4a2008-12-15 21:08:54 +0000988 return false;
989 }
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000990 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000991}
992
Chris Lattner86395032006-09-30 23:32:09 +0000993/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
994/// somewhere. Transform all uses of the allocation into loads from the
995/// global and uses of the resultant pointer. Further, delete the store into
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000996/// GV. This assumes that these value pass the
Chris Lattner86395032006-09-30 23:32:09 +0000997/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +0000998static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
Chris Lattner86395032006-09-30 23:32:09 +0000999 GlobalVariable *GV) {
1000 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001001 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1002 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +00001003 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1004 // If this is the store of the allocation into the global, remove it.
1005 if (SI->getOperand(1) == GV) {
1006 SI->eraseFromParent();
1007 continue;
1008 }
Chris Lattnera637a8b2007-09-13 18:00:31 +00001009 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1010 // Insert the load in the corresponding predecessor, not right before the
1011 // PHI.
Gabor Greifa36791d2009-01-23 19:40:15 +00001012 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner101f44e2008-12-15 21:44:34 +00001013 } else if (isa<BitCastInst>(U)) {
1014 // Must be bitcast between the malloc and store to initialize the global.
1015 ReplaceUsesOfMallocWithGlobal(U, GV);
1016 U->eraseFromParent();
1017 continue;
1018 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1019 // If this is a "GEP bitcast" and the user is a store to the global, then
1020 // just process it as a bitcast.
1021 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1022 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1023 if (SI->getOperand(1) == GV) {
1024 // Must be bitcast GEP between the malloc and store to initialize
1025 // the global.
1026 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1027 GEPI->eraseFromParent();
1028 continue;
1029 }
Chris Lattner86395032006-09-30 23:32:09 +00001030 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001031
Chris Lattner86395032006-09-30 23:32:09 +00001032 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001033 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +00001034 U->replaceUsesOfWith(Alloc, NL);
1035 }
1036}
1037
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001038/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1039/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1040/// that index through the array and struct field, icmps of null, and PHIs.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001041static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
Gabor Greif27236912010-04-07 18:59:26 +00001042 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1043 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001044 // We permit two users of the load: setcc comparing against the null
1045 // pointer, and a getelementptr of a specific form.
Gabor Greif27236912010-04-07 18:59:26 +00001046 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1047 ++UI) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001048 const Instruction *User = cast<Instruction>(*UI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001049
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001050 // Comparison against null is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001051 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001052 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1053 return false;
1054 continue;
1055 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001056
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001057 // getelementptr is also ok, but only a simple form.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001058 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001059 // Must index into the array and into the struct.
1060 if (GEPI->getNumOperands() < 3)
1061 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001062
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001063 // Otherwise the GEP is ok.
1064 continue;
1065 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001066
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001067 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001068 if (!LoadUsingPHIsPerLoad.insert(PN))
1069 // This means some phi nodes are dependent on each other.
1070 // Avoid infinite looping!
1071 return false;
1072 if (!LoadUsingPHIs.insert(PN))
1073 // If we have already analyzed this PHI, then it is safe.
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001074 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001075
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001076 // Make sure all uses of the PHI are simple enough to transform.
Evan Cheng5d163962009-06-02 00:56:07 +00001077 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1078 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001079 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001080
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001081 continue;
Chris Lattner86395032006-09-30 23:32:09 +00001082 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001083
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001084 // Otherwise we don't know what this is, not ok.
1085 return false;
1086 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001087
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001088 return true;
1089}
1090
1091
1092/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1093/// GV are simple enough to perform HeapSRA, return true.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001094static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001095 Instruction *StoredVal) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001096 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1097 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
Gabor Greif27236912010-04-07 18:59:26 +00001098 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1099 UI != E; ++UI)
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001100 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Evan Cheng5d163962009-06-02 00:56:07 +00001101 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1102 LoadUsingPHIsPerLoad))
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001103 return false;
Evan Cheng5d163962009-06-02 00:56:07 +00001104 LoadUsingPHIsPerLoad.clear();
1105 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001106
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001107 // If we reach here, we know that all uses of the loads and transitive uses
1108 // (through PHI nodes) are simple enough to transform. However, we don't know
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001109 // that all inputs the to the PHI nodes are in the same equivalence sets.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001110 // Check to verify that all operands of the PHIs are either PHIS that can be
1111 // transformed, loads from GV, or MI itself.
Gabor Greif27236912010-04-07 18:59:26 +00001112 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1113 , E = LoadUsingPHIs.end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001114 const PHINode *PN = *I;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001115 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1116 Value *InVal = PN->getIncomingValue(op);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001117
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001118 // PHI of the stored value itself is ok.
Victor Hernandez83d63912009-09-18 22:35:49 +00001119 if (InVal == StoredVal) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001120
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001121 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001122 // One of the PHIs in our set is (optimistically) ok.
1123 if (LoadUsingPHIs.count(InPN))
1124 continue;
1125 return false;
1126 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001127
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001128 // Load from GV is ok.
Gabor Greifc8b82cc2010-04-01 08:21:08 +00001129 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001130 if (LI->getOperand(0) == GV)
1131 continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001132
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001133 // UNDEF? NULL?
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001134
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001135 // Anything else is rejected.
1136 return false;
1137 }
1138 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001139
Chris Lattner86395032006-09-30 23:32:09 +00001140 return true;
1141}
1142
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001143static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1144 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001145 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001146 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001147
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001148 if (FieldNo >= FieldVals.size())
1149 FieldVals.resize(FieldNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001150
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001151 // If we already have this value, just reuse the previously scalarized
1152 // version.
1153 if (Value *FieldVal = FieldVals[FieldNo])
1154 return FieldVal;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001155
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001156 // Depending on what instruction this is, we have several cases.
1157 Value *Result;
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,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001163 PHIsToRewrite),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001164 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001165 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1166 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1167 // field.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001168 StructType *ST =
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001169 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001170
Jay Foadd8b4fb42011-03-30 11:19:20 +00001171 PHINode *NewPN =
Owen Andersondebcb012009-07-29 22:17:13 +00001172 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Jay Foad3ecfc862011-03-30 11:28:46 +00001173 PN->getNumIncomingValues(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001174 PN->getName()+".f"+Twine(FieldNo), PN);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001175 Result = NewPN;
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001176 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1177 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001178 llvm_unreachable("Unknown usable value");
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001179 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001180
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001181 return FieldVals[FieldNo] = Result;
Chris Lattnera637a8b2007-09-13 18:00:31 +00001182}
1183
Chris Lattner330245e2007-09-13 17:29:05 +00001184/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1185/// the load, rewrite the derived value to use the HeapSRoA'd load.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001186static void RewriteHeapSROALoadUser(Instruction *LoadUser,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001187 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001188 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattner330245e2007-09-13 17:29:05 +00001189 // If this is a comparison against null, handle it.
1190 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1191 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1192 // If we have a setcc of the loaded pointer, we can use a setcc of any
1193 // field.
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001194 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001195 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001196
Owen Anderson333c4002009-07-09 23:48:35 +00001197 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001198 Constant::getNullValue(NPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001199 SCI->getName());
Chris Lattner330245e2007-09-13 17:29:05 +00001200 SCI->replaceAllUsesWith(New);
1201 SCI->eraseFromParent();
1202 return;
1203 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001204
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001205 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattnera637a8b2007-09-13 18:00:31 +00001206 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1207 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1208 && "Unexpected GEPI!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001209
Chris Lattnera637a8b2007-09-13 18:00:31 +00001210 // Load the pointer for this field.
1211 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001212 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001213 InsertedScalarizedValues, PHIsToRewrite);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001214
Chris Lattnera637a8b2007-09-13 18:00:31 +00001215 // Create the new GEP idx vector.
1216 SmallVector<Value*, 8> GEPIdx;
1217 GEPIdx.push_back(GEPI->getOperand(1));
1218 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001219
Jay Foada9203102011-07-25 09:48:08 +00001220 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
Gabor Greif051a9502008-04-06 20:25:17 +00001221 GEPI->getName(), GEPI);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001222 GEPI->replaceAllUsesWith(NGEPI);
1223 GEPI->eraseFromParent();
1224 return;
1225 }
Chris Lattner309f20f2007-09-13 21:31:36 +00001226
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001227 // Recursively transform the users of PHI nodes. This will lazily create the
1228 // PHIs that are needed for individual elements. Keep track of what PHIs we
1229 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1230 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1231 // already been seen first by another load, so its uses have already been
1232 // processed.
1233 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001234 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1235 std::vector<Value*>())).second)
1236 return;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001237
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001238 // If this is the first time we've seen this PHI, recursively process all
1239 // users.
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001240 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1241 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001242 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001243 }
Chris Lattner330245e2007-09-13 17:29:05 +00001244}
1245
Chris Lattner86395032006-09-30 23:32:09 +00001246/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1247/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1248/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner85d3d4f2008-12-16 21:24:51 +00001249/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001250static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001251 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001252 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001253 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001254 UI != E; ) {
1255 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001256 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
Chris Lattnerf49a28c2008-12-17 05:42:08 +00001257 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001258
Chris Lattnerbce4afe2008-12-17 05:28:49 +00001259 if (Load->use_empty()) {
1260 Load->eraseFromParent();
1261 InsertedScalarizedValues.erase(Load);
1262 }
Chris Lattner86395032006-09-30 23:32:09 +00001263}
1264
Victor Hernandez83d63912009-09-18 22:35:49 +00001265/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1266/// it up into multiple allocations of arrays of the fields.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001267static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1268 Value* NElems, TargetData *TD) {
David Greene3215b0e2010-01-05 01:28:05 +00001269 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001270 Type* MAT = getMallocAllocatedType(CI);
1271 StructType *STy = cast<StructType>(MAT);
Victor Hernandez83d63912009-09-18 22:35:49 +00001272
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
1276 // into GV.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001277 ReplaceUsesOfMallocWithGlobal(CI, GV);
1278
Victor Hernandez83d63912009-09-18 22:35:49 +00001279 // 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;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001283
Victor Hernandez83d63912009-09-18 22:35:49 +00001284 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001285 Type *FieldTy = STy->getElementType(FieldNo);
1286 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001287
Victor Hernandez83d63912009-09-18 22:35:49 +00001288 GlobalVariable *NGV =
1289 new GlobalVariable(*GV->getParent(),
1290 PFieldTy, false, GlobalValue::InternalLinkage,
1291 Constant::getNullValue(PFieldTy),
1292 GV->getName() + ".f" + Twine(FieldNo), GV,
1293 GV->isThreadLocal());
1294 FieldGlobals.push_back(NGV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001295
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001296 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001297 if (StructType *ST = dyn_cast<StructType>(FieldTy))
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001298 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001299 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001300 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1301 ConstantInt::get(IntPtrTy, TypeSize),
Chris Lattner5a30a852010-07-12 00:57:28 +00001302 NElems, 0,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001303 CI->getName() + ".f" + Twine(FieldNo));
Chris Lattner3f5e0b82010-02-26 18:23:13 +00001304 FieldMallocs.push_back(NMI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001305 new StoreInst(NMI, NGV, CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001306 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001307
Victor Hernandez83d63912009-09-18 22:35:49 +00001308 // The tricky aspect of this transformation is handling the case when malloc
1309 // fails. In the original code, malloc failing would set the result pointer
1310 // of malloc to null. In this case, some mallocs could succeed and others
1311 // could fail. As such, we emit code that looks like this:
1312 // F0 = malloc(field0)
1313 // F1 = malloc(field1)
1314 // F2 = malloc(field2)
1315 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1316 // if (F0) { free(F0); F0 = 0; }
1317 // if (F1) { free(F1); F1 = 0; }
1318 // if (F2) { free(F2); F2 = 0; }
1319 // }
Victor Hernandez8e345a12009-11-10 08:32:25 +00001320 // The malloc can also fail if its argument is too large.
Gabor Greif9e4f2432010-06-24 14:42:01 +00001321 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1322 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
Victor Hernandez8e345a12009-11-10 08:32:25 +00001323 ConstantZero, "isneg");
Victor Hernandez83d63912009-09-18 22:35:49 +00001324 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001325 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1326 Constant::getNullValue(FieldMallocs[i]->getType()),
1327 "isnull");
Victor Hernandez8e345a12009-11-10 08:32:25 +00001328 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001329 }
1330
1331 // Split the basic block at the old malloc.
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001332 BasicBlock *OrigBB = CI->getParent();
1333 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001334
Victor Hernandez83d63912009-09-18 22:35:49 +00001335 // Create the block to check the first condition. Put all these blocks at the
1336 // end of the function as they are unlikely to be executed.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001337 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1338 "malloc_ret_null",
Victor Hernandez83d63912009-09-18 22:35:49 +00001339 OrigBB->getParent());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001340
Victor Hernandez83d63912009-09-18 22:35:49 +00001341 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1342 // branch on RunningOr.
1343 OrigBB->getTerminator()->eraseFromParent();
1344 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001345
Victor Hernandez83d63912009-09-18 22:35:49 +00001346 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1347 // pointer, because some may be null while others are not.
1348 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1349 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001350 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +00001351 Constant::getNullValue(GVVal->getType()));
Chris Lattner7b550cc2009-11-06 04:27:31 +00001352 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
Victor Hernandez83d63912009-09-18 22:35:49 +00001353 OrigBB->getParent());
Chris Lattner7b550cc2009-11-06 04:27:31 +00001354 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
Victor Hernandez83d63912009-09-18 22:35:49 +00001355 OrigBB->getParent());
Victor Hernandez66284e02009-10-24 04:23:03 +00001356 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1357 Cmp, NullPtrBlock);
Victor Hernandez83d63912009-09-18 22:35:49 +00001358
1359 // Fill in FreeBlock.
Victor Hernandez66284e02009-10-24 04:23:03 +00001360 CallInst::CreateFree(GVVal, BI);
Victor Hernandez83d63912009-09-18 22:35:49 +00001361 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1362 FreeBlock);
1363 BranchInst::Create(NextBlock, FreeBlock);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001364
Victor Hernandez83d63912009-09-18 22:35:49 +00001365 NullPtrBlock = NextBlock;
1366 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001367
Victor Hernandez83d63912009-09-18 22:35:49 +00001368 BranchInst::Create(ContBB, NullPtrBlock);
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001369
1370 // CI is no longer needed, remove it.
Victor Hernandez83d63912009-09-18 22:35:49 +00001371 CI->eraseFromParent();
1372
1373 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1374 /// update all uses of the load, keep track of what scalarized loads are
1375 /// inserted for a given load.
1376 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1377 InsertedScalarizedValues[GV] = FieldGlobals;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001378
Victor Hernandez83d63912009-09-18 22:35:49 +00001379 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001380
Victor Hernandez83d63912009-09-18 22:35:49 +00001381 // Okay, the malloc site is completely handled. All of the uses of GV are now
1382 // loads, and all uses of those loads are simple. Rewrite them to use loads
1383 // of the per-field globals instead.
1384 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1385 Instruction *User = cast<Instruction>(*UI++);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001386
Victor Hernandez83d63912009-09-18 22:35:49 +00001387 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +00001388 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001389 continue;
1390 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001391
Victor Hernandez83d63912009-09-18 22:35:49 +00001392 // Must be a store of null.
1393 StoreInst *SI = cast<StoreInst>(User);
1394 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1395 "Unexpected heap-sra user!");
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001396
Victor Hernandez83d63912009-09-18 22:35:49 +00001397 // Insert a store of null into each global.
1398 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001399 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Victor Hernandez83d63912009-09-18 22:35:49 +00001400 Constant *Null = Constant::getNullValue(PT->getElementType());
1401 new StoreInst(Null, FieldGlobals[i], SI);
1402 }
1403 // Erase the original store.
1404 SI->eraseFromParent();
1405 }
1406
1407 // While we have PHIs that are interesting to rewrite, do it.
1408 while (!PHIsToRewrite.empty()) {
1409 PHINode *PN = PHIsToRewrite.back().first;
1410 unsigned FieldNo = PHIsToRewrite.back().second;
1411 PHIsToRewrite.pop_back();
1412 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1413 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1414
1415 // Add all the incoming values. This can materialize more phis.
1416 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1417 Value *InVal = PN->getIncomingValue(i);
1418 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001419 PHIsToRewrite);
Victor Hernandez83d63912009-09-18 22:35:49 +00001420 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1421 }
1422 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001423
Victor Hernandez83d63912009-09-18 22:35:49 +00001424 // Drop all inter-phi links and any loads that made it this far.
1425 for (DenseMap<Value*, std::vector<Value*> >::iterator
1426 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1427 I != E; ++I) {
1428 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1429 PN->dropAllReferences();
1430 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1431 LI->dropAllReferences();
1432 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001433
Victor Hernandez83d63912009-09-18 22:35:49 +00001434 // Delete all the phis and loads now that inter-references are dead.
1435 for (DenseMap<Value*, std::vector<Value*> >::iterator
1436 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1437 I != E; ++I) {
1438 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1439 PN->eraseFromParent();
1440 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1441 LI->eraseFromParent();
1442 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001443
Victor Hernandez83d63912009-09-18 22:35:49 +00001444 // The old global is now dead, remove it.
1445 GV->eraseFromParent();
1446
1447 ++NumHeapSRA;
1448 return cast<GlobalVariable>(FieldGlobals[0]);
1449}
1450
Chris Lattnere61d0a62008-12-15 21:02:25 +00001451/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1452/// pointer global variable with a single value stored it that is a malloc or
1453/// cast of malloc.
1454static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez83d63912009-09-18 22:35:49 +00001455 CallInst *CI,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001456 Type *AllocTy,
Victor Hernandez83d63912009-09-18 22:35:49 +00001457 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001458 TargetData *TD) {
Evan Cheng86cd4452010-04-14 20:52:55 +00001459 if (!TD)
1460 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001461
Victor Hernandez83d63912009-09-18 22:35:49 +00001462 // If this is a malloc of an abstract type, don't touch it.
1463 if (!AllocTy->isSized())
1464 return false;
1465
1466 // We can't optimize this global unless all uses of it are *known* to be
1467 // of the malloc value, not of the null initializer value (consider a use
1468 // that compares the global's value against zero to see if the malloc has
1469 // been reached). To do this, we check to see if all uses of the global
1470 // would trap if the global were null: this proves that they must all
1471 // happen after the malloc.
1472 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1473 return false;
1474
1475 // We can't optimize this if the malloc itself is used in a complex way,
1476 // for example, being stored into multiple globals. This allows the
1477 // malloc to be stored into the specified global, loaded setcc'd, and
1478 // GEP'd. These are all things we could transform to using the global
1479 // for.
Evan Cheng86cd4452010-04-14 20:52:55 +00001480 SmallPtrSet<const PHINode*, 8> PHIs;
1481 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1482 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001483
1484 // If we have a global that is only initialized with a fixed size malloc,
1485 // transform the program to use global memory instead of malloc'd memory.
1486 // This eliminates dynamic allocation, avoids an indirection accessing the
1487 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez8db42d22009-10-16 23:12:25 +00001488 // We cannot optimize the malloc if we cannot determine malloc array size.
Evan Cheng86cd4452010-04-14 20:52:55 +00001489 Value *NElems = getMallocArraySize(CI, TD, true);
1490 if (!NElems)
1491 return false;
Victor Hernandez83d63912009-09-18 22:35:49 +00001492
Evan Cheng86cd4452010-04-14 20:52:55 +00001493 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1494 // Restrict this transformation to only working on small allocations
1495 // (2048 bytes currently), as we don't want to introduce a 16M global or
1496 // something.
1497 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1498 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
1499 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001500 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001501
Evan Cheng86cd4452010-04-14 20:52:55 +00001502 // If the allocation is an array of structures, consider transforming this
1503 // into multiple malloc'd arrays, one for each field. This is basically
1504 // SRoA for malloc'd memory.
1505
1506 // If this is an allocation of a fixed size array of structs, analyze as a
1507 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
Gabor Greif9e4f2432010-06-24 14:42:01 +00001508 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001509 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
Evan Cheng86cd4452010-04-14 20:52:55 +00001510 AllocTy = AT->getElementType();
Gabor Greif9e4f2432010-06-24 14:42:01 +00001511
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001512 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
Evan Cheng86cd4452010-04-14 20:52:55 +00001513 if (!AllocSTy)
1514 return false;
1515
1516 // This the structure has an unreasonable number of fields, leave it
1517 // alone.
1518 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1519 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1520
1521 // If this is a fixed size array, transform the Malloc to be an alloc of
1522 // structs. malloc [100 x struct],1 -> malloc struct, 100
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001523 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1524 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
Evan Cheng86cd4452010-04-14 20:52:55 +00001525 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1526 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1527 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1528 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1529 AllocSize, NumElements,
Chris Lattner5a30a852010-07-12 00:57:28 +00001530 0, CI->getName());
Evan Cheng86cd4452010-04-14 20:52:55 +00001531 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1532 CI->replaceAllUsesWith(Cast);
1533 CI->eraseFromParent();
1534 CI = dyn_cast<BitCastInst>(Malloc) ?
1535 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
1536 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001537
Evan Cheng86cd4452010-04-14 20:52:55 +00001538 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
1539 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001540 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001541
Victor Hernandez83d63912009-09-18 22:35:49 +00001542 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001543}
Victor Hernandez83d63912009-09-18 22:35:49 +00001544
Chris Lattner9b34a612004-10-09 21:48:45 +00001545// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1546// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001547static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001548 Module::global_iterator &GVI,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001549 TargetData *TD) {
Chris Lattner344b41c2008-12-15 21:20:32 +00001550 // Ignore no-op GEPs and bitcasts.
1551 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Chris Lattner9b34a612004-10-09 21:48:45 +00001552
Chris Lattner708148e2004-10-10 23:14:11 +00001553 // If we are dealing with a pointer global that is initialized to null and
1554 // only has one (non-null) value stored into it, then we can optimize any
1555 // users of the loaded value (often calls and loads) that would trap if the
1556 // value was null.
Duncan Sands1df98592010-02-16 11:11:14 +00001557 if (GV->getInitializer()->getType()->isPointerTy() &&
Chris Lattner9b34a612004-10-09 21:48:45 +00001558 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001559 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1560 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner98a42b22011-05-22 07:15:13 +00001561 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001562
Chris Lattner708148e2004-10-10 23:14:11 +00001563 // Optimize away any trapping uses of the loaded value.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001564 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001565 return true;
Victor Hernandez83d63912009-09-18 22:35:49 +00001566 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001567 Type* MallocType = getMallocAllocatedType(CI);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001568 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
Victor Hernandez9d0b7042009-11-07 00:16:28 +00001569 GVI, TD))
1570 return true;
Chris Lattner708148e2004-10-10 23:14:11 +00001571 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001572 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001573
Chris Lattner9b34a612004-10-09 21:48:45 +00001574 return false;
1575}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001576
Chris Lattner58e44f42008-01-14 01:17:44 +00001577/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1578/// two values ever stored into GV are its initializer and OtherVal. See if we
1579/// can shrink the global into a boolean and select between the two values
1580/// whenever it is used. This exposes the values to other scalar optimizations.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001581static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001582 Type *GVElType = GV->getType()->getElementType();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001583
Chris Lattner58e44f42008-01-14 01:17:44 +00001584 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattner6f6923f2009-03-07 23:32:02 +00001585 // an FP value, pointer or vector, don't do this optimization because a select
1586 // between them is very expensive and unlikely to lead to later
1587 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1588 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001589 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001590 GVElType->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001591 GVElType->isPointerTy() || GVElType->isVectorTy())
Chris Lattner58e44f42008-01-14 01:17:44 +00001592 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001593
Chris Lattner58e44f42008-01-14 01:17:44 +00001594 // Walk the use list of the global seeing if all the uses are load or store.
1595 // If there is anything else, bail out.
Gabor Greifaaaaa022010-07-12 14:13:15 +00001596 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1597 User *U = *I;
1598 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
Chris Lattner58e44f42008-01-14 01:17:44 +00001599 return false;
Gabor Greifaaaaa022010-07-12 14:13:15 +00001600 }
1601
David Greene3215b0e2010-01-05 01:28:05 +00001602 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001603
Chris Lattner96a86b22004-12-12 05:53:50 +00001604 // Create the new global, initializing it to false.
Chris Lattner7b550cc2009-11-06 04:27:31 +00001605 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1606 false,
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001607 GlobalValue::InternalLinkage,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001608 ConstantInt::getFalse(GV->getContext()),
Nick Lewycky0e670df2009-05-03 03:49:08 +00001609 GV->getName()+".b",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001610 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001611 GV->getParent()->getGlobalList().insert(GV, NewGV);
1612
1613 Constant *InitVal = GV->getInitializer();
Chris Lattner7b550cc2009-11-06 04:27:31 +00001614 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +00001615 "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001616
1617 // If initialized to zero and storing one into the global, we can use a cast
1618 // instead of a select to synthesize the desired value.
1619 bool IsOneZero = false;
1620 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001621 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001622
1623 while (!GV->use_empty()) {
Devang Patel771281f2009-03-06 01:39:36 +00001624 Instruction *UI = cast<Instruction>(GV->use_back());
1625 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001626 // Change the store into a boolean store.
1627 bool StoringOther = SI->getOperand(0) == OtherVal;
1628 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001629 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001630 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner7b550cc2009-11-06 04:27:31 +00001631 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1632 StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001633 else {
1634 // Otherwise, we are storing a previously loaded copy. To do this,
1635 // change the copy from copying the original value to just copying the
1636 // bool.
1637 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1638
Gabor Greif9e4f2432010-06-24 14:42:01 +00001639 // If we've already replaced the input, StoredVal will be a cast or
Chris Lattner38c25562004-12-12 19:34:41 +00001640 // select instruction. If not, it will be a load of the original
1641 // global.
1642 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1643 assert(LI->getOperand(0) == GV && "Not a copy!");
1644 // Insert a new load, to preserve the saved value.
1645 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1646 } else {
1647 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1648 "This is not a form that we understand!");
1649 StoreVal = StoredVal->getOperand(0);
1650 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1651 }
1652 }
1653 new StoreInst(StoreVal, NewGV, SI);
Devang Patel771281f2009-03-06 01:39:36 +00001654 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001655 // Change the load into a load of bool then a select.
Devang Patel771281f2009-03-06 01:39:36 +00001656 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001657 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001658 Value *NSI;
1659 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001660 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001661 else
Gabor Greif051a9502008-04-06 20:25:17 +00001662 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Chris Lattner046800a2007-02-11 01:08:35 +00001663 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001664 LI->replaceAllUsesWith(NSI);
Devang Patel771281f2009-03-06 01:39:36 +00001665 }
1666 UI->eraseFromParent();
Chris Lattner96a86b22004-12-12 05:53:50 +00001667 }
1668
1669 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001670 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001671}
1672
1673
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001674/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1675/// it if possible. If we make a change, return true.
Rafael Espindolac4440e32011-01-19 16:32:21 +00001676bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1677 Module::global_iterator &GVI) {
1678 if (!GV->hasLocalLinkage())
1679 return false;
1680
1681 // Do more involved optimizations if the global is internal.
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001682 GV->removeDeadConstantUsers();
1683
1684 if (GV->use_empty()) {
David Greene3215b0e2010-01-05 01:28:05 +00001685 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
Chris Lattner7a7ed022004-10-16 18:09:00 +00001686 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001687 ++NumDeleted;
1688 return true;
1689 }
1690
Rafael Espindolac4440e32011-01-19 16:32:21 +00001691 SmallPtrSet<const PHINode*, 16> PHIUsers;
1692 GlobalStatus GS;
1693
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001694 if (AnalyzeGlobal(GV, GS, PHIUsers))
1695 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001696
Rafael Espindolac4440e32011-01-19 16:32:21 +00001697 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1698 GV->setUnnamedAddr(true);
1699 NumUnnamed++;
1700 }
1701
1702 if (GV->isConstant() || !GV->hasInitializer())
1703 return false;
1704
1705 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1706}
1707
1708/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1709/// it if possible. If we make a change, return true.
1710bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1711 Module::global_iterator &GVI,
1712 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
1713 const GlobalStatus &GS) {
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001714 // If this is a first class global and has only one accessing function
1715 // and this function is main (which we know is not recursive we can make
1716 // this global a local variable) we replace the global with a local alloca
1717 // in this function.
1718 //
1719 // NOTE: It doesn't make sense to promote non single-value types since we
1720 // are just replacing static memory to stack memory.
1721 //
1722 // If the global is in different address space, don't bring it to stack.
1723 if (!GS.HasMultipleAccessingFunctions &&
1724 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1725 GV->getType()->getElementType()->isSingleValueType() &&
1726 GS.AccessingFunction->getName() == "main" &&
1727 GS.AccessingFunction->hasExternalLinkage() &&
1728 GV->getType()->getAddressSpace() == 0) {
1729 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1730 Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1731 ->getEntryBlock().begin());
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001732 Type* ElemTy = GV->getType()->getElementType();
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001733 // FIXME: Pass Global's alignment when globals have alignment
1734 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1735 if (!isa<UndefValue>(GV->getInitializer()))
1736 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001737
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001738 GV->replaceAllUsesWith(Alloca);
1739 GV->eraseFromParent();
1740 ++NumLocalized;
1741 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001742 }
Rafael Espindoladaad56a2011-01-18 04:36:06 +00001743
1744 // If the global is never loaded (but may be stored to), it is dead.
1745 // Delete it now.
1746 if (!GS.isLoaded) {
1747 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1748
1749 // Delete any stores we can find to the global. We may not be able to
1750 // make it completely dead though.
1751 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1752
1753 // If the global is dead now, delete it.
1754 if (GV->use_empty()) {
1755 GV->eraseFromParent();
1756 ++NumDeleted;
1757 Changed = true;
1758 }
1759 return Changed;
1760
1761 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1762 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1763 GV->setConstant(true);
1764
1765 // Clean up any obviously simplifiable users now.
1766 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1767
1768 // If the global is dead now, just nuke it.
1769 if (GV->use_empty()) {
1770 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1771 << "all users and delete global!\n");
1772 GV->eraseFromParent();
1773 ++NumDeleted;
1774 }
1775
1776 ++NumMarked;
1777 return true;
1778 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1779 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1780 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1781 GVI = FirstNewGV; // Don't skip the newly produced globals!
1782 return true;
1783 }
1784 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1785 // If the initial value for the global was an undef value, and if only
1786 // one other value was stored into it, we can just change the
1787 // initializer to be the stored value, then delete all stores to the
1788 // global. This allows us to mark it constant.
1789 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1790 if (isa<UndefValue>(GV->getInitializer())) {
1791 // Change the initial value here.
1792 GV->setInitializer(SOVConstant);
1793
1794 // Clean up any obviously simplifiable users now.
1795 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1796
1797 if (GV->use_empty()) {
1798 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1799 << "simplify all users and delete global!\n");
1800 GV->eraseFromParent();
1801 ++NumDeleted;
1802 } else {
1803 GVI = GV;
1804 }
1805 ++NumSubstitute;
1806 return true;
1807 }
1808
1809 // Try to optimize globals based on the knowledge that only one value
1810 // (besides its initializer) is ever stored to the global.
1811 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1812 getAnalysisIfAvailable<TargetData>()))
1813 return true;
1814
1815 // Otherwise, if the global was not a boolean, we can shrink it to be a
1816 // boolean.
1817 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1818 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1819 ++NumShrunkToBool;
1820 return true;
1821 }
1822 }
1823
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001824 return false;
1825}
1826
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001827/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1828/// function, changing them to FastCC.
1829static void ChangeCalleesToFastCall(Function *F) {
1830 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001831 CallSite User(cast<Instruction>(*UI));
1832 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001833 }
1834}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001835
Devang Patel05988662008-09-25 21:00:45 +00001836static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner58d74912008-03-12 17:45:29 +00001837 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Patel05988662008-09-25 21:00:45 +00001838 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001839 continue;
1840
Duncan Sands548448a2008-02-18 17:32:13 +00001841 // There can be only one.
Devang Patel05988662008-09-25 21:00:45 +00001842 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001843 }
1844
1845 return Attrs;
1846}
1847
1848static void RemoveNestAttribute(Function *F) {
Devang Patel05988662008-09-25 21:00:45 +00001849 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001850 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001851 CallSite User(cast<Instruction>(*UI));
Devang Patel05988662008-09-25 21:00:45 +00001852 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001853 }
1854}
1855
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001856bool GlobalOpt::OptimizeFunctions(Module &M) {
1857 bool Changed = false;
1858 // Optimize functions.
1859 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1860 Function *F = FI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001861 // Functions without names cannot be referenced outside this module.
1862 if (!F->hasName() && !F->isDeclaration())
1863 F->setLinkage(GlobalValue::InternalLinkage);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001864 F->removeDeadConstantUsers();
Eli Friedmanc6633052011-10-20 05:23:42 +00001865 if (F->isDefTriviallyDead()) {
Chris Lattnerec4c7b92009-11-01 19:03:42 +00001866 F->eraseFromParent();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001867 Changed = true;
1868 ++NumFnDeleted;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001869 } else if (F->hasLocalLinkage()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001870 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad757068f2009-06-10 08:41:11 +00001871 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001872 // If this function has C calling conventions, is not a varargs
1873 // function, and is only called directly, promote it to use the Fast
1874 // calling convention.
1875 F->setCallingConv(CallingConv::Fast);
1876 ChangeCalleesToFastCall(F);
1877 ++NumFastCallFns;
1878 Changed = true;
1879 }
1880
Devang Patel05988662008-09-25 21:00:45 +00001881 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad757068f2009-06-10 08:41:11 +00001882 !F->hasAddressTaken()) {
Duncan Sands3d5378f2008-02-16 20:56:04 +00001883 // The function is not used by a trampoline intrinsic, so it is safe
1884 // to remove the 'nest' attribute.
1885 RemoveNestAttribute(F);
1886 ++NumNestRemoved;
1887 Changed = true;
1888 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001889 }
1890 }
1891 return Changed;
1892}
1893
1894bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1895 bool Changed = false;
1896 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1897 GVI != E; ) {
1898 GlobalVariable *GV = GVI++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00001899 // Global variables without names cannot be referenced outside this module.
1900 if (!GV->hasName() && !GV->isDeclaration())
1901 GV->setLinkage(GlobalValue::InternalLinkage);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001902 // Simplify the initializer.
1903 if (GV->hasInitializer())
1904 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Dan Gohmanf860db22010-04-02 03:04:37 +00001905 TargetData *TD = getAnalysisIfAvailable<TargetData>();
Chad Rosieraab8e282011-12-02 01:26:24 +00001906 TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
1907 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
Dan Gohman01b97dd2009-11-23 16:22:21 +00001908 if (New && New != CE)
1909 GV->setInitializer(New);
1910 }
Rafael Espindolac4440e32011-01-19 16:32:21 +00001911
1912 Changed |= ProcessGlobal(GV, GVI);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001913 }
1914 return Changed;
1915}
1916
Nick Lewycky2c44a802011-04-08 07:30:21 +00001917/// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001918/// initializers have an init priority of 65535.
1919GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001920 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1921 if (GV == 0) return 0;
1922
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001923 // Verify that the initializer is simple enough for us to handle. We are
1924 // only allowed to optimize the initializer if it is unique.
1925 if (!GV->hasUniqueInitializer()) return 0;
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001926
1927 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1928 return GV;
1929 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Eli Friedman18a2e502011-04-09 09:11:09 +00001930
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001931 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001932 if (isa<ConstantAggregateZero>(*i))
1933 continue;
1934 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001935 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1936 continue;
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001937
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001938 // Must have a function or null ptr.
1939 if (!isa<Function>(CS->getOperand(1)))
1940 return 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001941
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001942 // Init priority must be standard.
Nick Lewycky2c44a802011-04-08 07:30:21 +00001943 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1944 if (CI->getZExtValue() != 65535)
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001945 return 0;
1946 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001947
Chris Lattnerf51a6cc2010-12-06 21:53:07 +00001948 return GV;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001949}
1950
Chris Lattnerdb973e62005-09-26 02:31:18 +00001951/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1952/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001953static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001954 if (GV->getInitializer()->isNullValue())
1955 return std::vector<Function*>();
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001956 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1957 std::vector<Function*> Result;
1958 Result.reserve(CA->getNumOperands());
Gabor Greif5e463212008-05-29 01:59:18 +00001959 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1960 ConstantStruct *CS = cast<ConstantStruct>(*i);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001961 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1962 }
1963 return Result;
1964}
1965
Chris Lattnerdb973e62005-09-26 02:31:18 +00001966/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1967/// specified array, returning the new global to use.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001968static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Chris Lattner7b550cc2009-11-06 04:27:31 +00001969 const std::vector<Function*> &Ctors) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001970 // If we made a change, reassemble the initializer list.
Chris Lattnerb065b062011-06-20 04:01:31 +00001971 Constant *CSVals[2];
1972 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
1973 CSVals[1] = 0;
1974
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001975 StructType *StructTy =
Chris Lattnerb065b062011-06-20 04:01:31 +00001976 cast <StructType>(
1977 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001978
Chris Lattnerdb973e62005-09-26 02:31:18 +00001979 // Create the new init list.
1980 std::vector<Constant*> CAList;
1981 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00001982 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001983 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00001984 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001985 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
Chris Lattner7b550cc2009-11-06 04:27:31 +00001986 false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001987 PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersona7235ea2009-07-31 20:28:14 +00001988 CSVals[1] = Constant::getNullValue(PFTy);
Chris Lattner7b550cc2009-11-06 04:27:31 +00001989 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
Nick Lewycky5ea5c612011-04-11 22:11:20 +00001990 0x7fffffff);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001991 }
Chris Lattnerb065b062011-06-20 04:01:31 +00001992 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001993 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001994
Chris Lattnerdb973e62005-09-26 02:31:18 +00001995 // Create the array initializer.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001996 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewyckyc332fba2009-09-19 20:30:26 +00001997 CAList.size()), CAList);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00001998
Chris Lattnerdb973e62005-09-26 02:31:18 +00001999 // If we didn't change the number of elements, don't create a new GV.
2000 if (CA->getType() == GCL->getInitializer()->getType()) {
2001 GCL->setInitializer(CA);
2002 return GCL;
2003 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002004
Chris Lattnerdb973e62005-09-26 02:31:18 +00002005 // Create the new global and insert it next to the existing list.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002006 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002007 GCL->getLinkage(), CA, "",
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00002008 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002009 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00002010 NGV->takeName(GCL);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002011
Chris Lattnerdb973e62005-09-26 02:31:18 +00002012 // Nuke the old list, replacing any uses with the new one.
2013 if (!GCL->use_empty()) {
2014 Constant *V = NGV;
2015 if (V->getType() != GCL->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002016 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00002017 GCL->replaceAllUsesWith(V);
2018 }
2019 GCL->eraseFromParent();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002020
Chris Lattnerdb973e62005-09-26 02:31:18 +00002021 if (Ctors.size())
2022 return NGV;
2023 else
2024 return 0;
2025}
Chris Lattner79c11012005-09-26 04:44:35 +00002026
2027
Chris Lattner1945d582010-12-07 04:33:29 +00002028static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues, Value *V) {
Chris Lattner79c11012005-09-26 04:44:35 +00002029 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2030 Constant *R = ComputedValues[V];
2031 assert(R && "Reference to an uncomputed value!");
2032 return R;
2033}
2034
Chris Lattner1945d582010-12-07 04:33:29 +00002035static inline bool
2036isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002037 SmallPtrSet<Constant*, 8> &SimpleConstants,
2038 const TargetData *TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002039
2040
2041/// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2042/// handled by the code generator. We don't want to generate something like:
2043/// void *X = &X/42;
2044/// because the code generator doesn't have a relocation that can handle that.
2045///
2046/// This function should be called if C was not found (but just got inserted)
2047/// in SimpleConstants to avoid having to rescan the same constants all the
2048/// time.
2049static bool isSimpleEnoughValueToCommitHelper(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002050 SmallPtrSet<Constant*, 8> &SimpleConstants,
2051 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002052 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2053 // all supported.
2054 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2055 isa<GlobalValue>(C))
2056 return true;
2057
2058 // Aggregate values are safe if all their elements are.
2059 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2060 isa<ConstantVector>(C)) {
2061 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2062 Constant *Op = cast<Constant>(C->getOperand(i));
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002063 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002064 return false;
2065 }
2066 return true;
2067 }
2068
2069 // We don't know exactly what relocations are allowed in constant expressions,
2070 // so we allow &global+constantoffset, which is safe and uniformly supported
2071 // across targets.
2072 ConstantExpr *CE = cast<ConstantExpr>(C);
2073 switch (CE->getOpcode()) {
2074 case Instruction::BitCast:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002075 // Bitcast is fine if the casted value is fine.
2076 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2077
Chris Lattner1945d582010-12-07 04:33:29 +00002078 case Instruction::IntToPtr:
2079 case Instruction::PtrToInt:
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002080 // int <=> ptr is fine if the int type is the same size as the
2081 // pointer type.
2082 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2083 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2084 return false;
2085 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002086
2087 // GEP is fine if it is simple + constant offset.
2088 case Instruction::GetElementPtr:
2089 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2090 if (!isa<ConstantInt>(CE->getOperand(i)))
2091 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002092 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002093
2094 case Instruction::Add:
2095 // We allow simple+cst.
2096 if (!isa<ConstantInt>(CE->getOperand(1)))
2097 return false;
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002098 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002099 }
2100 return false;
2101}
2102
2103static inline bool
2104isSimpleEnoughValueToCommit(Constant *C,
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002105 SmallPtrSet<Constant*, 8> &SimpleConstants,
2106 const TargetData *TD) {
Chris Lattner1945d582010-12-07 04:33:29 +00002107 // If we already checked this constant, we win.
2108 if (!SimpleConstants.insert(C)) return true;
2109 // Check the constant.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002110 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
Chris Lattner1945d582010-12-07 04:33:29 +00002111}
2112
2113
Chris Lattner79c11012005-09-26 04:44:35 +00002114/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
Owen Andersoncff6b372011-01-14 22:19:20 +00002115/// enough for us to understand. In particular, if it is a cast to anything
2116/// other than from one pointer type to another pointer type, we punt.
2117/// We basically just support direct accesses to globals and GEP's of
Chris Lattner79c11012005-09-26 04:44:35 +00002118/// globals. This should be kept up to date with CommitValueTo.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002119static bool isSimpleEnoughPointerToCommit(Constant *C) {
Dan Gohmance5de5b2009-09-07 22:42:05 +00002120 // Conservatively, avoid aggregate types. This is because we don't
2121 // want to worry about them partially overlapping other stores.
2122 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2123 return false;
2124
Dan Gohmanfd54a892009-09-07 22:31:26 +00002125 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002126 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002127 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002128 return GV->hasUniqueInitializer();
Dan Gohmanfd54a892009-09-07 22:31:26 +00002129
Owen Andersone95a32c2011-01-14 22:31:13 +00002130 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002131 // Handle a constantexpr gep.
2132 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmanc62482d2009-09-07 22:40:13 +00002133 isa<GlobalVariable>(CE->getOperand(0)) &&
2134 cast<GEPOperator>(CE)->isInBounds()) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002135 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002136 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
Dan Gohmanfd54a892009-09-07 22:31:26 +00002137 // external globals.
Mikhail Glushenkov99fca5d2010-10-19 16:47:23 +00002138 if (!GV->hasUniqueInitializer())
Dan Gohmanfd54a892009-09-07 22:31:26 +00002139 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002140
Dan Gohman80bdc962009-09-07 22:44:55 +00002141 // The first index must be zero.
Oscar Fuentesee56c422010-08-02 06:00:15 +00002142 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
Dan Gohman80bdc962009-09-07 22:44:55 +00002143 if (!CI || !CI->isZero()) return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002144
2145 // The remaining indices must be compile-time known integers within the
Dan Gohmane6992f72009-09-10 23:37:55 +00002146 // notional bounds of the corresponding static array types.
2147 if (!CE->isGEPWithNoNotionalOverIndexing())
2148 return false;
Dan Gohman80bdc962009-09-07 22:44:55 +00002149
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002150 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Owen Andersoncff6b372011-01-14 22:19:20 +00002151
2152 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2153 // and we know how to evaluate it by moving the bitcast from the pointer
2154 // operand to the value operand.
2155 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002156 isa<GlobalVariable>(CE->getOperand(0))) {
Owen Andersoncff6b372011-01-14 22:19:20 +00002157 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2158 // external globals.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002159 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
Chris Lattner798b4d52005-09-26 06:52:44 +00002160 }
Owen Andersone95a32c2011-01-14 22:31:13 +00002161 }
2162
Chris Lattner79c11012005-09-26 04:44:35 +00002163 return false;
2164}
2165
Chris Lattner798b4d52005-09-26 06:52:44 +00002166/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2167/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2168/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2169static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002170 ConstantExpr *Addr, unsigned OpNo) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002171 // Base case of the recursion.
2172 if (OpNo == Addr->getNumOperands()) {
2173 assert(Val->getType() == Init->getType() && "Type mismatch!");
2174 return Val;
2175 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002176
Chris Lattnera0e9a242010-01-07 01:16:21 +00002177 std::vector<Constant*> Elts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002178 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002179
2180 // Break up the constant into its elements.
2181 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif5e463212008-05-29 01:59:18 +00002182 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2183 Elts.push_back(cast<Constant>(*i));
Chris Lattner798b4d52005-09-26 06:52:44 +00002184 } else if (isa<ConstantAggregateZero>(Init)) {
2185 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00002186 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002187 } else if (isa<UndefValue>(Init)) {
2188 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002189 Elts.push_back(UndefValue::get(STy->getElementType(i)));
Chris Lattner798b4d52005-09-26 06:52:44 +00002190 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002191 llvm_unreachable("This code is out of sync with "
Chris Lattner798b4d52005-09-26 06:52:44 +00002192 " ConstantFoldLoadThroughGEPConstantExpr");
2193 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002194
Chris Lattner798b4d52005-09-26 06:52:44 +00002195 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00002196 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2197 unsigned Idx = CU->getZExtValue();
2198 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner7b550cc2009-11-06 04:27:31 +00002199 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002200
Chris Lattner798b4d52005-09-26 06:52:44 +00002201 // Return the modified struct.
Chris Lattnerb065b062011-06-20 04:01:31 +00002202 return ConstantStruct::get(STy, Elts);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002203 }
Chris Lattnerb065b062011-06-20 04:01:31 +00002204
2205 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002206 SequentialType *InitTy = cast<SequentialType>(Init->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +00002207
2208 uint64_t NumElts;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002209 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
Chris Lattnerb065b062011-06-20 04:01:31 +00002210 NumElts = ATy->getNumElements();
2211 else
2212 NumElts = cast<VectorType>(InitTy)->getNumElements();
2213
2214 // Break up the array into elements.
2215 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2216 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2217 Elts.push_back(cast<Constant>(*i));
2218 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2219 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2220 Elts.push_back(cast<Constant>(*i));
2221 } else if (isa<ConstantAggregateZero>(Init)) {
2222 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
2223 } else {
2224 assert(isa<UndefValue>(Init) && "This code is out of sync with "
2225 " ConstantFoldLoadThroughGEPConstantExpr");
2226 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
2227 }
2228
2229 assert(CI->getZExtValue() < NumElts);
2230 Elts[CI->getZExtValue()] =
2231 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2232
2233 if (Init->getType()->isArrayTy())
2234 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2235 return ConstantVector::get(Elts);
Chris Lattner798b4d52005-09-26 06:52:44 +00002236}
2237
Chris Lattner79c11012005-09-26 04:44:35 +00002238/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2239/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Chris Lattner7b550cc2009-11-06 04:27:31 +00002240static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00002241 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2242 assert(GV->hasInitializer());
2243 GV->setInitializer(Val);
2244 return;
2245 }
Chris Lattnera0e9a242010-01-07 01:16:21 +00002246
Chris Lattner798b4d52005-09-26 06:52:44 +00002247 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2248 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattnera0e9a242010-01-07 01:16:21 +00002249 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
Chris Lattner79c11012005-09-26 04:44:35 +00002250}
2251
Chris Lattner562a0552005-09-26 05:16:34 +00002252/// ComputeLoadResult - Return the value that would be computed by a load from
2253/// P after the stores reflected by 'memory' have been performed. If we can't
2254/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002255static Constant *ComputeLoadResult(Constant *P,
Chris Lattner7b550cc2009-11-06 04:27:31 +00002256 const DenseMap<Constant*, Constant*> &Memory) {
Chris Lattner04de1cf2005-09-26 05:15:37 +00002257 // If this memory location has been recently stored, use the stored value: it
2258 // is the most up-to-date.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002259 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Chris Lattner04de1cf2005-09-26 05:15:37 +00002260 if (I != Memory.end()) return I->second;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002261
Chris Lattner04de1cf2005-09-26 05:15:37 +00002262 // Access it.
2263 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman82555732009-08-19 18:20:44 +00002264 if (GV->hasDefinitiveInitializer())
Chris Lattner04de1cf2005-09-26 05:15:37 +00002265 return GV->getInitializer();
2266 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00002267 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002268
Chris Lattner798b4d52005-09-26 06:52:44 +00002269 // Handle a constantexpr getelementptr.
2270 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2271 if (CE->getOpcode() == Instruction::GetElementPtr &&
2272 isa<GlobalVariable>(CE->getOperand(0))) {
2273 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00002274 if (GV->hasDefinitiveInitializer())
Dan Gohmanc6f69e92009-10-05 16:36:26 +00002275 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Chris Lattner798b4d52005-09-26 06:52:44 +00002276 }
2277
2278 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002279}
2280
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002281/// EvaluateFunction - Evaluate a call to function F, returning true if
2282/// successful, false if we can't evaluate it. ActualArgs contains the formal
2283/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002284static bool EvaluateFunction(Function *F, Constant *&RetVal,
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002285 const SmallVectorImpl<Constant*> &ActualArgs,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002286 std::vector<Function*> &CallStack,
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002287 DenseMap<Constant*, Constant*> &MutatedMemory,
Chris Lattner1945d582010-12-07 04:33:29 +00002288 std::vector<GlobalVariable*> &AllocaTmps,
2289 SmallPtrSet<Constant*, 8> &SimpleConstants,
Chad Rosier00737bd2011-12-01 21:29:16 +00002290 const TargetData *TD,
2291 const TargetLibraryInfo *TLI) {
Chris Lattnercd271422005-09-27 04:45:34 +00002292 // Check to see if this function is already executing (recursion). If so,
2293 // bail out. TODO: we might want to accept limited recursion.
2294 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2295 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002296
Chris Lattnercd271422005-09-27 04:45:34 +00002297 CallStack.push_back(F);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002298
Chris Lattner79c11012005-09-26 04:44:35 +00002299 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002300 DenseMap<Value*, Constant*> Values;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002301
Chris Lattnercd271422005-09-27 04:45:34 +00002302 // Initialize arguments to the incoming values specified.
2303 unsigned ArgNo = 0;
2304 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2305 ++AI, ++ArgNo)
2306 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002307
Chris Lattnercdf98be2005-09-26 04:57:38 +00002308 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2309 /// we can only evaluate any one basic block at most once. This set keeps
2310 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002311 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002312
Chris Lattner79c11012005-09-26 04:44:35 +00002313 // CurInst - The current instruction we're evaluating.
2314 BasicBlock::iterator CurInst = F->begin()->begin();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002315
Chris Lattner79c11012005-09-26 04:44:35 +00002316 // This is the main evaluation loop.
2317 while (1) {
2318 Constant *InstResult = 0;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002319
Chris Lattner79c11012005-09-26 04:44:35 +00002320 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002321 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00002322 Constant *Ptr = getVal(Values, SI->getOperand(1));
Chris Lattner7b550cc2009-11-06 04:27:31 +00002323 if (!isSimpleEnoughPointerToCommit(Ptr))
Chris Lattner79c11012005-09-26 04:44:35 +00002324 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00002325 return false;
Chris Lattner1945d582010-12-07 04:33:29 +00002326
Chris Lattner79c11012005-09-26 04:44:35 +00002327 Constant *Val = getVal(Values, SI->getOperand(0));
Chris Lattner1945d582010-12-07 04:33:29 +00002328
2329 // If this might be too difficult for the backend to handle (e.g. the addr
2330 // of one global variable divided by another) then we can't commit it.
Eli Friedmanfb54ad12012-01-05 23:03:32 +00002331 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD))
Chris Lattner1945d582010-12-07 04:33:29 +00002332 return false;
Owen Andersoncff6b372011-01-14 22:19:20 +00002333
2334 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2335 if (CE->getOpcode() == Instruction::BitCast) {
2336 // If we're evaluating a store through a bitcast, then we need
2337 // to pull the bitcast off the pointer type and push it onto the
2338 // stored value.
Chris Lattnerd5f656f2011-01-16 02:05:10 +00002339 Ptr = CE->getOperand(0);
Owen Andersoncff6b372011-01-14 22:19:20 +00002340
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002341 Type *NewTy=cast<PointerType>(Ptr->getType())->getElementType();
Owen Andersoncff6b372011-01-14 22:19:20 +00002342
Owen Anderson66f708f2011-01-16 04:33:33 +00002343 // In order to push the bitcast onto the stored value, a bitcast
2344 // from NewTy to Val's type must be legal. If it's not, we can try
2345 // introspecting NewTy to find a legal conversion.
2346 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2347 // If NewTy is a struct, we can convert the pointer to the struct
2348 // into a pointer to its first member.
2349 // FIXME: This could be extended to support arrays as well.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002350 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
Owen Anderson66f708f2011-01-16 04:33:33 +00002351 NewTy = STy->getTypeAtIndex(0U);
2352
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002353 IntegerType *IdxTy =IntegerType::get(NewTy->getContext(), 32);
Owen Anderson66f708f2011-01-16 04:33:33 +00002354 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2355 Constant * const IdxList[] = {IdxZero, IdxZero};
2356
Jay Foadb4263a62011-07-22 08:52:50 +00002357 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
Owen Andersoncff6b372011-01-14 22:19:20 +00002358
Owen Anderson66f708f2011-01-16 04:33:33 +00002359 // If we can't improve the situation by introspecting NewTy,
2360 // we have to give up.
2361 } else {
2362 return 0;
2363 }
Owen Andersoncff6b372011-01-14 22:19:20 +00002364 }
2365
Owen Anderson66f708f2011-01-16 04:33:33 +00002366 // If we found compatible types, go ahead and push the bitcast
2367 // onto the stored value.
Owen Andersoncff6b372011-01-14 22:19:20 +00002368 Val = ConstantExpr::getBitCast(Val, NewTy);
2369 }
2370
Chris Lattner79c11012005-09-26 04:44:35 +00002371 MutatedMemory[Ptr] = Val;
2372 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002373 InstResult = ConstantExpr::get(BO->getOpcode(),
Chris Lattner79c11012005-09-26 04:44:35 +00002374 getVal(Values, BO->getOperand(0)),
2375 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002376 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002377 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002378 getVal(Values, CI->getOperand(0)),
2379 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00002380 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002381 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Chris Lattner9a989f02006-11-30 17:26:08 +00002382 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00002383 CI->getType());
2384 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Gabor Greif9e4f2432010-06-24 14:42:01 +00002385 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Eric Christopher551754c2010-04-16 23:37:20 +00002386 getVal(Values, SI->getOperand(1)),
2387 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00002388 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2389 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00002390 SmallVector<Constant*, 8> GEPOps;
Gabor Greif5e463212008-05-29 01:59:18 +00002391 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2392 i != e; ++i)
2393 GEPOps.push_back(getVal(Values, *i));
Jay Foad4b5e2072011-07-21 15:15:37 +00002394 InstResult =
2395 ConstantExpr::getGetElementPtr(P, GEPOps,
2396 cast<GEPOperator>(GEP)->isInBounds());
Chris Lattner04de1cf2005-09-26 05:15:37 +00002397 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Eli Friedman33cb4452011-08-16 00:20:11 +00002398 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00002399 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Chris Lattner7b550cc2009-11-06 04:27:31 +00002400 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00002401 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00002402 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002403 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002404 Type *Ty = AI->getType()->getElementType();
Chris Lattner7b550cc2009-11-06 04:27:31 +00002405 AllocaTmps.push_back(new GlobalVariable(Ty, false,
Chris Lattnera22fdb02005-09-26 17:07:09 +00002406 GlobalValue::InternalLinkage,
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002407 UndefValue::get(Ty),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002408 AI->getName()));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002409 InstResult = AllocaTmps.back();
Chris Lattnercd271422005-09-27 04:45:34 +00002410 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel412a4462009-03-09 23:04:12 +00002411
2412 // Debug info can safely be ignored here.
2413 if (isa<DbgInfoIntrinsic>(CI)) {
2414 ++CurInst;
2415 continue;
2416 }
2417
Chris Lattner7cd580f2006-07-07 21:37:01 +00002418 // Cannot handle inline asm.
Gabor Greifa9b23132010-04-20 13:13:04 +00002419 if (isa<InlineAsm>(CI->getCalledValue())) return false;
Chris Lattner7cd580f2006-07-07 21:37:01 +00002420
Nick Lewycky1f237b02011-05-29 18:41:56 +00002421 if (MemSetInst *MSI = dyn_cast<MemSetInst>(CI)) {
2422 if (MSI->isVolatile()) return false;
2423 Constant *Ptr = getVal(Values, MSI->getDest());
2424 Constant *Val = getVal(Values, MSI->getValue());
2425 Constant *DestVal = ComputeLoadResult(getVal(Values, Ptr),
2426 MutatedMemory);
Nick Lewyckybcb85082011-05-29 19:33:36 +00002427 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
Nick Lewycky1f237b02011-05-29 18:41:56 +00002428 // This memset is a no-op.
2429 ++CurInst;
2430 continue;
2431 }
2432 return false;
2433 }
2434
Chris Lattnercd271422005-09-27 04:45:34 +00002435 // Resolve function pointers.
Gabor Greifa3997812010-07-22 10:37:47 +00002436 Function *Callee = dyn_cast<Function>(getVal(Values,
2437 CI->getCalledValue()));
Chris Lattnercd271422005-09-27 04:45:34 +00002438 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002439
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002440 SmallVector<Constant*, 8> Formals;
Gabor Greif9e4f2432010-06-24 14:42:01 +00002441 CallSite CS(CI);
2442 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end();
Gabor Greif5e463212008-05-29 01:59:18 +00002443 i != e; ++i)
2444 Formals.push_back(getVal(Values, *i));
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002445
Reid Spencer5cbf9852007-01-30 20:08:39 +00002446 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002447 // If this is a function we can constant fold, do it.
Chad Rosier00737bd2011-12-01 21:29:16 +00002448 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002449 InstResult = C;
2450 } else {
2451 return false;
2452 }
2453 } else {
2454 if (Callee->getFunctionType()->isVarArg())
2455 return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002456
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002457 Constant *RetVal;
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002458 // Execute the call, if successful, use the return value.
2459 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
Chad Rosier00737bd2011-12-01 21:29:16 +00002460 MutatedMemory, AllocaTmps, SimpleConstants, TD,
2461 TLI))
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002462 return false;
2463 InstResult = RetVal;
2464 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002465 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002466 BasicBlock *NewBB = 0;
2467 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2468 if (BI->isUnconditional()) {
2469 NewBB = BI->getSuccessor(0);
2470 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002471 ConstantInt *Cond =
2472 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002473 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002474
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002475 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002476 }
2477 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2478 ConstantInt *Val =
2479 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002480 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002481 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
Chris Lattnerb3d5a652009-10-29 05:51:50 +00002482 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2483 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2484 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2485 NewBB = BA->getBasicBlock();
Chris Lattnercdfc9402009-11-01 01:27:45 +00002486 else
2487 return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002488 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002489 if (RI->getNumOperands())
2490 RetVal = getVal(Values, RI->getOperand(0));
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002491
Chris Lattnercd271422005-09-27 04:45:34 +00002492 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002493 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002494 } else {
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002495 // invoke, unwind, resume, unreachable.
Chris Lattnercd271422005-09-27 04:45:34 +00002496 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002497 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002498
Chris Lattnercdf98be2005-09-26 04:57:38 +00002499 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002500 // executed the new block before. If so, we have a looping function,
2501 // which we cannot evaluate in reasonable time.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002502 if (!ExecutedBlocks.insert(NewBB))
Chris Lattnercd271422005-09-27 04:45:34 +00002503 return false; // looped!
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002504
Chris Lattnercdf98be2005-09-26 04:57:38 +00002505 // Okay, we have never been in this block before. Check to see if there
2506 // are any PHI nodes. If so, evaluate them with information about where
2507 // we came from.
2508 BasicBlock *OldBB = CurInst->getParent();
2509 CurInst = NewBB->begin();
2510 PHINode *PN;
2511 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2512 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2513
2514 // Do NOT increment CurInst. We know that the terminator had no value.
2515 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002516 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002517 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002518 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002519 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002520
Chris Lattner1945d582010-12-07 04:33:29 +00002521 if (!CurInst->use_empty()) {
2522 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
Chad Rosieraab8e282011-12-02 01:26:24 +00002523 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
Chris Lattner1945d582010-12-07 04:33:29 +00002524
Chris Lattner79c11012005-09-26 04:44:35 +00002525 Values[CurInst] = InstResult;
Chris Lattner1945d582010-12-07 04:33:29 +00002526 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002527
Chris Lattner79c11012005-09-26 04:44:35 +00002528 // Advance program counter.
2529 ++CurInst;
2530 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002531}
2532
2533/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2534/// we can. Return true if we can, false otherwise.
Chad Rosier00737bd2011-12-01 21:29:16 +00002535static bool EvaluateStaticConstructor(Function *F, const TargetData *TD,
2536 const TargetLibraryInfo *TLI) {
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002537 /// MutatedMemory - For each store we execute, we update this map. Loads
2538 /// check this to get the most up-to-date value. If evaluation is successful,
2539 /// this state is committed to the process.
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002540 DenseMap<Constant*, Constant*> MutatedMemory;
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002541
2542 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2543 /// to represent its body. This vector is needed so we can delete the
2544 /// temporary globals when we are done.
2545 std::vector<GlobalVariable*> AllocaTmps;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002546
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002547 /// CallStack - This is used to detect recursion. In pathological situations
2548 /// we could hit exponential behavior, but at least there is nothing
2549 /// unbounded.
2550 std::vector<Function*> CallStack;
2551
Chris Lattner1945d582010-12-07 04:33:29 +00002552 /// SimpleConstants - These are constants we have checked and know to be
2553 /// simple enough to live in a static initializer of a global.
2554 SmallPtrSet<Constant*, 8> SimpleConstants;
2555
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002556 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002557 Constant *RetValDummy;
Duncan Sandsfa6a1cf2009-08-17 14:33:27 +00002558 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2559 SmallVector<Constant*, 0>(), CallStack,
Chris Lattner1945d582010-12-07 04:33:29 +00002560 MutatedMemory, AllocaTmps,
Chad Rosier00737bd2011-12-01 21:29:16 +00002561 SimpleConstants, TD, TLI);
Chris Lattner1945d582010-12-07 04:33:29 +00002562
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002563 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002564 // We succeeded at evaluation: commit the result.
David Greene3215b0e2010-01-05 01:28:05 +00002565 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00002566 << F->getName() << "' to " << MutatedMemory.size()
2567 << " stores.\n");
Chris Lattner5a6bb6a2008-12-16 07:34:30 +00002568 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Chris Lattnera22fdb02005-09-26 17:07:09 +00002569 E = MutatedMemory.end(); I != E; ++I)
Chris Lattner7b550cc2009-11-06 04:27:31 +00002570 CommitValueTo(I->second, I->first);
Chris Lattnera22fdb02005-09-26 17:07:09 +00002571 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002572
Chris Lattnera22fdb02005-09-26 17:07:09 +00002573 // At this point, we are done interpreting. If we created any 'alloca'
2574 // temporaries, release them now.
2575 while (!AllocaTmps.empty()) {
2576 GlobalVariable *Tmp = AllocaTmps.back();
2577 AllocaTmps.pop_back();
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002578
Chris Lattnera22fdb02005-09-26 17:07:09 +00002579 // If there are still users of the alloca, the program is doing something
2580 // silly, e.g. storing the address of the alloca somewhere and using it
2581 // later. Since this is undefined, we'll just make it be null.
2582 if (!Tmp->use_empty())
Owen Andersona7235ea2009-07-31 20:28:14 +00002583 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Chris Lattnera22fdb02005-09-26 17:07:09 +00002584 delete Tmp;
2585 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002586
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002587 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002588}
2589
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002590/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2591/// Return true if anything changed.
2592bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2593 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2594 bool MadeChange = false;
2595 if (Ctors.empty()) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002596
Chris Lattner1945d582010-12-07 04:33:29 +00002597 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Chad Rosier00737bd2011-12-01 21:29:16 +00002598 const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
2599
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002600 // Loop over global ctors, optimizing them when we can.
2601 for (unsigned i = 0; i != Ctors.size(); ++i) {
2602 Function *F = Ctors[i];
2603 // Found a null terminator in the middle of the list, prune off the rest of
2604 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002605 if (F == 0) {
2606 if (i != Ctors.size()-1) {
2607 Ctors.resize(i+1);
2608 MadeChange = true;
2609 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002610 break;
2611 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002612
Chris Lattner79c11012005-09-26 04:44:35 +00002613 // We cannot simplify external ctor functions.
2614 if (F->empty()) continue;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002615
Chris Lattner79c11012005-09-26 04:44:35 +00002616 // If we can evaluate the ctor at compile time, do.
Chad Rosier00737bd2011-12-01 21:29:16 +00002617 if (EvaluateStaticConstructor(F, TD, TLI)) {
Chris Lattner79c11012005-09-26 04:44:35 +00002618 Ctors.erase(Ctors.begin()+i);
2619 MadeChange = true;
2620 --i;
2621 ++NumCtorsEvaluated;
2622 continue;
2623 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002624 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002625
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002626 if (!MadeChange) return false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002627
Chris Lattner7b550cc2009-11-06 04:27:31 +00002628 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002629 return true;
2630}
2631
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002632bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002633 bool Changed = false;
2634
Duncan Sands177d84e2009-01-07 20:01:06 +00002635 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sands4782b302009-02-15 09:56:08 +00002636 I != E;) {
2637 Module::alias_iterator J = I++;
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002638 // Aliases without names cannot be referenced outside this module.
2639 if (!J->hasName() && !J->isDeclaration())
2640 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sands4782b302009-02-15 09:56:08 +00002641 // If the aliasee may change at link time, nothing can be done - bail out.
2642 if (J->mayBeOverridden())
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002643 continue;
2644
Duncan Sands4782b302009-02-15 09:56:08 +00002645 Constant *Aliasee = J->getAliasee();
2646 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands95c5d0f2009-02-18 17:55:38 +00002647 Target->removeDeadConstantUsers();
Duncan Sands4782b302009-02-15 09:56:08 +00002648 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2649
2650 // Make all users of the alias use the aliasee instead.
2651 if (!J->use_empty()) {
2652 J->replaceAllUsesWith(Aliasee);
2653 ++NumAliasesResolved;
2654 Changed = true;
2655 }
2656
Duncan Sands7a154cf2009-12-08 10:10:20 +00002657 // If the alias is externally visible, we may still be able to simplify it.
2658 if (!J->hasLocalLinkage()) {
2659 // If the aliasee has internal linkage, give it the name and linkage
2660 // of the alias, and delete the alias. This turns:
2661 // define internal ... @f(...)
2662 // @a = alias ... @f
2663 // into:
2664 // define ... @a(...)
2665 if (!Target->hasLocalLinkage())
2666 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002667
Duncan Sands7a154cf2009-12-08 10:10:20 +00002668 // Do not perform the transform if multiple aliases potentially target the
Gabor Greif27236912010-04-07 18:59:26 +00002669 // aliasee. This check also ensures that it is safe to replace the section
Duncan Sands7a154cf2009-12-08 10:10:20 +00002670 // and other attributes of the aliasee with those of the alias.
2671 if (!hasOneUse)
2672 continue;
Duncan Sands4782b302009-02-15 09:56:08 +00002673
Duncan Sands7a154cf2009-12-08 10:10:20 +00002674 // Give the aliasee the name, linkage and other attributes of the alias.
2675 Target->takeName(J);
2676 Target->setLinkage(J->getLinkage());
2677 Target->GlobalValue::copyAttributesFrom(J);
2678 }
Duncan Sands4782b302009-02-15 09:56:08 +00002679
2680 // Delete the alias.
2681 M.getAliasList().erase(J);
2682 ++NumAliasesRemoved;
2683 Changed = true;
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002684 }
2685
2686 return Changed;
2687}
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002688
Anders Carlssona201c4c2011-03-20 17:59:11 +00002689static Function *FindCXAAtExit(Module &M) {
2690 Function *Fn = M.getFunction("__cxa_atexit");
2691
2692 if (!Fn)
2693 return 0;
2694
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002695 FunctionType *FTy = Fn->getFunctionType();
Anders Carlssona201c4c2011-03-20 17:59:11 +00002696
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002697 // Checking that the function has the right return type, the right number of
2698 // parameters and that they all have pointer types should be enough.
2699 if (!FTy->getReturnType()->isIntegerTy() ||
2700 FTy->getNumParams() != 3 ||
Anders Carlssona201c4c2011-03-20 17:59:11 +00002701 !FTy->getParamType(0)->isPointerTy() ||
2702 !FTy->getParamType(1)->isPointerTy() ||
2703 !FTy->getParamType(2)->isPointerTy())
2704 return 0;
2705
2706 return Fn;
2707}
2708
2709/// cxxDtorIsEmpty - Returns whether the given function is an empty C++
2710/// destructor and can therefore be eliminated.
2711/// Note that we assume that other optimization passes have already simplified
2712/// the code so we only look for a function with a single basic block, where
2713/// the only allowed instructions are 'ret' or 'call' to empty C++ dtor.
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002714static bool cxxDtorIsEmpty(const Function &Fn,
2715 SmallPtrSet<const Function *, 8> &CalledFunctions) {
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002716 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002717 // nounwind, but that doesn't seem worth doing.
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002718 if (Fn.isDeclaration())
2719 return false;
Anders Carlssona201c4c2011-03-20 17:59:11 +00002720
2721 if (++Fn.begin() != Fn.end())
2722 return false;
2723
2724 const BasicBlock &EntryBlock = Fn.getEntryBlock();
2725 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
2726 I != E; ++I) {
2727 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
Anders Carlssonb12caf32011-03-21 14:54:40 +00002728 // Ignore debug intrinsics.
2729 if (isa<DbgInfoIntrinsic>(CI))
2730 continue;
2731
Anders Carlssona201c4c2011-03-20 17:59:11 +00002732 const Function *CalledFn = CI->getCalledFunction();
2733
2734 if (!CalledFn)
2735 return false;
2736
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002737 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
2738
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002739 // Don't treat recursive functions as empty.
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002740 if (!NewCalledFunctions.insert(CalledFn))
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002741 return false;
2742
Anders Carlsson807bc2a2011-03-22 03:21:01 +00002743 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002744 return false;
2745 } else if (isa<ReturnInst>(*I))
2746 return true;
2747 else
2748 return false;
2749 }
2750
2751 return false;
2752}
2753
2754bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
2755 /// Itanium C++ ABI p3.3.5:
2756 ///
2757 /// After constructing a global (or local static) object, that will require
2758 /// destruction on exit, a termination function is registered as follows:
2759 ///
2760 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
2761 ///
2762 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
2763 /// call f(p) when DSO d is unloaded, before all such termination calls
2764 /// registered before this one. It returns zero if registration is
Nick Lewycky35ee1c92011-03-21 02:26:01 +00002765 /// successful, nonzero on failure.
Anders Carlssona201c4c2011-03-20 17:59:11 +00002766
2767 // This pass will look for calls to __cxa_atexit where the function is trivial
2768 // and remove them.
2769 bool Changed = false;
2770
2771 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
2772 E = CXAAtExitFn->use_end(); I != E;) {
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002773 // We're only interested in calls. Theoretically, we could handle invoke
2774 // instructions as well, but neither llvm-gcc nor clang generate invokes
2775 // to __cxa_atexit.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002776 CallInst *CI = dyn_cast<CallInst>(*I++);
2777 if (!CI)
Anders Carlsson4f735ca2011-03-20 20:21:33 +00002778 continue;
2779
Anders Carlssona201c4c2011-03-20 17:59:11 +00002780 Function *DtorFn =
Anders Carlssonb12caf32011-03-21 14:54:40 +00002781 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
Anders Carlssona201c4c2011-03-20 17:59:11 +00002782 if (!DtorFn)
2783 continue;
2784
Anders Carlsson372ec6a2011-03-20 20:16:43 +00002785 SmallPtrSet<const Function *, 8> CalledFunctions;
2786 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
Anders Carlssona201c4c2011-03-20 17:59:11 +00002787 continue;
2788
2789 // Just remove the call.
Anders Carlssonb12caf32011-03-21 14:54:40 +00002790 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
2791 CI->eraseFromParent();
Anders Carlsson1f7c7ba2011-03-20 19:51:13 +00002792
Anders Carlssona201c4c2011-03-20 17:59:11 +00002793 ++NumCXXDtorsRemoved;
2794
2795 Changed |= true;
2796 }
2797
2798 return Changed;
2799}
2800
Chris Lattner7a90b682004-10-07 04:16:33 +00002801bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002802 bool Changed = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002803
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002804 // Try to find the llvm.globalctors list.
2805 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002806
Anders Carlssona201c4c2011-03-20 17:59:11 +00002807 Function *CXAAtExitFn = FindCXAAtExit(M);
2808
Chris Lattner7a90b682004-10-07 04:16:33 +00002809 bool LocalChange = true;
2810 while (LocalChange) {
2811 LocalChange = false;
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002812
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002813 // Delete functions that are trivially dead, ccc -> fastcc
2814 LocalChange |= OptimizeFunctions(M);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002815
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002816 // Optimize global_ctors list.
2817 if (GlobalCtors)
2818 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002819
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002820 // Optimize non-address-taken globals.
2821 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002822
2823 // Resolve aliases, when possible.
Duncan Sandsfc5940d2009-03-06 10:21:56 +00002824 LocalChange |= OptimizeGlobalAliases(M);
Anders Carlssona201c4c2011-03-20 17:59:11 +00002825
2826 // Try to remove trivial global destructors.
2827 if (CXAAtExitFn)
2828 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
2829
Anton Korobeynikove4c6b612008-09-09 19:04:59 +00002830 Changed |= LocalChange;
Chris Lattner7a90b682004-10-07 04:16:33 +00002831 }
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002832
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002833 // TODO: Move all global ctors functions to the end of the module for code
2834 // layout.
Mikhail Glushenkov9d28fdd2010-10-18 21:16:00 +00002835
Chris Lattner079236d2004-02-25 21:34:36 +00002836 return Changed;
2837}