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