GlobalOpt.cpp revision ab05d8fcf61f7b926cf3e08f111794c69ca60690
1//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This pass transforms simple global variables that never have their address 11// taken. If obviously true, it marks read/write globals as constant, deletes 12// variables only stored to, etc. 13// 14//===----------------------------------------------------------------------===// 15 16#define DEBUG_TYPE "globalopt" 17#include "llvm/Transforms/IPO.h" 18#include "llvm/CallingConv.h" 19#include "llvm/Constants.h" 20#include "llvm/DerivedTypes.h" 21#include "llvm/Instructions.h" 22#include "llvm/IntrinsicInst.h" 23#include "llvm/Module.h" 24#include "llvm/Pass.h" 25#include "llvm/Analysis/ConstantFolding.h" 26#include "llvm/Analysis/MemoryBuiltins.h" 27#include "llvm/Target/TargetData.h" 28#include "llvm/Support/CallSite.h" 29#include "llvm/Support/Debug.h" 30#include "llvm/Support/ErrorHandling.h" 31#include "llvm/Support/GetElementPtrTypeIterator.h" 32#include "llvm/Support/MathExtras.h" 33#include "llvm/Support/raw_ostream.h" 34#include "llvm/ADT/DenseMap.h" 35#include "llvm/ADT/SmallPtrSet.h" 36#include "llvm/ADT/SmallVector.h" 37#include "llvm/ADT/Statistic.h" 38#include "llvm/ADT/STLExtras.h" 39#include <algorithm> 40using namespace llvm; 41 42STATISTIC(NumMarked , "Number of globals marked constant"); 43STATISTIC(NumSRA , "Number of aggregate globals broken into scalars"); 44STATISTIC(NumHeapSRA , "Number of heap objects SRA'd"); 45STATISTIC(NumSubstitute,"Number of globals with initializers stored into them"); 46STATISTIC(NumDeleted , "Number of globals deleted"); 47STATISTIC(NumFnDeleted , "Number of functions deleted"); 48STATISTIC(NumGlobUses , "Number of global uses devirtualized"); 49STATISTIC(NumLocalized , "Number of globals localized"); 50STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans"); 51STATISTIC(NumFastCallFns , "Number of functions converted to fastcc"); 52STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated"); 53STATISTIC(NumNestRemoved , "Number of nest attributes removed"); 54STATISTIC(NumAliasesResolved, "Number of global aliases resolved"); 55STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated"); 56 57namespace { 58 struct GlobalOpt : public ModulePass { 59 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 60 } 61 static char ID; // Pass identification, replacement for typeid 62 GlobalOpt() : ModulePass(&ID) {} 63 64 bool runOnModule(Module &M); 65 66 private: 67 GlobalVariable *FindGlobalCtors(Module &M); 68 bool OptimizeFunctions(Module &M); 69 bool OptimizeGlobalVars(Module &M); 70 bool OptimizeGlobalAliases(Module &M); 71 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL); 72 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI); 73 }; 74} 75 76char GlobalOpt::ID = 0; 77static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer"); 78 79ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); } 80 81namespace { 82 83/// GlobalStatus - As we analyze each global, keep track of some information 84/// about it. If we find out that the address of the global is taken, none of 85/// this info will be accurate. 86struct GlobalStatus { 87 /// isLoaded - True if the global is ever loaded. If the global isn't ever 88 /// loaded it can be deleted. 89 bool isLoaded; 90 91 /// StoredType - Keep track of what stores to the global look like. 92 /// 93 enum StoredType { 94 /// NotStored - There is no store to this global. It can thus be marked 95 /// constant. 96 NotStored, 97 98 /// isInitializerStored - This global is stored to, but the only thing 99 /// stored is the constant it was initialized with. This is only tracked 100 /// for scalar globals. 101 isInitializerStored, 102 103 /// isStoredOnce - This global is stored to, but only its initializer and 104 /// one other value is ever stored to it. If this global isStoredOnce, we 105 /// track the value stored to it in StoredOnceValue below. This is only 106 /// tracked for scalar globals. 107 isStoredOnce, 108 109 /// isStored - This global is stored to by multiple values or something else 110 /// that we cannot track. 111 isStored 112 } StoredType; 113 114 /// StoredOnceValue - If only one value (besides the initializer constant) is 115 /// ever stored to this global, keep track of what value it is. 116 Value *StoredOnceValue; 117 118 /// AccessingFunction/HasMultipleAccessingFunctions - These start out 119 /// null/false. When the first accessing function is noticed, it is recorded. 120 /// When a second different accessing function is noticed, 121 /// HasMultipleAccessingFunctions is set to true. 122 const Function *AccessingFunction; 123 bool HasMultipleAccessingFunctions; 124 125 /// HasNonInstructionUser - Set to true if this global has a user that is not 126 /// an instruction (e.g. a constant expr or GV initializer). 127 bool HasNonInstructionUser; 128 129 /// HasPHIUser - Set to true if this global has a user that is a PHI node. 130 bool HasPHIUser; 131 132 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0), 133 AccessingFunction(0), HasMultipleAccessingFunctions(false), 134 HasNonInstructionUser(false), HasPHIUser(false) {} 135}; 136 137} 138 139// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used 140// by constants itself. Note that constants cannot be cyclic, so this test is 141// pretty easy to implement recursively. 142// 143static bool SafeToDestroyConstant(const Constant *C) { 144 if (isa<GlobalValue>(C)) return false; 145 146 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; 147 ++UI) 148 if (const Constant *CU = dyn_cast<Constant>(*UI)) { 149 if (!SafeToDestroyConstant(CU)) return false; 150 } else 151 return false; 152 return true; 153} 154 155 156/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus 157/// structure. If the global has its address taken, return true to indicate we 158/// can't do anything with it. 159/// 160static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS, 161 SmallPtrSet<const PHINode*, 16> &PHIUsers) { 162 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; 163 ++UI) 164 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) { 165 GS.HasNonInstructionUser = true; 166 167 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true; 168 169 } else if (const Instruction *I = dyn_cast<Instruction>(*UI)) { 170 if (!GS.HasMultipleAccessingFunctions) { 171 const Function *F = I->getParent()->getParent(); 172 if (GS.AccessingFunction == 0) 173 GS.AccessingFunction = F; 174 else if (GS.AccessingFunction != F) 175 GS.HasMultipleAccessingFunctions = true; 176 } 177 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 178 GS.isLoaded = true; 179 if (LI->isVolatile()) return true; // Don't hack on volatile loads. 180 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) { 181 // Don't allow a store OF the address, only stores TO the address. 182 if (SI->getOperand(0) == V) return true; 183 184 if (SI->isVolatile()) return true; // Don't hack on volatile stores. 185 186 // If this is a direct store to the global (i.e., the global is a scalar 187 // value, not an aggregate), keep more specific information about 188 // stores. 189 if (GS.StoredType != GlobalStatus::isStored) { 190 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>( 191 SI->getOperand(1))) { 192 Value *StoredVal = SI->getOperand(0); 193 if (StoredVal == GV->getInitializer()) { 194 if (GS.StoredType < GlobalStatus::isInitializerStored) 195 GS.StoredType = GlobalStatus::isInitializerStored; 196 } else if (isa<LoadInst>(StoredVal) && 197 cast<LoadInst>(StoredVal)->getOperand(0) == GV) { 198 if (GS.StoredType < GlobalStatus::isInitializerStored) 199 GS.StoredType = GlobalStatus::isInitializerStored; 200 } else if (GS.StoredType < GlobalStatus::isStoredOnce) { 201 GS.StoredType = GlobalStatus::isStoredOnce; 202 GS.StoredOnceValue = StoredVal; 203 } else if (GS.StoredType == GlobalStatus::isStoredOnce && 204 GS.StoredOnceValue == StoredVal) { 205 // noop. 206 } else { 207 GS.StoredType = GlobalStatus::isStored; 208 } 209 } else { 210 GS.StoredType = GlobalStatus::isStored; 211 } 212 } 213 } else if (isa<GetElementPtrInst>(I)) { 214 if (AnalyzeGlobal(I, GS, PHIUsers)) return true; 215 } else if (isa<SelectInst>(I)) { 216 if (AnalyzeGlobal(I, GS, PHIUsers)) return true; 217 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) { 218 // PHI nodes we can check just like select or GEP instructions, but we 219 // have to be careful about infinite recursion. 220 if (PHIUsers.insert(PN)) // Not already visited. 221 if (AnalyzeGlobal(I, GS, PHIUsers)) return true; 222 GS.HasPHIUser = true; 223 } else if (isa<CmpInst>(I)) { 224 } else if (isa<MemTransferInst>(I)) { 225 if (I->getOperand(1) == V) 226 GS.StoredType = GlobalStatus::isStored; 227 if (I->getOperand(2) == V) 228 GS.isLoaded = true; 229 } else if (isa<MemSetInst>(I)) { 230 assert(I->getOperand(1) == V && "Memset only takes one pointer!"); 231 GS.StoredType = GlobalStatus::isStored; 232 } else { 233 return true; // Any other non-load instruction might take address! 234 } 235 } else if (const Constant *C = dyn_cast<Constant>(*UI)) { 236 GS.HasNonInstructionUser = true; 237 // We might have a dead and dangling constant hanging off of here. 238 if (!SafeToDestroyConstant(C)) 239 return true; 240 } else { 241 GS.HasNonInstructionUser = true; 242 // Otherwise must be some other user. 243 return true; 244 } 245 246 return false; 247} 248 249static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) { 250 ConstantInt *CI = dyn_cast<ConstantInt>(Idx); 251 if (!CI) return 0; 252 unsigned IdxV = CI->getZExtValue(); 253 254 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) { 255 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV); 256 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) { 257 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV); 258 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) { 259 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV); 260 } else if (isa<ConstantAggregateZero>(Agg)) { 261 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) { 262 if (IdxV < STy->getNumElements()) 263 return Constant::getNullValue(STy->getElementType(IdxV)); 264 } else if (const SequentialType *STy = 265 dyn_cast<SequentialType>(Agg->getType())) { 266 return Constant::getNullValue(STy->getElementType()); 267 } 268 } else if (isa<UndefValue>(Agg)) { 269 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) { 270 if (IdxV < STy->getNumElements()) 271 return UndefValue::get(STy->getElementType(IdxV)); 272 } else if (const SequentialType *STy = 273 dyn_cast<SequentialType>(Agg->getType())) { 274 return UndefValue::get(STy->getElementType()); 275 } 276 } 277 return 0; 278} 279 280 281/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all 282/// users of the global, cleaning up the obvious ones. This is largely just a 283/// quick scan over the use list to clean up the easy and obvious cruft. This 284/// returns true if it made a change. 285static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) { 286 bool Changed = false; 287 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) { 288 User *U = *UI++; 289 290 if (LoadInst *LI = dyn_cast<LoadInst>(U)) { 291 if (Init) { 292 // Replace the load with the initializer. 293 LI->replaceAllUsesWith(Init); 294 LI->eraseFromParent(); 295 Changed = true; 296 } 297 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 298 // Store must be unreachable or storing Init into the global. 299 SI->eraseFromParent(); 300 Changed = true; 301 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) { 302 if (CE->getOpcode() == Instruction::GetElementPtr) { 303 Constant *SubInit = 0; 304 if (Init) 305 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE); 306 Changed |= CleanupConstantGlobalUsers(CE, SubInit); 307 } else if (CE->getOpcode() == Instruction::BitCast && 308 CE->getType()->isPointerTy()) { 309 // Pointer cast, delete any stores and memsets to the global. 310 Changed |= CleanupConstantGlobalUsers(CE, 0); 311 } 312 313 if (CE->use_empty()) { 314 CE->destroyConstant(); 315 Changed = true; 316 } 317 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) { 318 // Do not transform "gepinst (gep constexpr (GV))" here, because forming 319 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold 320 // and will invalidate our notion of what Init is. 321 Constant *SubInit = 0; 322 if (!isa<ConstantExpr>(GEP->getOperand(0))) { 323 ConstantExpr *CE = 324 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP)); 325 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr) 326 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE); 327 } 328 Changed |= CleanupConstantGlobalUsers(GEP, SubInit); 329 330 if (GEP->use_empty()) { 331 GEP->eraseFromParent(); 332 Changed = true; 333 } 334 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv 335 if (MI->getRawDest() == V) { 336 MI->eraseFromParent(); 337 Changed = true; 338 } 339 340 } else if (Constant *C = dyn_cast<Constant>(U)) { 341 // If we have a chain of dead constantexprs or other things dangling from 342 // us, and if they are all dead, nuke them without remorse. 343 if (SafeToDestroyConstant(C)) { 344 C->destroyConstant(); 345 // This could have invalidated UI, start over from scratch. 346 CleanupConstantGlobalUsers(V, Init); 347 return true; 348 } 349 } 350 } 351 return Changed; 352} 353 354/// isSafeSROAElementUse - Return true if the specified instruction is a safe 355/// user of a derived expression from a global that we want to SROA. 356static bool isSafeSROAElementUse(Value *V) { 357 // We might have a dead and dangling constant hanging off of here. 358 if (Constant *C = dyn_cast<Constant>(V)) 359 return SafeToDestroyConstant(C); 360 361 Instruction *I = dyn_cast<Instruction>(V); 362 if (!I) return false; 363 364 // Loads are ok. 365 if (isa<LoadInst>(I)) return true; 366 367 // Stores *to* the pointer are ok. 368 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 369 return SI->getOperand(0) != V; 370 371 // Otherwise, it must be a GEP. 372 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I); 373 if (GEPI == 0) return false; 374 375 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) || 376 !cast<Constant>(GEPI->getOperand(1))->isNullValue()) 377 return false; 378 379 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end(); 380 I != E; ++I) 381 if (!isSafeSROAElementUse(*I)) 382 return false; 383 return true; 384} 385 386 387/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value. 388/// Look at it and its uses and decide whether it is safe to SROA this global. 389/// 390static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) { 391 // The user of the global must be a GEP Inst or a ConstantExpr GEP. 392 if (!isa<GetElementPtrInst>(U) && 393 (!isa<ConstantExpr>(U) || 394 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr)) 395 return false; 396 397 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we 398 // don't like < 3 operand CE's, and we don't like non-constant integer 399 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some 400 // value of C. 401 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) || 402 !cast<Constant>(U->getOperand(1))->isNullValue() || 403 !isa<ConstantInt>(U->getOperand(2))) 404 return false; 405 406 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U); 407 ++GEPI; // Skip over the pointer index. 408 409 // If this is a use of an array allocation, do a bit more checking for sanity. 410 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) { 411 uint64_t NumElements = AT->getNumElements(); 412 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2)); 413 414 // Check to make sure that index falls within the array. If not, 415 // something funny is going on, so we won't do the optimization. 416 // 417 if (Idx->getZExtValue() >= NumElements) 418 return false; 419 420 // We cannot scalar repl this level of the array unless any array 421 // sub-indices are in-range constants. In particular, consider: 422 // A[0][i]. We cannot know that the user isn't doing invalid things like 423 // allowing i to index an out-of-range subscript that accesses A[1]. 424 // 425 // Scalar replacing *just* the outer index of the array is probably not 426 // going to be a win anyway, so just give up. 427 for (++GEPI; // Skip array index. 428 GEPI != E; 429 ++GEPI) { 430 uint64_t NumElements; 431 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI)) 432 NumElements = SubArrayTy->getNumElements(); 433 else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI)) 434 NumElements = SubVectorTy->getNumElements(); 435 else { 436 assert((*GEPI)->isStructTy() && 437 "Indexed GEP type is not array, vector, or struct!"); 438 continue; 439 } 440 441 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand()); 442 if (!IdxVal || IdxVal->getZExtValue() >= NumElements) 443 return false; 444 } 445 } 446 447 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I) 448 if (!isSafeSROAElementUse(*I)) 449 return false; 450 return true; 451} 452 453/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it 454/// is safe for us to perform this transformation. 455/// 456static bool GlobalUsersSafeToSRA(GlobalValue *GV) { 457 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); 458 UI != E; ++UI) { 459 if (!IsUserOfGlobalSafeForSRA(*UI, GV)) 460 return false; 461 } 462 return true; 463} 464 465 466/// SRAGlobal - Perform scalar replacement of aggregates on the specified global 467/// variable. This opens the door for other optimizations by exposing the 468/// behavior of the program in a more fine-grained way. We have determined that 469/// this transformation is safe already. We return the first global variable we 470/// insert so that the caller can reprocess it. 471static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) { 472 // Make sure this global only has simple uses that we can SRA. 473 if (!GlobalUsersSafeToSRA(GV)) 474 return 0; 475 476 assert(GV->hasLocalLinkage() && !GV->isConstant()); 477 Constant *Init = GV->getInitializer(); 478 const Type *Ty = Init->getType(); 479 480 std::vector<GlobalVariable*> NewGlobals; 481 Module::GlobalListType &Globals = GV->getParent()->getGlobalList(); 482 483 // Get the alignment of the global, either explicit or target-specific. 484 unsigned StartAlignment = GV->getAlignment(); 485 if (StartAlignment == 0) 486 StartAlignment = TD.getABITypeAlignment(GV->getType()); 487 488 if (const StructType *STy = dyn_cast<StructType>(Ty)) { 489 NewGlobals.reserve(STy->getNumElements()); 490 const StructLayout &Layout = *TD.getStructLayout(STy); 491 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 492 Constant *In = getAggregateConstantElement(Init, 493 ConstantInt::get(Type::getInt32Ty(STy->getContext()), i)); 494 assert(In && "Couldn't get element of initializer?"); 495 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false, 496 GlobalVariable::InternalLinkage, 497 In, GV->getName()+"."+Twine(i), 498 GV->isThreadLocal(), 499 GV->getType()->getAddressSpace()); 500 Globals.insert(GV, NGV); 501 NewGlobals.push_back(NGV); 502 503 // Calculate the known alignment of the field. If the original aggregate 504 // had 256 byte alignment for example, something might depend on that: 505 // propagate info to each field. 506 uint64_t FieldOffset = Layout.getElementOffset(i); 507 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset); 508 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i))) 509 NGV->setAlignment(NewAlign); 510 } 511 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) { 512 unsigned NumElements = 0; 513 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy)) 514 NumElements = ATy->getNumElements(); 515 else 516 NumElements = cast<VectorType>(STy)->getNumElements(); 517 518 if (NumElements > 16 && GV->hasNUsesOrMore(16)) 519 return 0; // It's not worth it. 520 NewGlobals.reserve(NumElements); 521 522 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType()); 523 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType()); 524 for (unsigned i = 0, e = NumElements; i != e; ++i) { 525 Constant *In = getAggregateConstantElement(Init, 526 ConstantInt::get(Type::getInt32Ty(Init->getContext()), i)); 527 assert(In && "Couldn't get element of initializer?"); 528 529 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false, 530 GlobalVariable::InternalLinkage, 531 In, GV->getName()+"."+Twine(i), 532 GV->isThreadLocal(), 533 GV->getType()->getAddressSpace()); 534 Globals.insert(GV, NGV); 535 NewGlobals.push_back(NGV); 536 537 // Calculate the known alignment of the field. If the original aggregate 538 // had 256 byte alignment for example, something might depend on that: 539 // propagate info to each field. 540 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i); 541 if (NewAlign > EltAlign) 542 NGV->setAlignment(NewAlign); 543 } 544 } 545 546 if (NewGlobals.empty()) 547 return 0; 548 549 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV); 550 551 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext())); 552 553 // Loop over all of the uses of the global, replacing the constantexpr geps, 554 // with smaller constantexpr geps or direct references. 555 while (!GV->use_empty()) { 556 User *GEP = GV->use_back(); 557 assert(((isa<ConstantExpr>(GEP) && 558 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)|| 559 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!"); 560 561 // Ignore the 1th operand, which has to be zero or else the program is quite 562 // broken (undefined). Get the 2nd operand, which is the structure or array 563 // index. 564 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue(); 565 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access. 566 567 Value *NewPtr = NewGlobals[Val]; 568 569 // Form a shorter GEP if needed. 570 if (GEP->getNumOperands() > 3) { 571 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) { 572 SmallVector<Constant*, 8> Idxs; 573 Idxs.push_back(NullInt); 574 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i) 575 Idxs.push_back(CE->getOperand(i)); 576 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), 577 &Idxs[0], Idxs.size()); 578 } else { 579 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP); 580 SmallVector<Value*, 8> Idxs; 581 Idxs.push_back(NullInt); 582 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i) 583 Idxs.push_back(GEPI->getOperand(i)); 584 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(), 585 GEPI->getName()+"."+Twine(Val),GEPI); 586 } 587 } 588 GEP->replaceAllUsesWith(NewPtr); 589 590 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP)) 591 GEPI->eraseFromParent(); 592 else 593 cast<ConstantExpr>(GEP)->destroyConstant(); 594 } 595 596 // Delete the old global, now that it is dead. 597 Globals.erase(GV); 598 ++NumSRA; 599 600 // Loop over the new globals array deleting any globals that are obviously 601 // dead. This can arise due to scalarization of a structure or an array that 602 // has elements that are dead. 603 unsigned FirstGlobal = 0; 604 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i) 605 if (NewGlobals[i]->use_empty()) { 606 Globals.erase(NewGlobals[i]); 607 if (FirstGlobal == i) ++FirstGlobal; 608 } 609 610 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0; 611} 612 613/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified 614/// value will trap if the value is dynamically null. PHIs keeps track of any 615/// phi nodes we've seen to avoid reprocessing them. 616static bool AllUsesOfValueWillTrapIfNull(const Value *V, 617 SmallPtrSet<const PHINode*, 8> &PHIs) { 618 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; 619 ++UI) { 620 const User *U = *UI; 621 622 if (isa<LoadInst>(U)) { 623 // Will trap. 624 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) { 625 if (SI->getOperand(0) == V) { 626 //cerr << "NONTRAPPING USE: " << *U; 627 return false; // Storing the value. 628 } 629 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) { 630 if (CI->getCalledValue() != V) { 631 //cerr << "NONTRAPPING USE: " << *U; 632 return false; // Not calling the ptr 633 } 634 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) { 635 if (II->getCalledValue() != V) { 636 //cerr << "NONTRAPPING USE: " << *U; 637 return false; // Not calling the ptr 638 } 639 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) { 640 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false; 641 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) { 642 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false; 643 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) { 644 // If we've already seen this phi node, ignore it, it has already been 645 // checked. 646 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs)) 647 return false; 648 } else if (isa<ICmpInst>(U) && 649 isa<ConstantPointerNull>(UI->getOperand(1))) { 650 // Ignore icmp X, null 651 } else { 652 //cerr << "NONTRAPPING USE: " << *U; 653 return false; 654 } 655 } 656 return true; 657} 658 659/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads 660/// from GV will trap if the loaded value is null. Note that this also permits 661/// comparisons of the loaded value against null, as a special case. 662static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) { 663 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end(); 664 UI != E; ++UI) { 665 const User *U = *UI; 666 667 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) { 668 SmallPtrSet<const PHINode*, 8> PHIs; 669 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs)) 670 return false; 671 } else if (isa<StoreInst>(U)) { 672 // Ignore stores to the global. 673 } else { 674 // We don't know or understand this user, bail out. 675 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U; 676 return false; 677 } 678 } 679 return true; 680} 681 682static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) { 683 bool Changed = false; 684 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) { 685 Instruction *I = cast<Instruction>(*UI++); 686 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 687 LI->setOperand(0, NewV); 688 Changed = true; 689 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 690 if (SI->getOperand(1) == V) { 691 SI->setOperand(1, NewV); 692 Changed = true; 693 } 694 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) { 695 CallSite CS(I); 696 if (CS.getCalledValue() == V) { 697 // Calling through the pointer! Turn into a direct call, but be careful 698 // that the pointer is not also being passed as an argument. 699 CS.setCalledFunction(NewV); 700 Changed = true; 701 bool PassedAsArg = false; 702 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i) 703 if (CS.getArgument(i) == V) { 704 PassedAsArg = true; 705 CS.setArgument(i, NewV); 706 } 707 708 if (PassedAsArg) { 709 // Being passed as an argument also. Be careful to not invalidate UI! 710 UI = V->use_begin(); 711 } 712 } 713 } else if (CastInst *CI = dyn_cast<CastInst>(I)) { 714 Changed |= OptimizeAwayTrappingUsesOfValue(CI, 715 ConstantExpr::getCast(CI->getOpcode(), 716 NewV, CI->getType())); 717 if (CI->use_empty()) { 718 Changed = true; 719 CI->eraseFromParent(); 720 } 721 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { 722 // Should handle GEP here. 723 SmallVector<Constant*, 8> Idxs; 724 Idxs.reserve(GEPI->getNumOperands()-1); 725 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end(); 726 i != e; ++i) 727 if (Constant *C = dyn_cast<Constant>(*i)) 728 Idxs.push_back(C); 729 else 730 break; 731 if (Idxs.size() == GEPI->getNumOperands()-1) 732 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI, 733 ConstantExpr::getGetElementPtr(NewV, &Idxs[0], 734 Idxs.size())); 735 if (GEPI->use_empty()) { 736 Changed = true; 737 GEPI->eraseFromParent(); 738 } 739 } 740 } 741 742 return Changed; 743} 744 745 746/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null 747/// value stored into it. If there are uses of the loaded value that would trap 748/// if the loaded value is dynamically null, then we know that they cannot be 749/// reachable with a null optimize away the load. 750static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) { 751 bool Changed = false; 752 753 // Keep track of whether we are able to remove all the uses of the global 754 // other than the store that defines it. 755 bool AllNonStoreUsesGone = true; 756 757 // Replace all uses of loads with uses of uses of the stored value. 758 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){ 759 User *GlobalUser = *GUI++; 760 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) { 761 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV); 762 // If we were able to delete all uses of the loads 763 if (LI->use_empty()) { 764 LI->eraseFromParent(); 765 Changed = true; 766 } else { 767 AllNonStoreUsesGone = false; 768 } 769 } else if (isa<StoreInst>(GlobalUser)) { 770 // Ignore the store that stores "LV" to the global. 771 assert(GlobalUser->getOperand(1) == GV && 772 "Must be storing *to* the global"); 773 } else { 774 AllNonStoreUsesGone = false; 775 776 // If we get here we could have other crazy uses that are transitively 777 // loaded. 778 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) || 779 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!"); 780 } 781 } 782 783 if (Changed) { 784 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV); 785 ++NumGlobUses; 786 } 787 788 // If we nuked all of the loads, then none of the stores are needed either, 789 // nor is the global. 790 if (AllNonStoreUsesGone) { 791 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n"); 792 CleanupConstantGlobalUsers(GV, 0); 793 if (GV->use_empty()) { 794 GV->eraseFromParent(); 795 ++NumDeleted; 796 } 797 Changed = true; 798 } 799 return Changed; 800} 801 802/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the 803/// instructions that are foldable. 804static void ConstantPropUsersOf(Value *V) { 805 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) 806 if (Instruction *I = dyn_cast<Instruction>(*UI++)) 807 if (Constant *NewC = ConstantFoldInstruction(I)) { 808 I->replaceAllUsesWith(NewC); 809 810 // Advance UI to the next non-I use to avoid invalidating it! 811 // Instructions could multiply use V. 812 while (UI != E && *UI == I) 813 ++UI; 814 I->eraseFromParent(); 815 } 816} 817 818/// OptimizeGlobalAddressOfMalloc - This function takes the specified global 819/// variable, and transforms the program as if it always contained the result of 820/// the specified malloc. Because it is always the result of the specified 821/// malloc, there is no reason to actually DO the malloc. Instead, turn the 822/// malloc into a global, and any loads of GV as uses of the new global. 823static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, 824 CallInst *CI, 825 const Type *AllocTy, 826 ConstantInt *NElements, 827 TargetData* TD) { 828 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n'); 829 830 const Type *GlobalType; 831 if (NElements->getZExtValue() == 1) 832 GlobalType = AllocTy; 833 else 834 // If we have an array allocation, the global variable is of an array. 835 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue()); 836 837 // Create the new global variable. The contents of the malloc'd memory is 838 // undefined, so initialize with an undef value. 839 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(), 840 GlobalType, false, 841 GlobalValue::InternalLinkage, 842 UndefValue::get(GlobalType), 843 GV->getName()+".body", 844 GV, 845 GV->isThreadLocal()); 846 847 // If there are bitcast users of the malloc (which is typical, usually we have 848 // a malloc + bitcast) then replace them with uses of the new global. Update 849 // other users to use the global as well. 850 BitCastInst *TheBC = 0; 851 while (!CI->use_empty()) { 852 Instruction *User = cast<Instruction>(CI->use_back()); 853 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) { 854 if (BCI->getType() == NewGV->getType()) { 855 BCI->replaceAllUsesWith(NewGV); 856 BCI->eraseFromParent(); 857 } else { 858 BCI->setOperand(0, NewGV); 859 } 860 } else { 861 if (TheBC == 0) 862 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI); 863 User->replaceUsesOfWith(CI, TheBC); 864 } 865 } 866 867 Constant *RepValue = NewGV; 868 if (NewGV->getType() != GV->getType()->getElementType()) 869 RepValue = ConstantExpr::getBitCast(RepValue, 870 GV->getType()->getElementType()); 871 872 // If there is a comparison against null, we will insert a global bool to 873 // keep track of whether the global was initialized yet or not. 874 GlobalVariable *InitBool = 875 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false, 876 GlobalValue::InternalLinkage, 877 ConstantInt::getFalse(GV->getContext()), 878 GV->getName()+".init", GV->isThreadLocal()); 879 bool InitBoolUsed = false; 880 881 // Loop over all uses of GV, processing them in turn. 882 while (!GV->use_empty()) { 883 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) { 884 // The global is initialized when the store to it occurs. 885 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI); 886 SI->eraseFromParent(); 887 continue; 888 } 889 890 LoadInst *LI = cast<LoadInst>(GV->use_back()); 891 while (!LI->use_empty()) { 892 Use &LoadUse = LI->use_begin().getUse(); 893 if (!isa<ICmpInst>(LoadUse.getUser())) { 894 LoadUse = RepValue; 895 continue; 896 } 897 898 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser()); 899 // Replace the cmp X, 0 with a use of the bool value. 900 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI); 901 InitBoolUsed = true; 902 switch (ICI->getPredicate()) { 903 default: llvm_unreachable("Unknown ICmp Predicate!"); 904 case ICmpInst::ICMP_ULT: 905 case ICmpInst::ICMP_SLT: // X < null -> always false 906 LV = ConstantInt::getFalse(GV->getContext()); 907 break; 908 case ICmpInst::ICMP_ULE: 909 case ICmpInst::ICMP_SLE: 910 case ICmpInst::ICMP_EQ: 911 LV = BinaryOperator::CreateNot(LV, "notinit", ICI); 912 break; 913 case ICmpInst::ICMP_NE: 914 case ICmpInst::ICMP_UGE: 915 case ICmpInst::ICMP_SGE: 916 case ICmpInst::ICMP_UGT: 917 case ICmpInst::ICMP_SGT: 918 break; // no change. 919 } 920 ICI->replaceAllUsesWith(LV); 921 ICI->eraseFromParent(); 922 } 923 LI->eraseFromParent(); 924 } 925 926 // If the initialization boolean was used, insert it, otherwise delete it. 927 if (!InitBoolUsed) { 928 while (!InitBool->use_empty()) // Delete initializations 929 cast<StoreInst>(InitBool->use_back())->eraseFromParent(); 930 delete InitBool; 931 } else 932 GV->getParent()->getGlobalList().insert(GV, InitBool); 933 934 // Now the GV is dead, nuke it and the malloc.. 935 GV->eraseFromParent(); 936 CI->eraseFromParent(); 937 938 // To further other optimizations, loop over all users of NewGV and try to 939 // constant prop them. This will promote GEP instructions with constant 940 // indices into GEP constant-exprs, which will allow global-opt to hack on it. 941 ConstantPropUsersOf(NewGV); 942 if (RepValue != NewGV) 943 ConstantPropUsersOf(RepValue); 944 945 return NewGV; 946} 947 948/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking 949/// to make sure that there are no complex uses of V. We permit simple things 950/// like dereferencing the pointer, but not storing through the address, unless 951/// it is to the specified global. 952static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V, 953 const GlobalVariable *GV, 954 SmallPtrSet<const PHINode*, 8> &PHIs) { 955 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); 956 UI != E; ++UI) { 957 const Instruction *Inst = cast<Instruction>(*UI); 958 959 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) { 960 continue; // Fine, ignore. 961 } 962 963 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 964 if (SI->getOperand(0) == V && SI->getOperand(1) != GV) 965 return false; // Storing the pointer itself... bad. 966 continue; // Otherwise, storing through it, or storing into GV... fine. 967 } 968 969 // Must index into the array and into the struct. 970 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) { 971 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs)) 972 return false; 973 continue; 974 } 975 976 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) { 977 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI 978 // cycles. 979 if (PHIs.insert(PN)) 980 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs)) 981 return false; 982 continue; 983 } 984 985 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) { 986 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs)) 987 return false; 988 continue; 989 } 990 991 return false; 992 } 993 return true; 994} 995 996/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV 997/// somewhere. Transform all uses of the allocation into loads from the 998/// global and uses of the resultant pointer. Further, delete the store into 999/// GV. This assumes that these value pass the 1000/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate. 1001static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc, 1002 GlobalVariable *GV) { 1003 while (!Alloc->use_empty()) { 1004 Instruction *U = cast<Instruction>(*Alloc->use_begin()); 1005 Instruction *InsertPt = U; 1006 if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 1007 // If this is the store of the allocation into the global, remove it. 1008 if (SI->getOperand(1) == GV) { 1009 SI->eraseFromParent(); 1010 continue; 1011 } 1012 } else if (PHINode *PN = dyn_cast<PHINode>(U)) { 1013 // Insert the load in the corresponding predecessor, not right before the 1014 // PHI. 1015 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator(); 1016 } else if (isa<BitCastInst>(U)) { 1017 // Must be bitcast between the malloc and store to initialize the global. 1018 ReplaceUsesOfMallocWithGlobal(U, GV); 1019 U->eraseFromParent(); 1020 continue; 1021 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) { 1022 // If this is a "GEP bitcast" and the user is a store to the global, then 1023 // just process it as a bitcast. 1024 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse()) 1025 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back())) 1026 if (SI->getOperand(1) == GV) { 1027 // Must be bitcast GEP between the malloc and store to initialize 1028 // the global. 1029 ReplaceUsesOfMallocWithGlobal(GEPI, GV); 1030 GEPI->eraseFromParent(); 1031 continue; 1032 } 1033 } 1034 1035 // Insert a load from the global, and use it instead of the malloc. 1036 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt); 1037 U->replaceUsesOfWith(Alloc, NL); 1038 } 1039} 1040 1041/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi 1042/// of a load) are simple enough to perform heap SRA on. This permits GEP's 1043/// that index through the array and struct field, icmps of null, and PHIs. 1044static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V, 1045 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs, 1046 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) { 1047 // We permit two users of the load: setcc comparing against the null 1048 // pointer, and a getelementptr of a specific form. 1049 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; 1050 ++UI) { 1051 const Instruction *User = cast<Instruction>(*UI); 1052 1053 // Comparison against null is ok. 1054 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) { 1055 if (!isa<ConstantPointerNull>(ICI->getOperand(1))) 1056 return false; 1057 continue; 1058 } 1059 1060 // getelementptr is also ok, but only a simple form. 1061 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { 1062 // Must index into the array and into the struct. 1063 if (GEPI->getNumOperands() < 3) 1064 return false; 1065 1066 // Otherwise the GEP is ok. 1067 continue; 1068 } 1069 1070 if (const PHINode *PN = dyn_cast<PHINode>(User)) { 1071 if (!LoadUsingPHIsPerLoad.insert(PN)) 1072 // This means some phi nodes are dependent on each other. 1073 // Avoid infinite looping! 1074 return false; 1075 if (!LoadUsingPHIs.insert(PN)) 1076 // If we have already analyzed this PHI, then it is safe. 1077 continue; 1078 1079 // Make sure all uses of the PHI are simple enough to transform. 1080 if (!LoadUsesSimpleEnoughForHeapSRA(PN, 1081 LoadUsingPHIs, LoadUsingPHIsPerLoad)) 1082 return false; 1083 1084 continue; 1085 } 1086 1087 // Otherwise we don't know what this is, not ok. 1088 return false; 1089 } 1090 1091 return true; 1092} 1093 1094 1095/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from 1096/// GV are simple enough to perform HeapSRA, return true. 1097static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV, 1098 Instruction *StoredVal) { 1099 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs; 1100 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad; 1101 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end(); 1102 UI != E; ++UI) 1103 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) { 1104 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs, 1105 LoadUsingPHIsPerLoad)) 1106 return false; 1107 LoadUsingPHIsPerLoad.clear(); 1108 } 1109 1110 // If we reach here, we know that all uses of the loads and transitive uses 1111 // (through PHI nodes) are simple enough to transform. However, we don't know 1112 // that all inputs the to the PHI nodes are in the same equivalence sets. 1113 // Check to verify that all operands of the PHIs are either PHIS that can be 1114 // transformed, loads from GV, or MI itself. 1115 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin() 1116 , E = LoadUsingPHIs.end(); I != E; ++I) { 1117 const PHINode *PN = *I; 1118 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) { 1119 Value *InVal = PN->getIncomingValue(op); 1120 1121 // PHI of the stored value itself is ok. 1122 if (InVal == StoredVal) continue; 1123 1124 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) { 1125 // One of the PHIs in our set is (optimistically) ok. 1126 if (LoadUsingPHIs.count(InPN)) 1127 continue; 1128 return false; 1129 } 1130 1131 // Load from GV is ok. 1132 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal)) 1133 if (LI->getOperand(0) == GV) 1134 continue; 1135 1136 // UNDEF? NULL? 1137 1138 // Anything else is rejected. 1139 return false; 1140 } 1141 } 1142 1143 return true; 1144} 1145 1146static Value *GetHeapSROAValue(Value *V, unsigned FieldNo, 1147 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues, 1148 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) { 1149 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V]; 1150 1151 if (FieldNo >= FieldVals.size()) 1152 FieldVals.resize(FieldNo+1); 1153 1154 // If we already have this value, just reuse the previously scalarized 1155 // version. 1156 if (Value *FieldVal = FieldVals[FieldNo]) 1157 return FieldVal; 1158 1159 // Depending on what instruction this is, we have several cases. 1160 Value *Result; 1161 if (LoadInst *LI = dyn_cast<LoadInst>(V)) { 1162 // This is a scalarized version of the load from the global. Just create 1163 // a new Load of the scalarized global. 1164 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo, 1165 InsertedScalarizedValues, 1166 PHIsToRewrite), 1167 LI->getName()+".f"+Twine(FieldNo), LI); 1168 } else if (PHINode *PN = dyn_cast<PHINode>(V)) { 1169 // PN's type is pointer to struct. Make a new PHI of pointer to struct 1170 // field. 1171 const StructType *ST = 1172 cast<StructType>(cast<PointerType>(PN->getType())->getElementType()); 1173 1174 Result = 1175 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)), 1176 PN->getName()+".f"+Twine(FieldNo), PN); 1177 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo)); 1178 } else { 1179 llvm_unreachable("Unknown usable value"); 1180 Result = 0; 1181 } 1182 1183 return FieldVals[FieldNo] = Result; 1184} 1185 1186/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from 1187/// the load, rewrite the derived value to use the HeapSRoA'd load. 1188static void RewriteHeapSROALoadUser(Instruction *LoadUser, 1189 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues, 1190 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) { 1191 // If this is a comparison against null, handle it. 1192 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) { 1193 assert(isa<ConstantPointerNull>(SCI->getOperand(1))); 1194 // If we have a setcc of the loaded pointer, we can use a setcc of any 1195 // field. 1196 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0, 1197 InsertedScalarizedValues, PHIsToRewrite); 1198 1199 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr, 1200 Constant::getNullValue(NPtr->getType()), 1201 SCI->getName()); 1202 SCI->replaceAllUsesWith(New); 1203 SCI->eraseFromParent(); 1204 return; 1205 } 1206 1207 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...' 1208 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) { 1209 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2)) 1210 && "Unexpected GEPI!"); 1211 1212 // Load the pointer for this field. 1213 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue(); 1214 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo, 1215 InsertedScalarizedValues, PHIsToRewrite); 1216 1217 // Create the new GEP idx vector. 1218 SmallVector<Value*, 8> GEPIdx; 1219 GEPIdx.push_back(GEPI->getOperand(1)); 1220 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end()); 1221 1222 Value *NGEPI = GetElementPtrInst::Create(NewPtr, 1223 GEPIdx.begin(), GEPIdx.end(), 1224 GEPI->getName(), GEPI); 1225 GEPI->replaceAllUsesWith(NGEPI); 1226 GEPI->eraseFromParent(); 1227 return; 1228 } 1229 1230 // Recursively transform the users of PHI nodes. This will lazily create the 1231 // PHIs that are needed for individual elements. Keep track of what PHIs we 1232 // see in InsertedScalarizedValues so that we don't get infinite loops (very 1233 // antisocial). If the PHI is already in InsertedScalarizedValues, it has 1234 // already been seen first by another load, so its uses have already been 1235 // processed. 1236 PHINode *PN = cast<PHINode>(LoadUser); 1237 bool Inserted; 1238 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos; 1239 tie(InsertPos, Inserted) = 1240 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>())); 1241 if (!Inserted) return; 1242 1243 // If this is the first time we've seen this PHI, recursively process all 1244 // users. 1245 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) { 1246 Instruction *User = cast<Instruction>(*UI++); 1247 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite); 1248 } 1249} 1250 1251/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr 1252/// is a value loaded from the global. Eliminate all uses of Ptr, making them 1253/// use FieldGlobals instead. All uses of loaded values satisfy 1254/// AllGlobalLoadUsesSimpleEnoughForHeapSRA. 1255static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load, 1256 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues, 1257 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) { 1258 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end(); 1259 UI != E; ) { 1260 Instruction *User = cast<Instruction>(*UI++); 1261 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite); 1262 } 1263 1264 if (Load->use_empty()) { 1265 Load->eraseFromParent(); 1266 InsertedScalarizedValues.erase(Load); 1267 } 1268} 1269 1270/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break 1271/// it up into multiple allocations of arrays of the fields. 1272static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI, 1273 Value* NElems, TargetData *TD) { 1274 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n'); 1275 const Type* MAT = getMallocAllocatedType(CI); 1276 const StructType *STy = cast<StructType>(MAT); 1277 1278 // There is guaranteed to be at least one use of the malloc (storing 1279 // it into GV). If there are other uses, change them to be uses of 1280 // the global to simplify later code. This also deletes the store 1281 // into GV. 1282 ReplaceUsesOfMallocWithGlobal(CI, GV); 1283 1284 // Okay, at this point, there are no users of the malloc. Insert N 1285 // new mallocs at the same place as CI, and N globals. 1286 std::vector<Value*> FieldGlobals; 1287 std::vector<Value*> FieldMallocs; 1288 1289 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){ 1290 const Type *FieldTy = STy->getElementType(FieldNo); 1291 const PointerType *PFieldTy = PointerType::getUnqual(FieldTy); 1292 1293 GlobalVariable *NGV = 1294 new GlobalVariable(*GV->getParent(), 1295 PFieldTy, false, GlobalValue::InternalLinkage, 1296 Constant::getNullValue(PFieldTy), 1297 GV->getName() + ".f" + Twine(FieldNo), GV, 1298 GV->isThreadLocal()); 1299 FieldGlobals.push_back(NGV); 1300 1301 unsigned TypeSize = TD->getTypeAllocSize(FieldTy); 1302 if (const StructType *ST = dyn_cast<StructType>(FieldTy)) 1303 TypeSize = TD->getStructLayout(ST)->getSizeInBytes(); 1304 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext()); 1305 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy, 1306 ConstantInt::get(IntPtrTy, TypeSize), 1307 NElems, 1308 CI->getName() + ".f" + Twine(FieldNo)); 1309 FieldMallocs.push_back(NMI); 1310 new StoreInst(NMI, NGV, CI); 1311 } 1312 1313 // The tricky aspect of this transformation is handling the case when malloc 1314 // fails. In the original code, malloc failing would set the result pointer 1315 // of malloc to null. In this case, some mallocs could succeed and others 1316 // could fail. As such, we emit code that looks like this: 1317 // F0 = malloc(field0) 1318 // F1 = malloc(field1) 1319 // F2 = malloc(field2) 1320 // if (F0 == 0 || F1 == 0 || F2 == 0) { 1321 // if (F0) { free(F0); F0 = 0; } 1322 // if (F1) { free(F1); F1 = 0; } 1323 // if (F2) { free(F2); F2 = 0; } 1324 // } 1325 // The malloc can also fail if its argument is too large. 1326 Constant *ConstantZero = ConstantInt::get(CI->getOperand(1)->getType(), 0); 1327 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getOperand(1), 1328 ConstantZero, "isneg"); 1329 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) { 1330 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i], 1331 Constant::getNullValue(FieldMallocs[i]->getType()), 1332 "isnull"); 1333 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI); 1334 } 1335 1336 // Split the basic block at the old malloc. 1337 BasicBlock *OrigBB = CI->getParent(); 1338 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont"); 1339 1340 // Create the block to check the first condition. Put all these blocks at the 1341 // end of the function as they are unlikely to be executed. 1342 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(), 1343 "malloc_ret_null", 1344 OrigBB->getParent()); 1345 1346 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond 1347 // branch on RunningOr. 1348 OrigBB->getTerminator()->eraseFromParent(); 1349 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB); 1350 1351 // Within the NullPtrBlock, we need to emit a comparison and branch for each 1352 // pointer, because some may be null while others are not. 1353 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) { 1354 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock); 1355 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal, 1356 Constant::getNullValue(GVVal->getType()), 1357 "tmp"); 1358 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it", 1359 OrigBB->getParent()); 1360 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next", 1361 OrigBB->getParent()); 1362 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock, 1363 Cmp, NullPtrBlock); 1364 1365 // Fill in FreeBlock. 1366 CallInst::CreateFree(GVVal, BI); 1367 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i], 1368 FreeBlock); 1369 BranchInst::Create(NextBlock, FreeBlock); 1370 1371 NullPtrBlock = NextBlock; 1372 } 1373 1374 BranchInst::Create(ContBB, NullPtrBlock); 1375 1376 // CI is no longer needed, remove it. 1377 CI->eraseFromParent(); 1378 1379 /// InsertedScalarizedLoads - As we process loads, if we can't immediately 1380 /// update all uses of the load, keep track of what scalarized loads are 1381 /// inserted for a given load. 1382 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues; 1383 InsertedScalarizedValues[GV] = FieldGlobals; 1384 1385 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite; 1386 1387 // Okay, the malloc site is completely handled. All of the uses of GV are now 1388 // loads, and all uses of those loads are simple. Rewrite them to use loads 1389 // of the per-field globals instead. 1390 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) { 1391 Instruction *User = cast<Instruction>(*UI++); 1392 1393 if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 1394 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite); 1395 continue; 1396 } 1397 1398 // Must be a store of null. 1399 StoreInst *SI = cast<StoreInst>(User); 1400 assert(isa<ConstantPointerNull>(SI->getOperand(0)) && 1401 "Unexpected heap-sra user!"); 1402 1403 // Insert a store of null into each global. 1404 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) { 1405 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType()); 1406 Constant *Null = Constant::getNullValue(PT->getElementType()); 1407 new StoreInst(Null, FieldGlobals[i], SI); 1408 } 1409 // Erase the original store. 1410 SI->eraseFromParent(); 1411 } 1412 1413 // While we have PHIs that are interesting to rewrite, do it. 1414 while (!PHIsToRewrite.empty()) { 1415 PHINode *PN = PHIsToRewrite.back().first; 1416 unsigned FieldNo = PHIsToRewrite.back().second; 1417 PHIsToRewrite.pop_back(); 1418 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]); 1419 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi"); 1420 1421 // Add all the incoming values. This can materialize more phis. 1422 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1423 Value *InVal = PN->getIncomingValue(i); 1424 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues, 1425 PHIsToRewrite); 1426 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i)); 1427 } 1428 } 1429 1430 // Drop all inter-phi links and any loads that made it this far. 1431 for (DenseMap<Value*, std::vector<Value*> >::iterator 1432 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end(); 1433 I != E; ++I) { 1434 if (PHINode *PN = dyn_cast<PHINode>(I->first)) 1435 PN->dropAllReferences(); 1436 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first)) 1437 LI->dropAllReferences(); 1438 } 1439 1440 // Delete all the phis and loads now that inter-references are dead. 1441 for (DenseMap<Value*, std::vector<Value*> >::iterator 1442 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end(); 1443 I != E; ++I) { 1444 if (PHINode *PN = dyn_cast<PHINode>(I->first)) 1445 PN->eraseFromParent(); 1446 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first)) 1447 LI->eraseFromParent(); 1448 } 1449 1450 // The old global is now dead, remove it. 1451 GV->eraseFromParent(); 1452 1453 ++NumHeapSRA; 1454 return cast<GlobalVariable>(FieldGlobals[0]); 1455} 1456 1457/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a 1458/// pointer global variable with a single value stored it that is a malloc or 1459/// cast of malloc. 1460static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV, 1461 CallInst *CI, 1462 const Type *AllocTy, 1463 Module::global_iterator &GVI, 1464 TargetData *TD) { 1465 if (!TD) 1466 return false; 1467 1468 // If this is a malloc of an abstract type, don't touch it. 1469 if (!AllocTy->isSized()) 1470 return false; 1471 1472 // We can't optimize this global unless all uses of it are *known* to be 1473 // of the malloc value, not of the null initializer value (consider a use 1474 // that compares the global's value against zero to see if the malloc has 1475 // been reached). To do this, we check to see if all uses of the global 1476 // would trap if the global were null: this proves that they must all 1477 // happen after the malloc. 1478 if (!AllUsesOfLoadedValueWillTrapIfNull(GV)) 1479 return false; 1480 1481 // We can't optimize this if the malloc itself is used in a complex way, 1482 // for example, being stored into multiple globals. This allows the 1483 // malloc to be stored into the specified global, loaded setcc'd, and 1484 // GEP'd. These are all things we could transform to using the global 1485 // for. 1486 SmallPtrSet<const PHINode*, 8> PHIs; 1487 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs)) 1488 return false; 1489 1490 // If we have a global that is only initialized with a fixed size malloc, 1491 // transform the program to use global memory instead of malloc'd memory. 1492 // This eliminates dynamic allocation, avoids an indirection accessing the 1493 // data, and exposes the resultant global to further GlobalOpt. 1494 // We cannot optimize the malloc if we cannot determine malloc array size. 1495 Value *NElems = getMallocArraySize(CI, TD, true); 1496 if (!NElems) 1497 return false; 1498 1499 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems)) 1500 // Restrict this transformation to only working on small allocations 1501 // (2048 bytes currently), as we don't want to introduce a 16M global or 1502 // something. 1503 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) { 1504 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD); 1505 return true; 1506 } 1507 1508 // If the allocation is an array of structures, consider transforming this 1509 // into multiple malloc'd arrays, one for each field. This is basically 1510 // SRoA for malloc'd memory. 1511 1512 // If this is an allocation of a fixed size array of structs, analyze as a 1513 // variable size array. malloc [100 x struct],1 -> malloc struct, 100 1514 if (NElems == ConstantInt::get(CI->getOperand(1)->getType(), 1)) 1515 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy)) 1516 AllocTy = AT->getElementType(); 1517 1518 const StructType *AllocSTy = dyn_cast<StructType>(AllocTy); 1519 if (!AllocSTy) 1520 return false; 1521 1522 // This the structure has an unreasonable number of fields, leave it 1523 // alone. 1524 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 && 1525 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) { 1526 1527 // If this is a fixed size array, transform the Malloc to be an alloc of 1528 // structs. malloc [100 x struct],1 -> malloc struct, 100 1529 if (const ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) { 1530 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext()); 1531 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes(); 1532 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize); 1533 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements()); 1534 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy, 1535 AllocSize, NumElements, 1536 CI->getName()); 1537 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI); 1538 CI->replaceAllUsesWith(Cast); 1539 CI->eraseFromParent(); 1540 CI = dyn_cast<BitCastInst>(Malloc) ? 1541 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc); 1542 } 1543 1544 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD); 1545 return true; 1546 } 1547 1548 return false; 1549} 1550 1551// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge 1552// that only one value (besides its initializer) is ever stored to the global. 1553static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, 1554 Module::global_iterator &GVI, 1555 TargetData *TD) { 1556 // Ignore no-op GEPs and bitcasts. 1557 StoredOnceVal = StoredOnceVal->stripPointerCasts(); 1558 1559 // If we are dealing with a pointer global that is initialized to null and 1560 // only has one (non-null) value stored into it, then we can optimize any 1561 // users of the loaded value (often calls and loads) that would trap if the 1562 // value was null. 1563 if (GV->getInitializer()->getType()->isPointerTy() && 1564 GV->getInitializer()->isNullValue()) { 1565 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) { 1566 if (GV->getInitializer()->getType() != SOVC->getType()) 1567 SOVC = 1568 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType()); 1569 1570 // Optimize away any trapping uses of the loaded value. 1571 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC)) 1572 return true; 1573 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) { 1574 const Type* MallocType = getMallocAllocatedType(CI); 1575 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, 1576 GVI, TD)) 1577 return true; 1578 } 1579 } 1580 1581 return false; 1582} 1583 1584/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only 1585/// two values ever stored into GV are its initializer and OtherVal. See if we 1586/// can shrink the global into a boolean and select between the two values 1587/// whenever it is used. This exposes the values to other scalar optimizations. 1588static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) { 1589 const Type *GVElType = GV->getType()->getElementType(); 1590 1591 // If GVElType is already i1, it is already shrunk. If the type of the GV is 1592 // an FP value, pointer or vector, don't do this optimization because a select 1593 // between them is very expensive and unlikely to lead to later 1594 // simplification. In these cases, we typically end up with "cond ? v1 : v2" 1595 // where v1 and v2 both require constant pool loads, a big loss. 1596 if (GVElType == Type::getInt1Ty(GV->getContext()) || 1597 GVElType->isFloatingPointTy() || 1598 GVElType->isPointerTy() || GVElType->isVectorTy()) 1599 return false; 1600 1601 // Walk the use list of the global seeing if all the uses are load or store. 1602 // If there is anything else, bail out. 1603 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I) 1604 if (!isa<LoadInst>(I) && !isa<StoreInst>(I)) 1605 return false; 1606 1607 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV); 1608 1609 // Create the new global, initializing it to false. 1610 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()), 1611 false, 1612 GlobalValue::InternalLinkage, 1613 ConstantInt::getFalse(GV->getContext()), 1614 GV->getName()+".b", 1615 GV->isThreadLocal()); 1616 GV->getParent()->getGlobalList().insert(GV, NewGV); 1617 1618 Constant *InitVal = GV->getInitializer(); 1619 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) && 1620 "No reason to shrink to bool!"); 1621 1622 // If initialized to zero and storing one into the global, we can use a cast 1623 // instead of a select to synthesize the desired value. 1624 bool IsOneZero = false; 1625 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) 1626 IsOneZero = InitVal->isNullValue() && CI->isOne(); 1627 1628 while (!GV->use_empty()) { 1629 Instruction *UI = cast<Instruction>(GV->use_back()); 1630 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) { 1631 // Change the store into a boolean store. 1632 bool StoringOther = SI->getOperand(0) == OtherVal; 1633 // Only do this if we weren't storing a loaded value. 1634 Value *StoreVal; 1635 if (StoringOther || SI->getOperand(0) == InitVal) 1636 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()), 1637 StoringOther); 1638 else { 1639 // Otherwise, we are storing a previously loaded copy. To do this, 1640 // change the copy from copying the original value to just copying the 1641 // bool. 1642 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0)); 1643 1644 // If we're already replaced the input, StoredVal will be a cast or 1645 // select instruction. If not, it will be a load of the original 1646 // global. 1647 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) { 1648 assert(LI->getOperand(0) == GV && "Not a copy!"); 1649 // Insert a new load, to preserve the saved value. 1650 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI); 1651 } else { 1652 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) && 1653 "This is not a form that we understand!"); 1654 StoreVal = StoredVal->getOperand(0); 1655 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!"); 1656 } 1657 } 1658 new StoreInst(StoreVal, NewGV, SI); 1659 } else { 1660 // Change the load into a load of bool then a select. 1661 LoadInst *LI = cast<LoadInst>(UI); 1662 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI); 1663 Value *NSI; 1664 if (IsOneZero) 1665 NSI = new ZExtInst(NLI, LI->getType(), "", LI); 1666 else 1667 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI); 1668 NSI->takeName(LI); 1669 LI->replaceAllUsesWith(NSI); 1670 } 1671 UI->eraseFromParent(); 1672 } 1673 1674 GV->eraseFromParent(); 1675 return true; 1676} 1677 1678 1679/// ProcessInternalGlobal - Analyze the specified global variable and optimize 1680/// it if possible. If we make a change, return true. 1681bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV, 1682 Module::global_iterator &GVI) { 1683 SmallPtrSet<const PHINode*, 16> PHIUsers; 1684 GlobalStatus GS; 1685 GV->removeDeadConstantUsers(); 1686 1687 if (GV->use_empty()) { 1688 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV); 1689 GV->eraseFromParent(); 1690 ++NumDeleted; 1691 return true; 1692 } 1693 1694 if (!AnalyzeGlobal(GV, GS, PHIUsers)) { 1695#if 0 1696 DEBUG(dbgs() << "Global: " << *GV); 1697 DEBUG(dbgs() << " isLoaded = " << GS.isLoaded << "\n"); 1698 DEBUG(dbgs() << " StoredType = "); 1699 switch (GS.StoredType) { 1700 case GlobalStatus::NotStored: DEBUG(dbgs() << "NEVER STORED\n"); break; 1701 case GlobalStatus::isInitializerStored: DEBUG(dbgs() << "INIT STORED\n"); 1702 break; 1703 case GlobalStatus::isStoredOnce: DEBUG(dbgs() << "STORED ONCE\n"); break; 1704 case GlobalStatus::isStored: DEBUG(dbgs() << "stored\n"); break; 1705 } 1706 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue) 1707 DEBUG(dbgs() << " StoredOnceValue = " << *GS.StoredOnceValue << "\n"); 1708 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions) 1709 DEBUG(dbgs() << " AccessingFunction = " 1710 << GS.AccessingFunction->getName() << "\n"); 1711 DEBUG(dbgs() << " HasMultipleAccessingFunctions = " 1712 << GS.HasMultipleAccessingFunctions << "\n"); 1713 DEBUG(dbgs() << " HasNonInstructionUser = " 1714 << GS.HasNonInstructionUser<<"\n"); 1715 DEBUG(dbgs() << "\n"); 1716#endif 1717 1718 // If this is a first class global and has only one accessing function 1719 // and this function is main (which we know is not recursive we can make 1720 // this global a local variable) we replace the global with a local alloca 1721 // in this function. 1722 // 1723 // NOTE: It doesn't make sense to promote non single-value types since we 1724 // are just replacing static memory to stack memory. 1725 // 1726 // If the global is in different address space, don't bring it to stack. 1727 if (!GS.HasMultipleAccessingFunctions && 1728 GS.AccessingFunction && !GS.HasNonInstructionUser && 1729 GV->getType()->getElementType()->isSingleValueType() && 1730 GS.AccessingFunction->getName() == "main" && 1731 GS.AccessingFunction->hasExternalLinkage() && 1732 GV->getType()->getAddressSpace() == 0) { 1733 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV); 1734 Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction 1735 ->getEntryBlock().begin()); 1736 const Type* ElemTy = GV->getType()->getElementType(); 1737 // FIXME: Pass Global's alignment when globals have alignment 1738 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI); 1739 if (!isa<UndefValue>(GV->getInitializer())) 1740 new StoreInst(GV->getInitializer(), Alloca, &FirstI); 1741 1742 GV->replaceAllUsesWith(Alloca); 1743 GV->eraseFromParent(); 1744 ++NumLocalized; 1745 return true; 1746 } 1747 1748 // If the global is never loaded (but may be stored to), it is dead. 1749 // Delete it now. 1750 if (!GS.isLoaded) { 1751 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV); 1752 1753 // Delete any stores we can find to the global. We may not be able to 1754 // make it completely dead though. 1755 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer()); 1756 1757 // If the global is dead now, delete it. 1758 if (GV->use_empty()) { 1759 GV->eraseFromParent(); 1760 ++NumDeleted; 1761 Changed = true; 1762 } 1763 return Changed; 1764 1765 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) { 1766 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV); 1767 GV->setConstant(true); 1768 1769 // Clean up any obviously simplifiable users now. 1770 CleanupConstantGlobalUsers(GV, GV->getInitializer()); 1771 1772 // If the global is dead now, just nuke it. 1773 if (GV->use_empty()) { 1774 DEBUG(dbgs() << " *** Marking constant allowed us to simplify " 1775 << "all users and delete global!\n"); 1776 GV->eraseFromParent(); 1777 ++NumDeleted; 1778 } 1779 1780 ++NumMarked; 1781 return true; 1782 } else if (!GV->getInitializer()->getType()->isSingleValueType()) { 1783 if (TargetData *TD = getAnalysisIfAvailable<TargetData>()) 1784 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) { 1785 GVI = FirstNewGV; // Don't skip the newly produced globals! 1786 return true; 1787 } 1788 } else if (GS.StoredType == GlobalStatus::isStoredOnce) { 1789 // If the initial value for the global was an undef value, and if only 1790 // one other value was stored into it, we can just change the 1791 // initializer to be the stored value, then delete all stores to the 1792 // global. This allows us to mark it constant. 1793 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) 1794 if (isa<UndefValue>(GV->getInitializer())) { 1795 // Change the initial value here. 1796 GV->setInitializer(SOVConstant); 1797 1798 // Clean up any obviously simplifiable users now. 1799 CleanupConstantGlobalUsers(GV, GV->getInitializer()); 1800 1801 if (GV->use_empty()) { 1802 DEBUG(dbgs() << " *** Substituting initializer allowed us to " 1803 << "simplify all users and delete global!\n"); 1804 GV->eraseFromParent(); 1805 ++NumDeleted; 1806 } else { 1807 GVI = GV; 1808 } 1809 ++NumSubstitute; 1810 return true; 1811 } 1812 1813 // Try to optimize globals based on the knowledge that only one value 1814 // (besides its initializer) is ever stored to the global. 1815 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI, 1816 getAnalysisIfAvailable<TargetData>())) 1817 return true; 1818 1819 // Otherwise, if the global was not a boolean, we can shrink it to be a 1820 // boolean. 1821 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) 1822 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) { 1823 ++NumShrunkToBool; 1824 return true; 1825 } 1826 } 1827 } 1828 return false; 1829} 1830 1831/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified 1832/// function, changing them to FastCC. 1833static void ChangeCalleesToFastCall(Function *F) { 1834 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){ 1835 CallSite User(cast<Instruction>(*UI)); 1836 User.setCallingConv(CallingConv::Fast); 1837 } 1838} 1839 1840static AttrListPtr StripNest(const AttrListPtr &Attrs) { 1841 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) { 1842 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0) 1843 continue; 1844 1845 // There can be only one. 1846 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest); 1847 } 1848 1849 return Attrs; 1850} 1851 1852static void RemoveNestAttribute(Function *F) { 1853 F->setAttributes(StripNest(F->getAttributes())); 1854 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){ 1855 CallSite User(cast<Instruction>(*UI)); 1856 User.setAttributes(StripNest(User.getAttributes())); 1857 } 1858} 1859 1860bool GlobalOpt::OptimizeFunctions(Module &M) { 1861 bool Changed = false; 1862 // Optimize functions. 1863 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) { 1864 Function *F = FI++; 1865 // Functions without names cannot be referenced outside this module. 1866 if (!F->hasName() && !F->isDeclaration()) 1867 F->setLinkage(GlobalValue::InternalLinkage); 1868 F->removeDeadConstantUsers(); 1869 if (F->use_empty() && (F->hasLocalLinkage() || F->hasLinkOnceLinkage())) { 1870 F->eraseFromParent(); 1871 Changed = true; 1872 ++NumFnDeleted; 1873 } else if (F->hasLocalLinkage()) { 1874 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() && 1875 !F->hasAddressTaken()) { 1876 // If this function has C calling conventions, is not a varargs 1877 // function, and is only called directly, promote it to use the Fast 1878 // calling convention. 1879 F->setCallingConv(CallingConv::Fast); 1880 ChangeCalleesToFastCall(F); 1881 ++NumFastCallFns; 1882 Changed = true; 1883 } 1884 1885 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) && 1886 !F->hasAddressTaken()) { 1887 // The function is not used by a trampoline intrinsic, so it is safe 1888 // to remove the 'nest' attribute. 1889 RemoveNestAttribute(F); 1890 ++NumNestRemoved; 1891 Changed = true; 1892 } 1893 } 1894 } 1895 return Changed; 1896} 1897 1898bool GlobalOpt::OptimizeGlobalVars(Module &M) { 1899 bool Changed = false; 1900 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end(); 1901 GVI != E; ) { 1902 GlobalVariable *GV = GVI++; 1903 // Global variables without names cannot be referenced outside this module. 1904 if (!GV->hasName() && !GV->isDeclaration()) 1905 GV->setLinkage(GlobalValue::InternalLinkage); 1906 // Simplify the initializer. 1907 if (GV->hasInitializer()) 1908 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) { 1909 TargetData *TD = getAnalysisIfAvailable<TargetData>(); 1910 Constant *New = ConstantFoldConstantExpression(CE, TD); 1911 if (New && New != CE) 1912 GV->setInitializer(New); 1913 } 1914 // Do more involved optimizations if the global is internal. 1915 if (!GV->isConstant() && GV->hasLocalLinkage() && 1916 GV->hasInitializer()) 1917 Changed |= ProcessInternalGlobal(GV, GVI); 1918 } 1919 return Changed; 1920} 1921 1922/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all 1923/// initializers have an init priority of 65535. 1924GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) { 1925 for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 1926 I != E; ++I) 1927 if (I->getName() == "llvm.global_ctors") { 1928 // Found it, verify it's an array of { int, void()* }. 1929 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType()); 1930 if (!ATy) return 0; 1931 const StructType *STy = dyn_cast<StructType>(ATy->getElementType()); 1932 if (!STy || STy->getNumElements() != 2 || 1933 !STy->getElementType(0)->isIntegerTy(32)) return 0; 1934 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1)); 1935 if (!PFTy) return 0; 1936 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType()); 1937 if (!FTy || !FTy->getReturnType()->isVoidTy() || 1938 FTy->isVarArg() || FTy->getNumParams() != 0) 1939 return 0; 1940 1941 // Verify that the initializer is simple enough for us to handle. 1942 if (!I->hasDefinitiveInitializer()) return 0; 1943 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer()); 1944 if (!CA) return 0; 1945 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) 1946 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) { 1947 if (isa<ConstantPointerNull>(CS->getOperand(1))) 1948 continue; 1949 1950 // Must have a function or null ptr. 1951 if (!isa<Function>(CS->getOperand(1))) 1952 return 0; 1953 1954 // Init priority must be standard. 1955 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0)); 1956 if (!CI || CI->getZExtValue() != 65535) 1957 return 0; 1958 } else { 1959 return 0; 1960 } 1961 1962 return I; 1963 } 1964 return 0; 1965} 1966 1967/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand, 1968/// return a list of the functions and null terminator as a vector. 1969static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) { 1970 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer()); 1971 std::vector<Function*> Result; 1972 Result.reserve(CA->getNumOperands()); 1973 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) { 1974 ConstantStruct *CS = cast<ConstantStruct>(*i); 1975 Result.push_back(dyn_cast<Function>(CS->getOperand(1))); 1976 } 1977 return Result; 1978} 1979 1980/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the 1981/// specified array, returning the new global to use. 1982static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL, 1983 const std::vector<Function*> &Ctors) { 1984 // If we made a change, reassemble the initializer list. 1985 std::vector<Constant*> CSVals; 1986 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(GCL->getContext()),65535)); 1987 CSVals.push_back(0); 1988 1989 // Create the new init list. 1990 std::vector<Constant*> CAList; 1991 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) { 1992 if (Ctors[i]) { 1993 CSVals[1] = Ctors[i]; 1994 } else { 1995 const Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()), 1996 false); 1997 const PointerType *PFTy = PointerType::getUnqual(FTy); 1998 CSVals[1] = Constant::getNullValue(PFTy); 1999 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 2000 2147483647); 2001 } 2002 CAList.push_back(ConstantStruct::get(GCL->getContext(), CSVals, false)); 2003 } 2004 2005 // Create the array initializer. 2006 const Type *StructTy = 2007 cast<ArrayType>(GCL->getType()->getElementType())->getElementType(); 2008 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, 2009 CAList.size()), CAList); 2010 2011 // If we didn't change the number of elements, don't create a new GV. 2012 if (CA->getType() == GCL->getInitializer()->getType()) { 2013 GCL->setInitializer(CA); 2014 return GCL; 2015 } 2016 2017 // Create the new global and insert it next to the existing list. 2018 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(), 2019 GCL->getLinkage(), CA, "", 2020 GCL->isThreadLocal()); 2021 GCL->getParent()->getGlobalList().insert(GCL, NGV); 2022 NGV->takeName(GCL); 2023 2024 // Nuke the old list, replacing any uses with the new one. 2025 if (!GCL->use_empty()) { 2026 Constant *V = NGV; 2027 if (V->getType() != GCL->getType()) 2028 V = ConstantExpr::getBitCast(V, GCL->getType()); 2029 GCL->replaceAllUsesWith(V); 2030 } 2031 GCL->eraseFromParent(); 2032 2033 if (Ctors.size()) 2034 return NGV; 2035 else 2036 return 0; 2037} 2038 2039 2040static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues, 2041 Value *V) { 2042 if (Constant *CV = dyn_cast<Constant>(V)) return CV; 2043 Constant *R = ComputedValues[V]; 2044 assert(R && "Reference to an uncomputed value!"); 2045 return R; 2046} 2047 2048/// isSimpleEnoughPointerToCommit - Return true if this constant is simple 2049/// enough for us to understand. In particular, if it is a cast of something, 2050/// we punt. We basically just support direct accesses to globals and GEP's of 2051/// globals. This should be kept up to date with CommitValueTo. 2052static bool isSimpleEnoughPointerToCommit(Constant *C) { 2053 // Conservatively, avoid aggregate types. This is because we don't 2054 // want to worry about them partially overlapping other stores. 2055 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType()) 2056 return false; 2057 2058 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) 2059 // Do not allow weak/linkonce/dllimport/dllexport linkage or 2060 // external globals. 2061 return GV->hasDefinitiveInitializer(); 2062 2063 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) 2064 // Handle a constantexpr gep. 2065 if (CE->getOpcode() == Instruction::GetElementPtr && 2066 isa<GlobalVariable>(CE->getOperand(0)) && 2067 cast<GEPOperator>(CE)->isInBounds()) { 2068 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0)); 2069 // Do not allow weak/linkonce/dllimport/dllexport linkage or 2070 // external globals. 2071 if (!GV->hasDefinitiveInitializer()) 2072 return false; 2073 2074 // The first index must be zero. 2075 ConstantInt *CI = dyn_cast<ConstantInt>(*next(CE->op_begin())); 2076 if (!CI || !CI->isZero()) return false; 2077 2078 // The remaining indices must be compile-time known integers within the 2079 // notional bounds of the corresponding static array types. 2080 if (!CE->isGEPWithNoNotionalOverIndexing()) 2081 return false; 2082 2083 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE); 2084 } 2085 return false; 2086} 2087 2088/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global 2089/// initializer. This returns 'Init' modified to reflect 'Val' stored into it. 2090/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into. 2091static Constant *EvaluateStoreInto(Constant *Init, Constant *Val, 2092 ConstantExpr *Addr, unsigned OpNo) { 2093 // Base case of the recursion. 2094 if (OpNo == Addr->getNumOperands()) { 2095 assert(Val->getType() == Init->getType() && "Type mismatch!"); 2096 return Val; 2097 } 2098 2099 std::vector<Constant*> Elts; 2100 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) { 2101 2102 // Break up the constant into its elements. 2103 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) { 2104 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i) 2105 Elts.push_back(cast<Constant>(*i)); 2106 } else if (isa<ConstantAggregateZero>(Init)) { 2107 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 2108 Elts.push_back(Constant::getNullValue(STy->getElementType(i))); 2109 } else if (isa<UndefValue>(Init)) { 2110 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 2111 Elts.push_back(UndefValue::get(STy->getElementType(i))); 2112 } else { 2113 llvm_unreachable("This code is out of sync with " 2114 " ConstantFoldLoadThroughGEPConstantExpr"); 2115 } 2116 2117 // Replace the element that we are supposed to. 2118 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo)); 2119 unsigned Idx = CU->getZExtValue(); 2120 assert(Idx < STy->getNumElements() && "Struct index out of range!"); 2121 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1); 2122 2123 // Return the modified struct. 2124 return ConstantStruct::get(Init->getContext(), &Elts[0], Elts.size(), 2125 STy->isPacked()); 2126 } else { 2127 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo)); 2128 const SequentialType *InitTy = cast<SequentialType>(Init->getType()); 2129 2130 uint64_t NumElts; 2131 if (const ArrayType *ATy = dyn_cast<ArrayType>(InitTy)) 2132 NumElts = ATy->getNumElements(); 2133 else 2134 NumElts = cast<VectorType>(InitTy)->getNumElements(); 2135 2136 2137 // Break up the array into elements. 2138 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) { 2139 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) 2140 Elts.push_back(cast<Constant>(*i)); 2141 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) { 2142 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i) 2143 Elts.push_back(cast<Constant>(*i)); 2144 } else if (isa<ConstantAggregateZero>(Init)) { 2145 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType())); 2146 } else { 2147 assert(isa<UndefValue>(Init) && "This code is out of sync with " 2148 " ConstantFoldLoadThroughGEPConstantExpr"); 2149 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType())); 2150 } 2151 2152 assert(CI->getZExtValue() < NumElts); 2153 Elts[CI->getZExtValue()] = 2154 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1); 2155 2156 if (Init->getType()->isArrayTy()) 2157 return ConstantArray::get(cast<ArrayType>(InitTy), Elts); 2158 else 2159 return ConstantVector::get(&Elts[0], Elts.size()); 2160 } 2161} 2162 2163/// CommitValueTo - We have decided that Addr (which satisfies the predicate 2164/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen. 2165static void CommitValueTo(Constant *Val, Constant *Addr) { 2166 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) { 2167 assert(GV->hasInitializer()); 2168 GV->setInitializer(Val); 2169 return; 2170 } 2171 2172 ConstantExpr *CE = cast<ConstantExpr>(Addr); 2173 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0)); 2174 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2)); 2175} 2176 2177/// ComputeLoadResult - Return the value that would be computed by a load from 2178/// P after the stores reflected by 'memory' have been performed. If we can't 2179/// decide, return null. 2180static Constant *ComputeLoadResult(Constant *P, 2181 const DenseMap<Constant*, Constant*> &Memory) { 2182 // If this memory location has been recently stored, use the stored value: it 2183 // is the most up-to-date. 2184 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P); 2185 if (I != Memory.end()) return I->second; 2186 2187 // Access it. 2188 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) { 2189 if (GV->hasDefinitiveInitializer()) 2190 return GV->getInitializer(); 2191 return 0; 2192 } 2193 2194 // Handle a constantexpr getelementptr. 2195 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P)) 2196 if (CE->getOpcode() == Instruction::GetElementPtr && 2197 isa<GlobalVariable>(CE->getOperand(0))) { 2198 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0)); 2199 if (GV->hasDefinitiveInitializer()) 2200 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE); 2201 } 2202 2203 return 0; // don't know how to evaluate. 2204} 2205 2206/// EvaluateFunction - Evaluate a call to function F, returning true if 2207/// successful, false if we can't evaluate it. ActualArgs contains the formal 2208/// arguments for the function. 2209static bool EvaluateFunction(Function *F, Constant *&RetVal, 2210 const SmallVectorImpl<Constant*> &ActualArgs, 2211 std::vector<Function*> &CallStack, 2212 DenseMap<Constant*, Constant*> &MutatedMemory, 2213 std::vector<GlobalVariable*> &AllocaTmps) { 2214 // Check to see if this function is already executing (recursion). If so, 2215 // bail out. TODO: we might want to accept limited recursion. 2216 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end()) 2217 return false; 2218 2219 CallStack.push_back(F); 2220 2221 /// Values - As we compute SSA register values, we store their contents here. 2222 DenseMap<Value*, Constant*> Values; 2223 2224 // Initialize arguments to the incoming values specified. 2225 unsigned ArgNo = 0; 2226 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E; 2227 ++AI, ++ArgNo) 2228 Values[AI] = ActualArgs[ArgNo]; 2229 2230 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such, 2231 /// we can only evaluate any one basic block at most once. This set keeps 2232 /// track of what we have executed so we can detect recursive cases etc. 2233 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks; 2234 2235 // CurInst - The current instruction we're evaluating. 2236 BasicBlock::iterator CurInst = F->begin()->begin(); 2237 2238 // This is the main evaluation loop. 2239 while (1) { 2240 Constant *InstResult = 0; 2241 2242 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) { 2243 if (SI->isVolatile()) return false; // no volatile accesses. 2244 Constant *Ptr = getVal(Values, SI->getOperand(1)); 2245 if (!isSimpleEnoughPointerToCommit(Ptr)) 2246 // If this is too complex for us to commit, reject it. 2247 return false; 2248 Constant *Val = getVal(Values, SI->getOperand(0)); 2249 MutatedMemory[Ptr] = Val; 2250 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) { 2251 InstResult = ConstantExpr::get(BO->getOpcode(), 2252 getVal(Values, BO->getOperand(0)), 2253 getVal(Values, BO->getOperand(1))); 2254 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) { 2255 InstResult = ConstantExpr::getCompare(CI->getPredicate(), 2256 getVal(Values, CI->getOperand(0)), 2257 getVal(Values, CI->getOperand(1))); 2258 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) { 2259 InstResult = ConstantExpr::getCast(CI->getOpcode(), 2260 getVal(Values, CI->getOperand(0)), 2261 CI->getType()); 2262 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) { 2263 InstResult = 2264 ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)), 2265 getVal(Values, SI->getOperand(1)), 2266 getVal(Values, SI->getOperand(2))); 2267 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) { 2268 Constant *P = getVal(Values, GEP->getOperand(0)); 2269 SmallVector<Constant*, 8> GEPOps; 2270 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); 2271 i != e; ++i) 2272 GEPOps.push_back(getVal(Values, *i)); 2273 InstResult = cast<GEPOperator>(GEP)->isInBounds() ? 2274 ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) : 2275 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size()); 2276 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) { 2277 if (LI->isVolatile()) return false; // no volatile accesses. 2278 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)), 2279 MutatedMemory); 2280 if (InstResult == 0) return false; // Could not evaluate load. 2281 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) { 2282 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs. 2283 const Type *Ty = AI->getType()->getElementType(); 2284 AllocaTmps.push_back(new GlobalVariable(Ty, false, 2285 GlobalValue::InternalLinkage, 2286 UndefValue::get(Ty), 2287 AI->getName())); 2288 InstResult = AllocaTmps.back(); 2289 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) { 2290 2291 // Debug info can safely be ignored here. 2292 if (isa<DbgInfoIntrinsic>(CI)) { 2293 ++CurInst; 2294 continue; 2295 } 2296 2297 // Cannot handle inline asm. 2298 if (isa<InlineAsm>(CI->getOperand(0))) return false; 2299 2300 // Resolve function pointers. 2301 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0))); 2302 if (!Callee) return false; // Cannot resolve. 2303 2304 SmallVector<Constant*, 8> Formals; 2305 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end(); 2306 i != e; ++i) 2307 Formals.push_back(getVal(Values, *i)); 2308 2309 if (Callee->isDeclaration()) { 2310 // If this is a function we can constant fold, do it. 2311 if (Constant *C = ConstantFoldCall(Callee, Formals.data(), 2312 Formals.size())) { 2313 InstResult = C; 2314 } else { 2315 return false; 2316 } 2317 } else { 2318 if (Callee->getFunctionType()->isVarArg()) 2319 return false; 2320 2321 Constant *RetVal; 2322 // Execute the call, if successful, use the return value. 2323 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack, 2324 MutatedMemory, AllocaTmps)) 2325 return false; 2326 InstResult = RetVal; 2327 } 2328 } else if (isa<TerminatorInst>(CurInst)) { 2329 BasicBlock *NewBB = 0; 2330 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) { 2331 if (BI->isUnconditional()) { 2332 NewBB = BI->getSuccessor(0); 2333 } else { 2334 ConstantInt *Cond = 2335 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition())); 2336 if (!Cond) return false; // Cannot determine. 2337 2338 NewBB = BI->getSuccessor(!Cond->getZExtValue()); 2339 } 2340 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) { 2341 ConstantInt *Val = 2342 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition())); 2343 if (!Val) return false; // Cannot determine. 2344 NewBB = SI->getSuccessor(SI->findCaseValue(Val)); 2345 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) { 2346 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts(); 2347 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val)) 2348 NewBB = BA->getBasicBlock(); 2349 else 2350 return false; // Cannot determine. 2351 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) { 2352 if (RI->getNumOperands()) 2353 RetVal = getVal(Values, RI->getOperand(0)); 2354 2355 CallStack.pop_back(); // return from fn. 2356 return true; // We succeeded at evaluating this ctor! 2357 } else { 2358 // invoke, unwind, unreachable. 2359 return false; // Cannot handle this terminator. 2360 } 2361 2362 // Okay, we succeeded in evaluating this control flow. See if we have 2363 // executed the new block before. If so, we have a looping function, 2364 // which we cannot evaluate in reasonable time. 2365 if (!ExecutedBlocks.insert(NewBB)) 2366 return false; // looped! 2367 2368 // Okay, we have never been in this block before. Check to see if there 2369 // are any PHI nodes. If so, evaluate them with information about where 2370 // we came from. 2371 BasicBlock *OldBB = CurInst->getParent(); 2372 CurInst = NewBB->begin(); 2373 PHINode *PN; 2374 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst) 2375 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB)); 2376 2377 // Do NOT increment CurInst. We know that the terminator had no value. 2378 continue; 2379 } else { 2380 // Did not know how to evaluate this! 2381 return false; 2382 } 2383 2384 if (!CurInst->use_empty()) 2385 Values[CurInst] = InstResult; 2386 2387 // Advance program counter. 2388 ++CurInst; 2389 } 2390} 2391 2392/// EvaluateStaticConstructor - Evaluate static constructors in the function, if 2393/// we can. Return true if we can, false otherwise. 2394static bool EvaluateStaticConstructor(Function *F) { 2395 /// MutatedMemory - For each store we execute, we update this map. Loads 2396 /// check this to get the most up-to-date value. If evaluation is successful, 2397 /// this state is committed to the process. 2398 DenseMap<Constant*, Constant*> MutatedMemory; 2399 2400 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable 2401 /// to represent its body. This vector is needed so we can delete the 2402 /// temporary globals when we are done. 2403 std::vector<GlobalVariable*> AllocaTmps; 2404 2405 /// CallStack - This is used to detect recursion. In pathological situations 2406 /// we could hit exponential behavior, but at least there is nothing 2407 /// unbounded. 2408 std::vector<Function*> CallStack; 2409 2410 // Call the function. 2411 Constant *RetValDummy; 2412 bool EvalSuccess = EvaluateFunction(F, RetValDummy, 2413 SmallVector<Constant*, 0>(), CallStack, 2414 MutatedMemory, AllocaTmps); 2415 if (EvalSuccess) { 2416 // We succeeded at evaluation: commit the result. 2417 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '" 2418 << F->getName() << "' to " << MutatedMemory.size() 2419 << " stores.\n"); 2420 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(), 2421 E = MutatedMemory.end(); I != E; ++I) 2422 CommitValueTo(I->second, I->first); 2423 } 2424 2425 // At this point, we are done interpreting. If we created any 'alloca' 2426 // temporaries, release them now. 2427 while (!AllocaTmps.empty()) { 2428 GlobalVariable *Tmp = AllocaTmps.back(); 2429 AllocaTmps.pop_back(); 2430 2431 // If there are still users of the alloca, the program is doing something 2432 // silly, e.g. storing the address of the alloca somewhere and using it 2433 // later. Since this is undefined, we'll just make it be null. 2434 if (!Tmp->use_empty()) 2435 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType())); 2436 delete Tmp; 2437 } 2438 2439 return EvalSuccess; 2440} 2441 2442 2443 2444/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible. 2445/// Return true if anything changed. 2446bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) { 2447 std::vector<Function*> Ctors = ParseGlobalCtors(GCL); 2448 bool MadeChange = false; 2449 if (Ctors.empty()) return false; 2450 2451 // Loop over global ctors, optimizing them when we can. 2452 for (unsigned i = 0; i != Ctors.size(); ++i) { 2453 Function *F = Ctors[i]; 2454 // Found a null terminator in the middle of the list, prune off the rest of 2455 // the list. 2456 if (F == 0) { 2457 if (i != Ctors.size()-1) { 2458 Ctors.resize(i+1); 2459 MadeChange = true; 2460 } 2461 break; 2462 } 2463 2464 // We cannot simplify external ctor functions. 2465 if (F->empty()) continue; 2466 2467 // If we can evaluate the ctor at compile time, do. 2468 if (EvaluateStaticConstructor(F)) { 2469 Ctors.erase(Ctors.begin()+i); 2470 MadeChange = true; 2471 --i; 2472 ++NumCtorsEvaluated; 2473 continue; 2474 } 2475 } 2476 2477 if (!MadeChange) return false; 2478 2479 GCL = InstallGlobalCtors(GCL, Ctors); 2480 return true; 2481} 2482 2483bool GlobalOpt::OptimizeGlobalAliases(Module &M) { 2484 bool Changed = false; 2485 2486 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); 2487 I != E;) { 2488 Module::alias_iterator J = I++; 2489 // Aliases without names cannot be referenced outside this module. 2490 if (!J->hasName() && !J->isDeclaration()) 2491 J->setLinkage(GlobalValue::InternalLinkage); 2492 // If the aliasee may change at link time, nothing can be done - bail out. 2493 if (J->mayBeOverridden()) 2494 continue; 2495 2496 Constant *Aliasee = J->getAliasee(); 2497 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts()); 2498 Target->removeDeadConstantUsers(); 2499 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse(); 2500 2501 // Make all users of the alias use the aliasee instead. 2502 if (!J->use_empty()) { 2503 J->replaceAllUsesWith(Aliasee); 2504 ++NumAliasesResolved; 2505 Changed = true; 2506 } 2507 2508 // If the alias is externally visible, we may still be able to simplify it. 2509 if (!J->hasLocalLinkage()) { 2510 // If the aliasee has internal linkage, give it the name and linkage 2511 // of the alias, and delete the alias. This turns: 2512 // define internal ... @f(...) 2513 // @a = alias ... @f 2514 // into: 2515 // define ... @a(...) 2516 if (!Target->hasLocalLinkage()) 2517 continue; 2518 2519 // Do not perform the transform if multiple aliases potentially target the 2520 // aliasee. This check also ensures that it is safe to replace the section 2521 // and other attributes of the aliasee with those of the alias. 2522 if (!hasOneUse) 2523 continue; 2524 2525 // Give the aliasee the name, linkage and other attributes of the alias. 2526 Target->takeName(J); 2527 Target->setLinkage(J->getLinkage()); 2528 Target->GlobalValue::copyAttributesFrom(J); 2529 } 2530 2531 // Delete the alias. 2532 M.getAliasList().erase(J); 2533 ++NumAliasesRemoved; 2534 Changed = true; 2535 } 2536 2537 return Changed; 2538} 2539 2540bool GlobalOpt::runOnModule(Module &M) { 2541 bool Changed = false; 2542 2543 // Try to find the llvm.globalctors list. 2544 GlobalVariable *GlobalCtors = FindGlobalCtors(M); 2545 2546 bool LocalChange = true; 2547 while (LocalChange) { 2548 LocalChange = false; 2549 2550 // Delete functions that are trivially dead, ccc -> fastcc 2551 LocalChange |= OptimizeFunctions(M); 2552 2553 // Optimize global_ctors list. 2554 if (GlobalCtors) 2555 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors); 2556 2557 // Optimize non-address-taken globals. 2558 LocalChange |= OptimizeGlobalVars(M); 2559 2560 // Resolve aliases, when possible. 2561 LocalChange |= OptimizeGlobalAliases(M); 2562 Changed |= LocalChange; 2563 } 2564 2565 // TODO: Move all global ctors functions to the end of the module for code 2566 // layout. 2567 2568 return Changed; 2569} 2570