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