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