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