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/SetVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/ADT/iterator_range.h" 24 #include "llvm/Analysis/BlockFrequencyInfo.h" 25 #include "llvm/Analysis/ConstantFolding.h" 26 #include "llvm/Analysis/MemoryBuiltins.h" 27 #include "llvm/Analysis/TargetLibraryInfo.h" 28 #include "llvm/Analysis/TargetTransformInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/BinaryFormat/Dwarf.h" 31 #include "llvm/IR/Attributes.h" 32 #include "llvm/IR/BasicBlock.h" 33 #include "llvm/IR/CallingConv.h" 34 #include "llvm/IR/Constant.h" 35 #include "llvm/IR/Constants.h" 36 #include "llvm/IR/DataLayout.h" 37 #include "llvm/IR/DebugInfoMetadata.h" 38 #include "llvm/IR/DerivedTypes.h" 39 #include "llvm/IR/Dominators.h" 40 #include "llvm/IR/Function.h" 41 #include "llvm/IR/GlobalAlias.h" 42 #include "llvm/IR/GlobalValue.h" 43 #include "llvm/IR/GlobalVariable.h" 44 #include "llvm/IR/IRBuilder.h" 45 #include "llvm/IR/InstrTypes.h" 46 #include "llvm/IR/Instruction.h" 47 #include "llvm/IR/Instructions.h" 48 #include "llvm/IR/IntrinsicInst.h" 49 #include "llvm/IR/Module.h" 50 #include "llvm/IR/Operator.h" 51 #include "llvm/IR/Type.h" 52 #include "llvm/IR/Use.h" 53 #include "llvm/IR/User.h" 54 #include "llvm/IR/Value.h" 55 #include "llvm/IR/ValueHandle.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/raw_ostream.h" 62 #include "llvm/Transforms/IPO.h" 63 #include "llvm/Transforms/Utils/CtorUtils.h" 64 #include "llvm/Transforms/Utils/Evaluator.h" 65 #include "llvm/Transforms/Utils/GlobalStatus.h" 66 #include "llvm/Transforms/Utils/Local.h" 67 #include <cassert> 68 #include <cstdint> 69 #include <optional> 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(NumSubstitute,"Number of globals with initializers stored into them"); 81 STATISTIC(NumDeleted , "Number of globals deleted"); 82 STATISTIC(NumGlobUses , "Number of global uses devirtualized"); 83 STATISTIC(NumLocalized , "Number of globals localized"); 84 STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans"); 85 STATISTIC(NumFastCallFns , "Number of functions converted to fastcc"); 86 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated"); 87 STATISTIC(NumNestRemoved , "Number of nest attributes removed"); 88 STATISTIC(NumAliasesResolved, "Number of global aliases resolved"); 89 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated"); 90 STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed"); 91 STATISTIC(NumInternalFunc, "Number of internal functions"); 92 STATISTIC(NumColdCC, "Number of functions marked coldcc"); 93 94 static cl::opt<bool> 95 EnableColdCCStressTest("enable-coldcc-stress-test", 96 cl::desc("Enable stress test of coldcc by adding " 97 "calling conv to all internal functions."), 98 cl::init(false), cl::Hidden); 99 100 static cl::opt<int> ColdCCRelFreq( 101 "coldcc-rel-freq", cl::Hidden, cl::init(2), 102 cl::desc( 103 "Maximum block frequency, expressed as a percentage of caller's " 104 "entry frequency, for a call site to be considered cold for enabling" 105 "coldcc")); 106 107 /// Is this global variable possibly used by a leak checker as a root? If so, 108 /// we might not really want to eliminate the stores to it. 109 static bool isLeakCheckerRoot(GlobalVariable *GV) { 110 // A global variable is a root if it is a pointer, or could plausibly contain 111 // a pointer. There are two challenges; one is that we could have a struct 112 // the has an inner member which is a pointer. We recurse through the type to 113 // detect these (up to a point). The other is that we may actually be a union 114 // of a pointer and another type, and so our LLVM type is an integer which 115 // gets converted into a pointer, or our type is an [i8 x #] with a pointer 116 // potentially contained here. 117 118 if (GV->hasPrivateLinkage()) 119 return false; 120 121 SmallVector<Type *, 4> Types; 122 Types.push_back(GV->getValueType()); 123 124 unsigned Limit = 20; 125 do { 126 Type *Ty = Types.pop_back_val(); 127 switch (Ty->getTypeID()) { 128 default: break; 129 case Type::PointerTyID: 130 return true; 131 case Type::FixedVectorTyID: 132 case Type::ScalableVectorTyID: 133 if (cast<VectorType>(Ty)->getElementType()->isPointerTy()) 134 return true; 135 break; 136 case Type::ArrayTyID: 137 Types.push_back(cast<ArrayType>(Ty)->getElementType()); 138 break; 139 case Type::StructTyID: { 140 StructType *STy = cast<StructType>(Ty); 141 if (STy->isOpaque()) return true; 142 for (Type *InnerTy : STy->elements()) { 143 if (isa<PointerType>(InnerTy)) return true; 144 if (isa<StructType>(InnerTy) || isa<ArrayType>(InnerTy) || 145 isa<VectorType>(InnerTy)) 146 Types.push_back(InnerTy); 147 } 148 break; 149 } 150 } 151 if (--Limit == 0) return true; 152 } while (!Types.empty()); 153 return false; 154 } 155 156 /// Given a value that is stored to a global but never read, determine whether 157 /// it's safe to remove the store and the chain of computation that feeds the 158 /// store. 159 static bool IsSafeComputationToRemove( 160 Value *V, function_ref<TargetLibraryInfo &(Function &)> GetTLI) { 161 do { 162 if (isa<Constant>(V)) 163 return true; 164 if (!V->hasOneUse()) 165 return false; 166 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) || 167 isa<GlobalValue>(V)) 168 return false; 169 if (isAllocationFn(V, GetTLI)) 170 return true; 171 172 Instruction *I = cast<Instruction>(V); 173 if (I->mayHaveSideEffects()) 174 return false; 175 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) { 176 if (!GEP->hasAllConstantIndices()) 177 return false; 178 } else if (I->getNumOperands() != 1) { 179 return false; 180 } 181 182 V = I->getOperand(0); 183 } while (true); 184 } 185 186 /// This GV is a pointer root. Loop over all users of the global and clean up 187 /// any that obviously don't assign the global a value that isn't dynamically 188 /// allocated. 189 static bool 190 CleanupPointerRootUsers(GlobalVariable *GV, 191 function_ref<TargetLibraryInfo &(Function &)> GetTLI) { 192 // A brief explanation of leak checkers. The goal is to find bugs where 193 // pointers are forgotten, causing an accumulating growth in memory 194 // usage over time. The common strategy for leak checkers is to explicitly 195 // allow the memory pointed to by globals at exit. This is popular because it 196 // also solves another problem where the main thread of a C++ program may shut 197 // down before other threads that are still expecting to use those globals. To 198 // handle that case, we expect the program may create a singleton and never 199 // destroy it. 200 201 bool Changed = false; 202 203 // If Dead[n].first is the only use of a malloc result, we can delete its 204 // chain of computation and the store to the global in Dead[n].second. 205 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead; 206 207 SmallVector<User *> Worklist(GV->users()); 208 // Constants can't be pointers to dynamically allocated memory. 209 while (!Worklist.empty()) { 210 User *U = Worklist.pop_back_val(); 211 if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 212 Value *V = SI->getValueOperand(); 213 if (isa<Constant>(V)) { 214 Changed = true; 215 SI->eraseFromParent(); 216 } else if (Instruction *I = dyn_cast<Instruction>(V)) { 217 if (I->hasOneUse()) 218 Dead.push_back(std::make_pair(I, SI)); 219 } 220 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) { 221 if (isa<Constant>(MSI->getValue())) { 222 Changed = true; 223 MSI->eraseFromParent(); 224 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) { 225 if (I->hasOneUse()) 226 Dead.push_back(std::make_pair(I, MSI)); 227 } 228 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) { 229 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource()); 230 if (MemSrc && MemSrc->isConstant()) { 231 Changed = true; 232 MTI->eraseFromParent(); 233 } else if (Instruction *I = dyn_cast<Instruction>(MTI->getSource())) { 234 if (I->hasOneUse()) 235 Dead.push_back(std::make_pair(I, MTI)); 236 } 237 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) { 238 if (isa<GEPOperator>(CE)) 239 append_range(Worklist, CE->users()); 240 } 241 } 242 243 for (int i = 0, e = Dead.size(); i != e; ++i) { 244 if (IsSafeComputationToRemove(Dead[i].first, GetTLI)) { 245 Dead[i].second->eraseFromParent(); 246 Instruction *I = Dead[i].first; 247 do { 248 if (isAllocationFn(I, GetTLI)) 249 break; 250 Instruction *J = dyn_cast<Instruction>(I->getOperand(0)); 251 if (!J) 252 break; 253 I->eraseFromParent(); 254 I = J; 255 } while (true); 256 I->eraseFromParent(); 257 Changed = true; 258 } 259 } 260 261 GV->removeDeadConstantUsers(); 262 return Changed; 263 } 264 265 /// We just marked GV constant. Loop over all users of the global, cleaning up 266 /// the obvious ones. This is largely just a quick scan over the use list to 267 /// clean up the easy and obvious cruft. This returns true if it made a change. 268 static bool CleanupConstantGlobalUsers(GlobalVariable *GV, 269 const DataLayout &DL) { 270 Constant *Init = GV->getInitializer(); 271 SmallVector<User *, 8> WorkList(GV->users()); 272 SmallPtrSet<User *, 8> Visited; 273 bool Changed = false; 274 275 SmallVector<WeakTrackingVH> MaybeDeadInsts; 276 auto EraseFromParent = [&](Instruction *I) { 277 for (Value *Op : I->operands()) 278 if (auto *OpI = dyn_cast<Instruction>(Op)) 279 MaybeDeadInsts.push_back(OpI); 280 I->eraseFromParent(); 281 Changed = true; 282 }; 283 while (!WorkList.empty()) { 284 User *U = WorkList.pop_back_val(); 285 if (!Visited.insert(U).second) 286 continue; 287 288 if (auto *BO = dyn_cast<BitCastOperator>(U)) 289 append_range(WorkList, BO->users()); 290 if (auto *ASC = dyn_cast<AddrSpaceCastOperator>(U)) 291 append_range(WorkList, ASC->users()); 292 else if (auto *GEP = dyn_cast<GEPOperator>(U)) 293 append_range(WorkList, GEP->users()); 294 else if (auto *LI = dyn_cast<LoadInst>(U)) { 295 // A load from a uniform value is always the same, regardless of any 296 // applied offset. 297 Type *Ty = LI->getType(); 298 if (Constant *Res = ConstantFoldLoadFromUniformValue(Init, Ty)) { 299 LI->replaceAllUsesWith(Res); 300 EraseFromParent(LI); 301 continue; 302 } 303 304 Value *PtrOp = LI->getPointerOperand(); 305 APInt Offset(DL.getIndexTypeSizeInBits(PtrOp->getType()), 0); 306 PtrOp = PtrOp->stripAndAccumulateConstantOffsets( 307 DL, Offset, /* AllowNonInbounds */ true); 308 if (PtrOp == GV) { 309 if (auto *Value = ConstantFoldLoadFromConst(Init, Ty, Offset, DL)) { 310 LI->replaceAllUsesWith(Value); 311 EraseFromParent(LI); 312 } 313 } 314 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 315 // Store must be unreachable or storing Init into the global. 316 EraseFromParent(SI); 317 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv 318 if (getUnderlyingObject(MI->getRawDest()) == GV) 319 EraseFromParent(MI); 320 } 321 } 322 323 Changed |= 324 RecursivelyDeleteTriviallyDeadInstructionsPermissive(MaybeDeadInsts); 325 GV->removeDeadConstantUsers(); 326 return Changed; 327 } 328 329 /// Part of the global at a specific offset, which is only accessed through 330 /// loads and stores with the given type. 331 struct GlobalPart { 332 Type *Ty; 333 Constant *Initializer = nullptr; 334 bool IsLoaded = false; 335 bool IsStored = false; 336 }; 337 338 /// Look at all uses of the global and determine which (offset, type) pairs it 339 /// can be split into. 340 static bool collectSRATypes(DenseMap<uint64_t, GlobalPart> &Parts, 341 GlobalVariable *GV, const DataLayout &DL) { 342 SmallVector<Use *, 16> Worklist; 343 SmallPtrSet<Use *, 16> Visited; 344 auto AppendUses = [&](Value *V) { 345 for (Use &U : V->uses()) 346 if (Visited.insert(&U).second) 347 Worklist.push_back(&U); 348 }; 349 AppendUses(GV); 350 while (!Worklist.empty()) { 351 Use *U = Worklist.pop_back_val(); 352 User *V = U->getUser(); 353 354 auto *GEP = dyn_cast<GEPOperator>(V); 355 if (isa<BitCastOperator>(V) || isa<AddrSpaceCastOperator>(V) || 356 (GEP && GEP->hasAllConstantIndices())) { 357 AppendUses(V); 358 continue; 359 } 360 361 if (Value *Ptr = getLoadStorePointerOperand(V)) { 362 // This is storing the global address into somewhere, not storing into 363 // the global. 364 if (isa<StoreInst>(V) && U->getOperandNo() == 0) 365 return false; 366 367 APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0); 368 Ptr = Ptr->stripAndAccumulateConstantOffsets(DL, Offset, 369 /* AllowNonInbounds */ true); 370 if (Ptr != GV || Offset.getActiveBits() >= 64) 371 return false; 372 373 // TODO: We currently require that all accesses at a given offset must 374 // use the same type. This could be relaxed. 375 Type *Ty = getLoadStoreType(V); 376 const auto &[It, Inserted] = 377 Parts.try_emplace(Offset.getZExtValue(), GlobalPart{Ty}); 378 if (Ty != It->second.Ty) 379 return false; 380 381 if (Inserted) { 382 It->second.Initializer = 383 ConstantFoldLoadFromConst(GV->getInitializer(), Ty, Offset, DL); 384 if (!It->second.Initializer) { 385 LLVM_DEBUG(dbgs() << "Global SRA: Failed to evaluate initializer of " 386 << *GV << " with type " << *Ty << " at offset " 387 << Offset.getZExtValue()); 388 return false; 389 } 390 } 391 392 // Scalable types not currently supported. 393 if (isa<ScalableVectorType>(Ty)) 394 return false; 395 396 auto IsStored = [](Value *V, Constant *Initializer) { 397 auto *SI = dyn_cast<StoreInst>(V); 398 if (!SI) 399 return false; 400 401 Constant *StoredConst = dyn_cast<Constant>(SI->getOperand(0)); 402 if (!StoredConst) 403 return true; 404 405 // Don't consider stores that only write the initializer value. 406 return Initializer != StoredConst; 407 }; 408 409 It->second.IsLoaded |= isa<LoadInst>(V); 410 It->second.IsStored |= IsStored(V, It->second.Initializer); 411 continue; 412 } 413 414 // Ignore dead constant users. 415 if (auto *C = dyn_cast<Constant>(V)) { 416 if (!isSafeToDestroyConstant(C)) 417 return false; 418 continue; 419 } 420 421 // Unknown user. 422 return false; 423 } 424 425 return true; 426 } 427 428 /// Copy over the debug info for a variable to its SRA replacements. 429 static void transferSRADebugInfo(GlobalVariable *GV, GlobalVariable *NGV, 430 uint64_t FragmentOffsetInBits, 431 uint64_t FragmentSizeInBits, 432 uint64_t VarSize) { 433 SmallVector<DIGlobalVariableExpression *, 1> GVs; 434 GV->getDebugInfo(GVs); 435 for (auto *GVE : GVs) { 436 DIVariable *Var = GVE->getVariable(); 437 DIExpression *Expr = GVE->getExpression(); 438 int64_t CurVarOffsetInBytes = 0; 439 uint64_t CurVarOffsetInBits = 0; 440 uint64_t FragmentEndInBits = FragmentOffsetInBits + FragmentSizeInBits; 441 442 // Calculate the offset (Bytes), Continue if unknown. 443 if (!Expr->extractIfOffset(CurVarOffsetInBytes)) 444 continue; 445 446 // Ignore negative offset. 447 if (CurVarOffsetInBytes < 0) 448 continue; 449 450 // Convert offset to bits. 451 CurVarOffsetInBits = CHAR_BIT * (uint64_t)CurVarOffsetInBytes; 452 453 // Current var starts after the fragment, ignore. 454 if (CurVarOffsetInBits >= FragmentEndInBits) 455 continue; 456 457 uint64_t CurVarSize = Var->getType()->getSizeInBits(); 458 uint64_t CurVarEndInBits = CurVarOffsetInBits + CurVarSize; 459 // Current variable ends before start of fragment, ignore. 460 if (CurVarSize != 0 && /* CurVarSize is known */ 461 CurVarEndInBits <= FragmentOffsetInBits) 462 continue; 463 464 // Current variable fits in (not greater than) the fragment, 465 // does not need fragment expression. 466 if (CurVarSize != 0 && /* CurVarSize is known */ 467 CurVarOffsetInBits >= FragmentOffsetInBits && 468 CurVarEndInBits <= FragmentEndInBits) { 469 uint64_t CurVarOffsetInFragment = 470 (CurVarOffsetInBits - FragmentOffsetInBits) / 8; 471 if (CurVarOffsetInFragment != 0) 472 Expr = DIExpression::get(Expr->getContext(), {dwarf::DW_OP_plus_uconst, 473 CurVarOffsetInFragment}); 474 else 475 Expr = DIExpression::get(Expr->getContext(), {}); 476 auto *NGVE = 477 DIGlobalVariableExpression::get(GVE->getContext(), Var, Expr); 478 NGV->addDebugInfo(NGVE); 479 continue; 480 } 481 // Current variable does not fit in single fragment, 482 // emit a fragment expression. 483 if (FragmentSizeInBits < VarSize) { 484 if (CurVarOffsetInBits > FragmentOffsetInBits) 485 continue; 486 uint64_t CurVarFragmentOffsetInBits = 487 FragmentOffsetInBits - CurVarOffsetInBits; 488 uint64_t CurVarFragmentSizeInBits = FragmentSizeInBits; 489 if (CurVarSize != 0 && CurVarEndInBits < FragmentEndInBits) 490 CurVarFragmentSizeInBits -= (FragmentEndInBits - CurVarEndInBits); 491 if (CurVarOffsetInBits) 492 Expr = DIExpression::get(Expr->getContext(), {}); 493 if (auto E = DIExpression::createFragmentExpression( 494 Expr, CurVarFragmentOffsetInBits, CurVarFragmentSizeInBits)) 495 Expr = *E; 496 else 497 continue; 498 } 499 auto *NGVE = DIGlobalVariableExpression::get(GVE->getContext(), Var, Expr); 500 NGV->addDebugInfo(NGVE); 501 } 502 } 503 504 /// Perform scalar replacement of aggregates on the specified global variable. 505 /// This opens the door for other optimizations by exposing the behavior of the 506 /// program in a more fine-grained way. We have determined that this 507 /// transformation is safe already. We return the first global variable we 508 /// insert so that the caller can reprocess it. 509 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &DL) { 510 assert(GV->hasLocalLinkage()); 511 512 // Collect types to split into. 513 DenseMap<uint64_t, GlobalPart> Parts; 514 if (!collectSRATypes(Parts, GV, DL) || Parts.empty()) 515 return nullptr; 516 517 // Make sure we don't SRA back to the same type. 518 if (Parts.size() == 1 && Parts.begin()->second.Ty == GV->getValueType()) 519 return nullptr; 520 521 // Don't perform SRA if we would have to split into many globals. Ignore 522 // parts that are either only loaded or only stored, because we expect them 523 // to be optimized away. 524 unsigned NumParts = count_if(Parts, [](const auto &Pair) { 525 return Pair.second.IsLoaded && Pair.second.IsStored; 526 }); 527 if (NumParts > 16) 528 return nullptr; 529 530 // Sort by offset. 531 SmallVector<std::tuple<uint64_t, Type *, Constant *>, 16> TypesVector; 532 for (const auto &Pair : Parts) { 533 TypesVector.push_back( 534 {Pair.first, Pair.second.Ty, Pair.second.Initializer}); 535 } 536 sort(TypesVector, llvm::less_first()); 537 538 // Check that the types are non-overlapping. 539 uint64_t Offset = 0; 540 for (const auto &[OffsetForTy, Ty, _] : TypesVector) { 541 // Overlaps with previous type. 542 if (OffsetForTy < Offset) 543 return nullptr; 544 545 Offset = OffsetForTy + DL.getTypeAllocSize(Ty); 546 } 547 548 // Some accesses go beyond the end of the global, don't bother. 549 if (Offset > DL.getTypeAllocSize(GV->getValueType())) 550 return nullptr; 551 552 LLVM_DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV << "\n"); 553 554 // Get the alignment of the global, either explicit or target-specific. 555 Align StartAlignment = 556 DL.getValueOrABITypeAlignment(GV->getAlign(), GV->getValueType()); 557 uint64_t VarSize = DL.getTypeSizeInBits(GV->getValueType()); 558 559 // Create replacement globals. 560 DenseMap<uint64_t, GlobalVariable *> NewGlobals; 561 unsigned NameSuffix = 0; 562 for (auto &[OffsetForTy, Ty, Initializer] : TypesVector) { 563 GlobalVariable *NGV = new GlobalVariable( 564 *GV->getParent(), Ty, false, GlobalVariable::InternalLinkage, 565 Initializer, GV->getName() + "." + Twine(NameSuffix++), GV, 566 GV->getThreadLocalMode(), GV->getAddressSpace()); 567 NGV->copyAttributesFrom(GV); 568 NewGlobals.insert({OffsetForTy, NGV}); 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 = commonAlignment(StartAlignment, OffsetForTy); 574 if (NewAlign > DL.getABITypeAlign(Ty)) 575 NGV->setAlignment(NewAlign); 576 577 // Copy over the debug info for the variable. 578 transferSRADebugInfo(GV, NGV, OffsetForTy * 8, 579 DL.getTypeAllocSizeInBits(Ty), VarSize); 580 } 581 582 // Replace uses of the original global with uses of the new global. 583 SmallVector<Value *, 16> Worklist; 584 SmallPtrSet<Value *, 16> Visited; 585 SmallVector<WeakTrackingVH, 16> DeadInsts; 586 auto AppendUsers = [&](Value *V) { 587 for (User *U : V->users()) 588 if (Visited.insert(U).second) 589 Worklist.push_back(U); 590 }; 591 AppendUsers(GV); 592 while (!Worklist.empty()) { 593 Value *V = Worklist.pop_back_val(); 594 if (isa<BitCastOperator>(V) || isa<AddrSpaceCastOperator>(V) || 595 isa<GEPOperator>(V)) { 596 AppendUsers(V); 597 if (isa<Instruction>(V)) 598 DeadInsts.push_back(V); 599 continue; 600 } 601 602 if (Value *Ptr = getLoadStorePointerOperand(V)) { 603 APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0); 604 Ptr = Ptr->stripAndAccumulateConstantOffsets(DL, Offset, 605 /* AllowNonInbounds */ true); 606 assert(Ptr == GV && "Load/store must be from/to global"); 607 GlobalVariable *NGV = NewGlobals[Offset.getZExtValue()]; 608 assert(NGV && "Must have replacement global for this offset"); 609 610 // Update the pointer operand and recalculate alignment. 611 Align PrefAlign = DL.getPrefTypeAlign(getLoadStoreType(V)); 612 Align NewAlign = 613 getOrEnforceKnownAlignment(NGV, PrefAlign, DL, cast<Instruction>(V)); 614 615 if (auto *LI = dyn_cast<LoadInst>(V)) { 616 LI->setOperand(0, NGV); 617 LI->setAlignment(NewAlign); 618 } else { 619 auto *SI = cast<StoreInst>(V); 620 SI->setOperand(1, NGV); 621 SI->setAlignment(NewAlign); 622 } 623 continue; 624 } 625 626 assert(isa<Constant>(V) && isSafeToDestroyConstant(cast<Constant>(V)) && 627 "Other users can only be dead constants"); 628 } 629 630 // Delete old instructions and global. 631 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts); 632 GV->removeDeadConstantUsers(); 633 GV->eraseFromParent(); 634 ++NumSRA; 635 636 assert(NewGlobals.size() > 0); 637 return NewGlobals.begin()->second; 638 } 639 640 /// Return true if all users of the specified value will trap if the value is 641 /// dynamically null. PHIs keeps track of any phi nodes we've seen to avoid 642 /// reprocessing them. 643 static bool AllUsesOfValueWillTrapIfNull(const Value *V, 644 SmallPtrSetImpl<const PHINode*> &PHIs) { 645 for (const User *U : V->users()) { 646 if (const Instruction *I = dyn_cast<Instruction>(U)) { 647 // If null pointer is considered valid, then all uses are non-trapping. 648 // Non address-space 0 globals have already been pruned by the caller. 649 if (NullPointerIsDefined(I->getFunction())) 650 return false; 651 } 652 if (isa<LoadInst>(U)) { 653 // Will trap. 654 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) { 655 if (SI->getOperand(0) == V) { 656 return false; // Storing the value. 657 } 658 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) { 659 if (CI->getCalledOperand() != V) { 660 return false; // Not calling the ptr 661 } 662 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) { 663 if (II->getCalledOperand() != V) { 664 return false; // Not calling the ptr 665 } 666 } else if (const AddrSpaceCastInst *CI = dyn_cast<AddrSpaceCastInst>(U)) { 667 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) 668 return false; 669 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) { 670 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false; 671 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) { 672 // If we've already seen this phi node, ignore it, it has already been 673 // checked. 674 if (PHIs.insert(PN).second && !AllUsesOfValueWillTrapIfNull(PN, PHIs)) 675 return false; 676 } else if (isa<ICmpInst>(U) && 677 !ICmpInst::isSigned(cast<ICmpInst>(U)->getPredicate()) && 678 isa<LoadInst>(U->getOperand(0)) && 679 isa<ConstantPointerNull>(U->getOperand(1))) { 680 assert(isa<GlobalValue>(cast<LoadInst>(U->getOperand(0)) 681 ->getPointerOperand() 682 ->stripPointerCasts()) && 683 "Should be GlobalVariable"); 684 // This and only this kind of non-signed ICmpInst is to be replaced with 685 // the comparing of the value of the created global init bool later in 686 // optimizeGlobalAddressOfAllocation for the global variable. 687 } else { 688 return false; 689 } 690 } 691 return true; 692 } 693 694 /// Return true if all uses of any loads from GV will trap if the loaded value 695 /// is null. Note that this also permits comparisons of the loaded value 696 /// against null, as a special case. 697 static bool allUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) { 698 SmallVector<const Value *, 4> Worklist; 699 Worklist.push_back(GV); 700 while (!Worklist.empty()) { 701 const Value *P = Worklist.pop_back_val(); 702 for (const auto *U : P->users()) { 703 if (auto *LI = dyn_cast<LoadInst>(U)) { 704 SmallPtrSet<const PHINode *, 8> PHIs; 705 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs)) 706 return false; 707 } else if (auto *SI = dyn_cast<StoreInst>(U)) { 708 // Ignore stores to the global. 709 if (SI->getPointerOperand() != P) 710 return false; 711 } else if (auto *CE = dyn_cast<ConstantExpr>(U)) { 712 if (CE->stripPointerCasts() != GV) 713 return false; 714 // Check further the ConstantExpr. 715 Worklist.push_back(CE); 716 } else { 717 // We don't know or understand this user, bail out. 718 return false; 719 } 720 } 721 } 722 723 return true; 724 } 725 726 /// Get all the loads/store uses for global variable \p GV. 727 static void allUsesOfLoadAndStores(GlobalVariable *GV, 728 SmallVector<Value *, 4> &Uses) { 729 SmallVector<Value *, 4> Worklist; 730 Worklist.push_back(GV); 731 while (!Worklist.empty()) { 732 auto *P = Worklist.pop_back_val(); 733 for (auto *U : P->users()) { 734 if (auto *CE = dyn_cast<ConstantExpr>(U)) { 735 Worklist.push_back(CE); 736 continue; 737 } 738 739 assert((isa<LoadInst>(U) || isa<StoreInst>(U)) && 740 "Expect only load or store instructions"); 741 Uses.push_back(U); 742 } 743 } 744 } 745 746 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) { 747 bool Changed = false; 748 for (auto UI = V->user_begin(), E = V->user_end(); UI != E; ) { 749 Instruction *I = cast<Instruction>(*UI++); 750 // Uses are non-trapping if null pointer is considered valid. 751 // Non address-space 0 globals are already pruned by the caller. 752 if (NullPointerIsDefined(I->getFunction())) 753 return false; 754 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 755 LI->setOperand(0, NewV); 756 Changed = true; 757 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 758 if (SI->getOperand(1) == V) { 759 SI->setOperand(1, NewV); 760 Changed = true; 761 } 762 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) { 763 CallBase *CB = cast<CallBase>(I); 764 if (CB->getCalledOperand() == V) { 765 // Calling through the pointer! Turn into a direct call, but be careful 766 // that the pointer is not also being passed as an argument. 767 CB->setCalledOperand(NewV); 768 Changed = true; 769 bool PassedAsArg = false; 770 for (unsigned i = 0, e = CB->arg_size(); i != e; ++i) 771 if (CB->getArgOperand(i) == V) { 772 PassedAsArg = true; 773 CB->setArgOperand(i, NewV); 774 } 775 776 if (PassedAsArg) { 777 // Being passed as an argument also. Be careful to not invalidate UI! 778 UI = V->user_begin(); 779 } 780 } 781 } else if (AddrSpaceCastInst *CI = dyn_cast<AddrSpaceCastInst>(I)) { 782 Changed |= OptimizeAwayTrappingUsesOfValue( 783 CI, ConstantExpr::getAddrSpaceCast(NewV, CI->getType())); 784 if (CI->use_empty()) { 785 Changed = true; 786 CI->eraseFromParent(); 787 } 788 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { 789 // Should handle GEP here. 790 SmallVector<Constant*, 8> Idxs; 791 Idxs.reserve(GEPI->getNumOperands()-1); 792 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end(); 793 i != e; ++i) 794 if (Constant *C = dyn_cast<Constant>(*i)) 795 Idxs.push_back(C); 796 else 797 break; 798 if (Idxs.size() == GEPI->getNumOperands()-1) 799 Changed |= OptimizeAwayTrappingUsesOfValue( 800 GEPI, ConstantExpr::getGetElementPtr(GEPI->getSourceElementType(), 801 NewV, Idxs)); 802 if (GEPI->use_empty()) { 803 Changed = true; 804 GEPI->eraseFromParent(); 805 } 806 } 807 } 808 809 return Changed; 810 } 811 812 /// The specified global has only one non-null value stored into it. If there 813 /// are uses of the loaded value that would trap if the loaded value is 814 /// dynamically null, then we know that they cannot be reachable with a null 815 /// optimize away the load. 816 static bool OptimizeAwayTrappingUsesOfLoads( 817 GlobalVariable *GV, Constant *LV, const DataLayout &DL, 818 function_ref<TargetLibraryInfo &(Function &)> GetTLI) { 819 bool Changed = false; 820 821 // Keep track of whether we are able to remove all the uses of the global 822 // other than the store that defines it. 823 bool AllNonStoreUsesGone = true; 824 825 // Replace all uses of loads with uses of uses of the stored value. 826 for (User *GlobalUser : llvm::make_early_inc_range(GV->users())) { 827 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) { 828 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV); 829 // If we were able to delete all uses of the loads 830 if (LI->use_empty()) { 831 LI->eraseFromParent(); 832 Changed = true; 833 } else { 834 AllNonStoreUsesGone = false; 835 } 836 } else if (isa<StoreInst>(GlobalUser)) { 837 // Ignore the store that stores "LV" to the global. 838 assert(GlobalUser->getOperand(1) == GV && 839 "Must be storing *to* the global"); 840 } else { 841 AllNonStoreUsesGone = false; 842 843 // If we get here we could have other crazy uses that are transitively 844 // loaded. 845 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) || 846 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) || 847 isa<BitCastInst>(GlobalUser) || 848 isa<GetElementPtrInst>(GlobalUser) || 849 isa<AddrSpaceCastInst>(GlobalUser)) && 850 "Only expect load and stores!"); 851 } 852 } 853 854 if (Changed) { 855 LLVM_DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV 856 << "\n"); 857 ++NumGlobUses; 858 } 859 860 // If we nuked all of the loads, then none of the stores are needed either, 861 // nor is the global. 862 if (AllNonStoreUsesGone) { 863 if (isLeakCheckerRoot(GV)) { 864 Changed |= CleanupPointerRootUsers(GV, GetTLI); 865 } else { 866 Changed = true; 867 CleanupConstantGlobalUsers(GV, DL); 868 } 869 if (GV->use_empty()) { 870 LLVM_DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n"); 871 Changed = true; 872 GV->eraseFromParent(); 873 ++NumDeleted; 874 } 875 } 876 return Changed; 877 } 878 879 /// Walk the use list of V, constant folding all of the instructions that are 880 /// foldable. 881 static void ConstantPropUsersOf(Value *V, const DataLayout &DL, 882 TargetLibraryInfo *TLI) { 883 for (Value::user_iterator UI = V->user_begin(), E = V->user_end(); UI != E; ) 884 if (Instruction *I = dyn_cast<Instruction>(*UI++)) 885 if (Constant *NewC = ConstantFoldInstruction(I, DL, TLI)) { 886 I->replaceAllUsesWith(NewC); 887 888 // Advance UI to the next non-I use to avoid invalidating it! 889 // Instructions could multiply use V. 890 while (UI != E && *UI == I) 891 ++UI; 892 if (isInstructionTriviallyDead(I, TLI)) 893 I->eraseFromParent(); 894 } 895 } 896 897 /// This function takes the specified global variable, and transforms the 898 /// program as if it always contained the result of the specified malloc. 899 /// Because it is always the result of the specified malloc, there is no reason 900 /// to actually DO the malloc. Instead, turn the malloc into a global, and any 901 /// loads of GV as uses of the new global. 902 static GlobalVariable * 903 OptimizeGlobalAddressOfAllocation(GlobalVariable *GV, CallInst *CI, 904 uint64_t AllocSize, Constant *InitVal, 905 const DataLayout &DL, 906 TargetLibraryInfo *TLI) { 907 LLVM_DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI 908 << '\n'); 909 910 // Create global of type [AllocSize x i8]. 911 Type *GlobalType = ArrayType::get(Type::getInt8Ty(GV->getContext()), 912 AllocSize); 913 914 // Create the new global variable. The contents of the allocated memory is 915 // undefined initially, so initialize with an undef value. 916 GlobalVariable *NewGV = new GlobalVariable( 917 *GV->getParent(), GlobalType, false, GlobalValue::InternalLinkage, 918 UndefValue::get(GlobalType), GV->getName() + ".body", nullptr, 919 GV->getThreadLocalMode()); 920 921 // Initialize the global at the point of the original call. Note that this 922 // is a different point from the initialization referred to below for the 923 // nullability handling. Sublety: We have not proven the original global was 924 // only initialized once. As such, we can not fold this into the initializer 925 // of the new global as may need to re-init the storage multiple times. 926 if (!isa<UndefValue>(InitVal)) { 927 IRBuilder<> Builder(CI->getNextNode()); 928 // TODO: Use alignment above if align!=1 929 Builder.CreateMemSet(NewGV, InitVal, AllocSize, std::nullopt); 930 } 931 932 // Update users of the allocation to use the new global instead. 933 BitCastInst *TheBC = nullptr; 934 while (!CI->use_empty()) { 935 Instruction *User = cast<Instruction>(CI->user_back()); 936 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) { 937 if (BCI->getType() == NewGV->getType()) { 938 BCI->replaceAllUsesWith(NewGV); 939 BCI->eraseFromParent(); 940 } else { 941 BCI->setOperand(0, NewGV); 942 } 943 } else { 944 if (!TheBC) 945 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI); 946 User->replaceUsesOfWith(CI, TheBC); 947 } 948 } 949 950 SmallSetVector<Constant *, 1> RepValues; 951 RepValues.insert(NewGV); 952 953 // If there is a comparison against null, we will insert a global bool to 954 // keep track of whether the global was initialized yet or not. 955 GlobalVariable *InitBool = 956 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false, 957 GlobalValue::InternalLinkage, 958 ConstantInt::getFalse(GV->getContext()), 959 GV->getName()+".init", GV->getThreadLocalMode()); 960 bool InitBoolUsed = false; 961 962 // Loop over all instruction uses of GV, processing them in turn. 963 SmallVector<Value *, 4> Guses; 964 allUsesOfLoadAndStores(GV, Guses); 965 for (auto *U : Guses) { 966 if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 967 // The global is initialized when the store to it occurs. If the stored 968 // value is null value, the global bool is set to false, otherwise true. 969 new StoreInst(ConstantInt::getBool( 970 GV->getContext(), 971 !isa<ConstantPointerNull>(SI->getValueOperand())), 972 InitBool, false, Align(1), SI->getOrdering(), 973 SI->getSyncScopeID(), SI); 974 SI->eraseFromParent(); 975 continue; 976 } 977 978 LoadInst *LI = cast<LoadInst>(U); 979 while (!LI->use_empty()) { 980 Use &LoadUse = *LI->use_begin(); 981 ICmpInst *ICI = dyn_cast<ICmpInst>(LoadUse.getUser()); 982 if (!ICI) { 983 auto *CE = ConstantExpr::getBitCast(NewGV, LI->getType()); 984 RepValues.insert(CE); 985 LoadUse.set(CE); 986 continue; 987 } 988 989 // Replace the cmp X, 0 with a use of the bool value. 990 Value *LV = new LoadInst(InitBool->getValueType(), InitBool, 991 InitBool->getName() + ".val", false, Align(1), 992 LI->getOrdering(), LI->getSyncScopeID(), LI); 993 InitBoolUsed = true; 994 switch (ICI->getPredicate()) { 995 default: llvm_unreachable("Unknown ICmp Predicate!"); 996 case ICmpInst::ICMP_ULT: // X < null -> always false 997 LV = ConstantInt::getFalse(GV->getContext()); 998 break; 999 case ICmpInst::ICMP_UGE: // X >= null -> always true 1000 LV = ConstantInt::getTrue(GV->getContext()); 1001 break; 1002 case ICmpInst::ICMP_ULE: 1003 case ICmpInst::ICMP_EQ: 1004 LV = BinaryOperator::CreateNot(LV, "notinit", ICI); 1005 break; 1006 case ICmpInst::ICMP_NE: 1007 case ICmpInst::ICMP_UGT: 1008 break; // no change. 1009 } 1010 ICI->replaceAllUsesWith(LV); 1011 ICI->eraseFromParent(); 1012 } 1013 LI->eraseFromParent(); 1014 } 1015 1016 // If the initialization boolean was used, insert it, otherwise delete it. 1017 if (!InitBoolUsed) { 1018 while (!InitBool->use_empty()) // Delete initializations 1019 cast<StoreInst>(InitBool->user_back())->eraseFromParent(); 1020 delete InitBool; 1021 } else 1022 GV->getParent()->insertGlobalVariable(GV->getIterator(), InitBool); 1023 1024 // Now the GV is dead, nuke it and the allocation.. 1025 GV->eraseFromParent(); 1026 CI->eraseFromParent(); 1027 1028 // To further other optimizations, loop over all users of NewGV and try to 1029 // constant prop them. This will promote GEP instructions with constant 1030 // indices into GEP constant-exprs, which will allow global-opt to hack on it. 1031 for (auto *CE : RepValues) 1032 ConstantPropUsersOf(CE, DL, TLI); 1033 1034 return NewGV; 1035 } 1036 1037 /// Scan the use-list of GV checking to make sure that there are no complex uses 1038 /// of GV. We permit simple things like dereferencing the pointer, but not 1039 /// storing through the address, unless it is to the specified global. 1040 static bool 1041 valueIsOnlyUsedLocallyOrStoredToOneGlobal(const CallInst *CI, 1042 const GlobalVariable *GV) { 1043 SmallPtrSet<const Value *, 4> Visited; 1044 SmallVector<const Value *, 4> Worklist; 1045 Worklist.push_back(CI); 1046 1047 while (!Worklist.empty()) { 1048 const Value *V = Worklist.pop_back_val(); 1049 if (!Visited.insert(V).second) 1050 continue; 1051 1052 for (const Use &VUse : V->uses()) { 1053 const User *U = VUse.getUser(); 1054 if (isa<LoadInst>(U) || isa<CmpInst>(U)) 1055 continue; // Fine, ignore. 1056 1057 if (auto *SI = dyn_cast<StoreInst>(U)) { 1058 if (SI->getValueOperand() == V && 1059 SI->getPointerOperand()->stripPointerCasts() != GV) 1060 return false; // Storing the pointer not into GV... bad. 1061 continue; // Otherwise, storing through it, or storing into GV... fine. 1062 } 1063 1064 if (auto *BCI = dyn_cast<BitCastInst>(U)) { 1065 Worklist.push_back(BCI); 1066 continue; 1067 } 1068 1069 if (auto *GEPI = dyn_cast<GetElementPtrInst>(U)) { 1070 Worklist.push_back(GEPI); 1071 continue; 1072 } 1073 1074 return false; 1075 } 1076 } 1077 1078 return true; 1079 } 1080 1081 /// If we have a global that is only initialized with a fixed size allocation 1082 /// try to transform the program to use global memory instead of heap 1083 /// allocated memory. This eliminates dynamic allocation, avoids an indirection 1084 /// accessing the data, and exposes the resultant global to further GlobalOpt. 1085 static bool tryToOptimizeStoreOfAllocationToGlobal(GlobalVariable *GV, 1086 CallInst *CI, 1087 const DataLayout &DL, 1088 TargetLibraryInfo *TLI) { 1089 if (!isRemovableAlloc(CI, TLI)) 1090 // Must be able to remove the call when we get done.. 1091 return false; 1092 1093 Type *Int8Ty = Type::getInt8Ty(CI->getFunction()->getContext()); 1094 Constant *InitVal = getInitialValueOfAllocation(CI, TLI, Int8Ty); 1095 if (!InitVal) 1096 // Must be able to emit a memset for initialization 1097 return false; 1098 1099 uint64_t AllocSize; 1100 if (!getObjectSize(CI, AllocSize, DL, TLI, ObjectSizeOpts())) 1101 return false; 1102 1103 // Restrict this transformation to only working on small allocations 1104 // (2048 bytes currently), as we don't want to introduce a 16M global or 1105 // something. 1106 if (AllocSize >= 2048) 1107 return false; 1108 1109 // We can't optimize this global unless all uses of it are *known* to be 1110 // of the malloc value, not of the null initializer value (consider a use 1111 // that compares the global's value against zero to see if the malloc has 1112 // been reached). To do this, we check to see if all uses of the global 1113 // would trap if the global were null: this proves that they must all 1114 // happen after the malloc. 1115 if (!allUsesOfLoadedValueWillTrapIfNull(GV)) 1116 return false; 1117 1118 // We can't optimize this if the malloc itself is used in a complex way, 1119 // for example, being stored into multiple globals. This allows the 1120 // malloc to be stored into the specified global, loaded, gep, icmp'd. 1121 // These are all things we could transform to using the global for. 1122 if (!valueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV)) 1123 return false; 1124 1125 OptimizeGlobalAddressOfAllocation(GV, CI, AllocSize, InitVal, DL, TLI); 1126 return true; 1127 } 1128 1129 // Try to optimize globals based on the knowledge that only one value (besides 1130 // its initializer) is ever stored to the global. 1131 static bool 1132 optimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, 1133 const DataLayout &DL, 1134 function_ref<TargetLibraryInfo &(Function &)> GetTLI) { 1135 // Ignore no-op GEPs and bitcasts. 1136 StoredOnceVal = StoredOnceVal->stripPointerCasts(); 1137 1138 // If we are dealing with a pointer global that is initialized to null and 1139 // only has one (non-null) value stored into it, then we can optimize any 1140 // users of the loaded value (often calls and loads) that would trap if the 1141 // value was null. 1142 if (GV->getInitializer()->getType()->isPointerTy() && 1143 GV->getInitializer()->isNullValue() && 1144 StoredOnceVal->getType()->isPointerTy() && 1145 !NullPointerIsDefined( 1146 nullptr /* F */, 1147 GV->getInitializer()->getType()->getPointerAddressSpace())) { 1148 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) { 1149 // Optimize away any trapping uses of the loaded value. 1150 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, DL, GetTLI)) 1151 return true; 1152 } else if (isAllocationFn(StoredOnceVal, GetTLI)) { 1153 if (auto *CI = dyn_cast<CallInst>(StoredOnceVal)) { 1154 auto *TLI = &GetTLI(*CI->getFunction()); 1155 if (tryToOptimizeStoreOfAllocationToGlobal(GV, CI, DL, TLI)) 1156 return true; 1157 } 1158 } 1159 } 1160 1161 return false; 1162 } 1163 1164 /// At this point, we have learned that the only two values ever stored into GV 1165 /// are its initializer and OtherVal. See if we can shrink the global into a 1166 /// boolean and select between the two values whenever it is used. This exposes 1167 /// the values to other scalar optimizations. 1168 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) { 1169 Type *GVElType = GV->getValueType(); 1170 1171 // If GVElType is already i1, it is already shrunk. If the type of the GV is 1172 // an FP value, pointer or vector, don't do this optimization because a select 1173 // between them is very expensive and unlikely to lead to later 1174 // simplification. In these cases, we typically end up with "cond ? v1 : v2" 1175 // where v1 and v2 both require constant pool loads, a big loss. 1176 if (GVElType == Type::getInt1Ty(GV->getContext()) || 1177 GVElType->isFloatingPointTy() || 1178 GVElType->isPointerTy() || GVElType->isVectorTy()) 1179 return false; 1180 1181 // Walk the use list of the global seeing if all the uses are load or store. 1182 // If there is anything else, bail out. 1183 for (User *U : GV->users()) { 1184 if (!isa<LoadInst>(U) && !isa<StoreInst>(U)) 1185 return false; 1186 if (getLoadStoreType(U) != GVElType) 1187 return false; 1188 } 1189 1190 LLVM_DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV << "\n"); 1191 1192 // Create the new global, initializing it to false. 1193 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()), 1194 false, 1195 GlobalValue::InternalLinkage, 1196 ConstantInt::getFalse(GV->getContext()), 1197 GV->getName()+".b", 1198 GV->getThreadLocalMode(), 1199 GV->getType()->getAddressSpace()); 1200 NewGV->copyAttributesFrom(GV); 1201 GV->getParent()->insertGlobalVariable(GV->getIterator(), NewGV); 1202 1203 Constant *InitVal = GV->getInitializer(); 1204 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) && 1205 "No reason to shrink to bool!"); 1206 1207 SmallVector<DIGlobalVariableExpression *, 1> GVs; 1208 GV->getDebugInfo(GVs); 1209 1210 // If initialized to zero and storing one into the global, we can use a cast 1211 // instead of a select to synthesize the desired value. 1212 bool IsOneZero = false; 1213 bool EmitOneOrZero = true; 1214 auto *CI = dyn_cast<ConstantInt>(OtherVal); 1215 if (CI && CI->getValue().getActiveBits() <= 64) { 1216 IsOneZero = InitVal->isNullValue() && CI->isOne(); 1217 1218 auto *CIInit = dyn_cast<ConstantInt>(GV->getInitializer()); 1219 if (CIInit && CIInit->getValue().getActiveBits() <= 64) { 1220 uint64_t ValInit = CIInit->getZExtValue(); 1221 uint64_t ValOther = CI->getZExtValue(); 1222 uint64_t ValMinus = ValOther - ValInit; 1223 1224 for(auto *GVe : GVs){ 1225 DIGlobalVariable *DGV = GVe->getVariable(); 1226 DIExpression *E = GVe->getExpression(); 1227 const DataLayout &DL = GV->getParent()->getDataLayout(); 1228 unsigned SizeInOctets = 1229 DL.getTypeAllocSizeInBits(NewGV->getValueType()) / 8; 1230 1231 // It is expected that the address of global optimized variable is on 1232 // top of the stack. After optimization, value of that variable will 1233 // be ether 0 for initial value or 1 for other value. The following 1234 // expression should return constant integer value depending on the 1235 // value at global object address: 1236 // val * (ValOther - ValInit) + ValInit: 1237 // DW_OP_deref DW_OP_constu <ValMinus> 1238 // DW_OP_mul DW_OP_constu <ValInit> DW_OP_plus DW_OP_stack_value 1239 SmallVector<uint64_t, 12> Ops = { 1240 dwarf::DW_OP_deref_size, SizeInOctets, 1241 dwarf::DW_OP_constu, ValMinus, 1242 dwarf::DW_OP_mul, dwarf::DW_OP_constu, ValInit, 1243 dwarf::DW_OP_plus}; 1244 bool WithStackValue = true; 1245 E = DIExpression::prependOpcodes(E, Ops, WithStackValue); 1246 DIGlobalVariableExpression *DGVE = 1247 DIGlobalVariableExpression::get(NewGV->getContext(), DGV, E); 1248 NewGV->addDebugInfo(DGVE); 1249 } 1250 EmitOneOrZero = false; 1251 } 1252 } 1253 1254 if (EmitOneOrZero) { 1255 // FIXME: This will only emit address for debugger on which will 1256 // be written only 0 or 1. 1257 for(auto *GV : GVs) 1258 NewGV->addDebugInfo(GV); 1259 } 1260 1261 while (!GV->use_empty()) { 1262 Instruction *UI = cast<Instruction>(GV->user_back()); 1263 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) { 1264 // Change the store into a boolean store. 1265 bool StoringOther = SI->getOperand(0) == OtherVal; 1266 // Only do this if we weren't storing a loaded value. 1267 Value *StoreVal; 1268 if (StoringOther || SI->getOperand(0) == InitVal) { 1269 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()), 1270 StoringOther); 1271 } else { 1272 // Otherwise, we are storing a previously loaded copy. To do this, 1273 // change the copy from copying the original value to just copying the 1274 // bool. 1275 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0)); 1276 1277 // If we've already replaced the input, StoredVal will be a cast or 1278 // select instruction. If not, it will be a load of the original 1279 // global. 1280 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) { 1281 assert(LI->getOperand(0) == GV && "Not a copy!"); 1282 // Insert a new load, to preserve the saved value. 1283 StoreVal = new LoadInst(NewGV->getValueType(), NewGV, 1284 LI->getName() + ".b", false, Align(1), 1285 LI->getOrdering(), LI->getSyncScopeID(), LI); 1286 } else { 1287 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) && 1288 "This is not a form that we understand!"); 1289 StoreVal = StoredVal->getOperand(0); 1290 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!"); 1291 } 1292 } 1293 StoreInst *NSI = 1294 new StoreInst(StoreVal, NewGV, false, Align(1), SI->getOrdering(), 1295 SI->getSyncScopeID(), SI); 1296 NSI->setDebugLoc(SI->getDebugLoc()); 1297 } else { 1298 // Change the load into a load of bool then a select. 1299 LoadInst *LI = cast<LoadInst>(UI); 1300 LoadInst *NLI = new LoadInst(NewGV->getValueType(), NewGV, 1301 LI->getName() + ".b", false, Align(1), 1302 LI->getOrdering(), LI->getSyncScopeID(), LI); 1303 Instruction *NSI; 1304 if (IsOneZero) 1305 NSI = new ZExtInst(NLI, LI->getType(), "", LI); 1306 else 1307 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI); 1308 NSI->takeName(LI); 1309 // Since LI is split into two instructions, NLI and NSI both inherit the 1310 // same DebugLoc 1311 NLI->setDebugLoc(LI->getDebugLoc()); 1312 NSI->setDebugLoc(LI->getDebugLoc()); 1313 LI->replaceAllUsesWith(NSI); 1314 } 1315 UI->eraseFromParent(); 1316 } 1317 1318 // Retain the name of the old global variable. People who are debugging their 1319 // programs may expect these variables to be named the same. 1320 NewGV->takeName(GV); 1321 GV->eraseFromParent(); 1322 return true; 1323 } 1324 1325 static bool 1326 deleteIfDead(GlobalValue &GV, 1327 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats, 1328 function_ref<void(Function &)> DeleteFnCallback = nullptr) { 1329 GV.removeDeadConstantUsers(); 1330 1331 if (!GV.isDiscardableIfUnused() && !GV.isDeclaration()) 1332 return false; 1333 1334 if (const Comdat *C = GV.getComdat()) 1335 if (!GV.hasLocalLinkage() && NotDiscardableComdats.count(C)) 1336 return false; 1337 1338 bool Dead; 1339 if (auto *F = dyn_cast<Function>(&GV)) 1340 Dead = (F->isDeclaration() && F->use_empty()) || F->isDefTriviallyDead(); 1341 else 1342 Dead = GV.use_empty(); 1343 if (!Dead) 1344 return false; 1345 1346 LLVM_DEBUG(dbgs() << "GLOBAL DEAD: " << GV << "\n"); 1347 if (auto *F = dyn_cast<Function>(&GV)) { 1348 if (DeleteFnCallback) 1349 DeleteFnCallback(*F); 1350 } 1351 GV.eraseFromParent(); 1352 ++NumDeleted; 1353 return true; 1354 } 1355 1356 static bool isPointerValueDeadOnEntryToFunction( 1357 const Function *F, GlobalValue *GV, 1358 function_ref<DominatorTree &(Function &)> LookupDomTree) { 1359 // Find all uses of GV. We expect them all to be in F, and if we can't 1360 // identify any of the uses we bail out. 1361 // 1362 // On each of these uses, identify if the memory that GV points to is 1363 // used/required/live at the start of the function. If it is not, for example 1364 // if the first thing the function does is store to the GV, the GV can 1365 // possibly be demoted. 1366 // 1367 // We don't do an exhaustive search for memory operations - simply look 1368 // through bitcasts as they're quite common and benign. 1369 const DataLayout &DL = GV->getParent()->getDataLayout(); 1370 SmallVector<LoadInst *, 4> Loads; 1371 SmallVector<StoreInst *, 4> Stores; 1372 for (auto *U : GV->users()) { 1373 Instruction *I = dyn_cast<Instruction>(U); 1374 if (!I) 1375 return false; 1376 assert(I->getParent()->getParent() == F); 1377 1378 if (auto *LI = dyn_cast<LoadInst>(I)) 1379 Loads.push_back(LI); 1380 else if (auto *SI = dyn_cast<StoreInst>(I)) 1381 Stores.push_back(SI); 1382 else 1383 return false; 1384 } 1385 1386 // We have identified all uses of GV into loads and stores. Now check if all 1387 // of them are known not to depend on the value of the global at the function 1388 // entry point. We do this by ensuring that every load is dominated by at 1389 // least one store. 1390 auto &DT = LookupDomTree(*const_cast<Function *>(F)); 1391 1392 // The below check is quadratic. Check we're not going to do too many tests. 1393 // FIXME: Even though this will always have worst-case quadratic time, we 1394 // could put effort into minimizing the average time by putting stores that 1395 // have been shown to dominate at least one load at the beginning of the 1396 // Stores array, making subsequent dominance checks more likely to succeed 1397 // early. 1398 // 1399 // The threshold here is fairly large because global->local demotion is a 1400 // very powerful optimization should it fire. 1401 const unsigned Threshold = 100; 1402 if (Loads.size() * Stores.size() > Threshold) 1403 return false; 1404 1405 for (auto *L : Loads) { 1406 auto *LTy = L->getType(); 1407 if (none_of(Stores, [&](const StoreInst *S) { 1408 auto *STy = S->getValueOperand()->getType(); 1409 // The load is only dominated by the store if DomTree says so 1410 // and the number of bits loaded in L is less than or equal to 1411 // the number of bits stored in S. 1412 return DT.dominates(S, L) && 1413 DL.getTypeStoreSize(LTy).getFixedValue() <= 1414 DL.getTypeStoreSize(STy).getFixedValue(); 1415 })) 1416 return false; 1417 } 1418 // All loads have known dependences inside F, so the global can be localized. 1419 return true; 1420 } 1421 1422 // For a global variable with one store, if the store dominates any loads, 1423 // those loads will always load the stored value (as opposed to the 1424 // initializer), even in the presence of recursion. 1425 static bool forwardStoredOnceStore( 1426 GlobalVariable *GV, const StoreInst *StoredOnceStore, 1427 function_ref<DominatorTree &(Function &)> LookupDomTree) { 1428 const Value *StoredOnceValue = StoredOnceStore->getValueOperand(); 1429 // We can do this optimization for non-constants in nosync + norecurse 1430 // functions, but globals used in exactly one norecurse functions are already 1431 // promoted to an alloca. 1432 if (!isa<Constant>(StoredOnceValue)) 1433 return false; 1434 const Function *F = StoredOnceStore->getFunction(); 1435 SmallVector<LoadInst *> Loads; 1436 for (User *U : GV->users()) { 1437 if (auto *LI = dyn_cast<LoadInst>(U)) { 1438 if (LI->getFunction() == F && 1439 LI->getType() == StoredOnceValue->getType() && LI->isSimple()) 1440 Loads.push_back(LI); 1441 } 1442 } 1443 // Only compute DT if we have any loads to examine. 1444 bool MadeChange = false; 1445 if (!Loads.empty()) { 1446 auto &DT = LookupDomTree(*const_cast<Function *>(F)); 1447 for (auto *LI : Loads) { 1448 if (DT.dominates(StoredOnceStore, LI)) { 1449 LI->replaceAllUsesWith(const_cast<Value *>(StoredOnceValue)); 1450 LI->eraseFromParent(); 1451 MadeChange = true; 1452 } 1453 } 1454 } 1455 return MadeChange; 1456 } 1457 1458 /// Analyze the specified global variable and optimize 1459 /// it if possible. If we make a change, return true. 1460 static bool 1461 processInternalGlobal(GlobalVariable *GV, const GlobalStatus &GS, 1462 function_ref<TargetTransformInfo &(Function &)> GetTTI, 1463 function_ref<TargetLibraryInfo &(Function &)> GetTLI, 1464 function_ref<DominatorTree &(Function &)> LookupDomTree) { 1465 auto &DL = GV->getParent()->getDataLayout(); 1466 // If this is a first class global and has only one accessing function and 1467 // this function is non-recursive, we replace the global with a local alloca 1468 // in this function. 1469 // 1470 // NOTE: It doesn't make sense to promote non-single-value types since we 1471 // are just replacing static memory to stack memory. 1472 // 1473 // If the global is in different address space, don't bring it to stack. 1474 if (!GS.HasMultipleAccessingFunctions && 1475 GS.AccessingFunction && 1476 GV->getValueType()->isSingleValueType() && 1477 GV->getType()->getAddressSpace() == 0 && 1478 !GV->isExternallyInitialized() && 1479 GS.AccessingFunction->doesNotRecurse() && 1480 isPointerValueDeadOnEntryToFunction(GS.AccessingFunction, GV, 1481 LookupDomTree)) { 1482 const DataLayout &DL = GV->getParent()->getDataLayout(); 1483 1484 LLVM_DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV << "\n"); 1485 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction 1486 ->getEntryBlock().begin()); 1487 Type *ElemTy = GV->getValueType(); 1488 // FIXME: Pass Global's alignment when globals have alignment 1489 AllocaInst *Alloca = new AllocaInst(ElemTy, DL.getAllocaAddrSpace(), nullptr, 1490 GV->getName(), &FirstI); 1491 if (!isa<UndefValue>(GV->getInitializer())) 1492 new StoreInst(GV->getInitializer(), Alloca, &FirstI); 1493 1494 GV->replaceAllUsesWith(Alloca); 1495 GV->eraseFromParent(); 1496 ++NumLocalized; 1497 return true; 1498 } 1499 1500 bool Changed = false; 1501 1502 // If the global is never loaded (but may be stored to), it is dead. 1503 // Delete it now. 1504 if (!GS.IsLoaded) { 1505 LLVM_DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV << "\n"); 1506 1507 if (isLeakCheckerRoot(GV)) { 1508 // Delete any constant stores to the global. 1509 Changed = CleanupPointerRootUsers(GV, GetTLI); 1510 } else { 1511 // Delete any stores we can find to the global. We may not be able to 1512 // make it completely dead though. 1513 Changed = CleanupConstantGlobalUsers(GV, DL); 1514 } 1515 1516 // If the global is dead now, delete it. 1517 if (GV->use_empty()) { 1518 GV->eraseFromParent(); 1519 ++NumDeleted; 1520 Changed = true; 1521 } 1522 return Changed; 1523 1524 } 1525 if (GS.StoredType <= GlobalStatus::InitializerStored) { 1526 LLVM_DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n"); 1527 1528 // Don't actually mark a global constant if it's atomic because atomic loads 1529 // are implemented by a trivial cmpxchg in some edge-cases and that usually 1530 // requires write access to the variable even if it's not actually changed. 1531 if (GS.Ordering == AtomicOrdering::NotAtomic) { 1532 assert(!GV->isConstant() && "Expected a non-constant global"); 1533 GV->setConstant(true); 1534 Changed = true; 1535 } 1536 1537 // Clean up any obviously simplifiable users now. 1538 Changed |= CleanupConstantGlobalUsers(GV, DL); 1539 1540 // If the global is dead now, just nuke it. 1541 if (GV->use_empty()) { 1542 LLVM_DEBUG(dbgs() << " *** Marking constant allowed us to simplify " 1543 << "all users and delete global!\n"); 1544 GV->eraseFromParent(); 1545 ++NumDeleted; 1546 return true; 1547 } 1548 1549 // Fall through to the next check; see if we can optimize further. 1550 ++NumMarked; 1551 } 1552 if (!GV->getInitializer()->getType()->isSingleValueType()) { 1553 const DataLayout &DL = GV->getParent()->getDataLayout(); 1554 if (SRAGlobal(GV, DL)) 1555 return true; 1556 } 1557 Value *StoredOnceValue = GS.getStoredOnceValue(); 1558 if (GS.StoredType == GlobalStatus::StoredOnce && StoredOnceValue) { 1559 Function &StoreFn = 1560 const_cast<Function &>(*GS.StoredOnceStore->getFunction()); 1561 bool CanHaveNonUndefGlobalInitializer = 1562 GetTTI(StoreFn).canHaveNonUndefGlobalInitializerInAddressSpace( 1563 GV->getType()->getAddressSpace()); 1564 // If the initial value for the global was an undef value, and if only 1565 // one other value was stored into it, we can just change the 1566 // initializer to be the stored value, then delete all stores to the 1567 // global. This allows us to mark it constant. 1568 // This is restricted to address spaces that allow globals to have 1569 // initializers. NVPTX, for example, does not support initializers for 1570 // shared memory (AS 3). 1571 auto *SOVConstant = dyn_cast<Constant>(StoredOnceValue); 1572 if (SOVConstant && isa<UndefValue>(GV->getInitializer()) && 1573 DL.getTypeAllocSize(SOVConstant->getType()) == 1574 DL.getTypeAllocSize(GV->getValueType()) && 1575 CanHaveNonUndefGlobalInitializer) { 1576 if (SOVConstant->getType() == GV->getValueType()) { 1577 // Change the initializer in place. 1578 GV->setInitializer(SOVConstant); 1579 } else { 1580 // Create a new global with adjusted type. 1581 auto *NGV = new GlobalVariable( 1582 *GV->getParent(), SOVConstant->getType(), GV->isConstant(), 1583 GV->getLinkage(), SOVConstant, "", GV, GV->getThreadLocalMode(), 1584 GV->getAddressSpace()); 1585 NGV->takeName(GV); 1586 NGV->copyAttributesFrom(GV); 1587 GV->replaceAllUsesWith(ConstantExpr::getBitCast(NGV, GV->getType())); 1588 GV->eraseFromParent(); 1589 GV = NGV; 1590 } 1591 1592 // Clean up any obviously simplifiable users now. 1593 CleanupConstantGlobalUsers(GV, DL); 1594 1595 if (GV->use_empty()) { 1596 LLVM_DEBUG(dbgs() << " *** Substituting initializer allowed us to " 1597 << "simplify all users and delete global!\n"); 1598 GV->eraseFromParent(); 1599 ++NumDeleted; 1600 } 1601 ++NumSubstitute; 1602 return true; 1603 } 1604 1605 // Try to optimize globals based on the knowledge that only one value 1606 // (besides its initializer) is ever stored to the global. 1607 if (optimizeOnceStoredGlobal(GV, StoredOnceValue, DL, GetTLI)) 1608 return true; 1609 1610 // Try to forward the store to any loads. If we have more than one store, we 1611 // may have a store of the initializer between StoredOnceStore and a load. 1612 if (GS.NumStores == 1) 1613 if (forwardStoredOnceStore(GV, GS.StoredOnceStore, LookupDomTree)) 1614 return true; 1615 1616 // Otherwise, if the global was not a boolean, we can shrink it to be a 1617 // boolean. Skip this optimization for AS that doesn't allow an initializer. 1618 if (SOVConstant && GS.Ordering == AtomicOrdering::NotAtomic && 1619 (!isa<UndefValue>(GV->getInitializer()) || 1620 CanHaveNonUndefGlobalInitializer)) { 1621 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) { 1622 ++NumShrunkToBool; 1623 return true; 1624 } 1625 } 1626 } 1627 1628 return Changed; 1629 } 1630 1631 /// Analyze the specified global variable and optimize it if possible. If we 1632 /// make a change, return true. 1633 static bool 1634 processGlobal(GlobalValue &GV, 1635 function_ref<TargetTransformInfo &(Function &)> GetTTI, 1636 function_ref<TargetLibraryInfo &(Function &)> GetTLI, 1637 function_ref<DominatorTree &(Function &)> LookupDomTree) { 1638 if (GV.getName().startswith("llvm.")) 1639 return false; 1640 1641 GlobalStatus GS; 1642 1643 if (GlobalStatus::analyzeGlobal(&GV, GS)) 1644 return false; 1645 1646 bool Changed = false; 1647 if (!GS.IsCompared && !GV.hasGlobalUnnamedAddr()) { 1648 auto NewUnnamedAddr = GV.hasLocalLinkage() ? GlobalValue::UnnamedAddr::Global 1649 : GlobalValue::UnnamedAddr::Local; 1650 if (NewUnnamedAddr != GV.getUnnamedAddr()) { 1651 GV.setUnnamedAddr(NewUnnamedAddr); 1652 NumUnnamed++; 1653 Changed = true; 1654 } 1655 } 1656 1657 // Do more involved optimizations if the global is internal. 1658 if (!GV.hasLocalLinkage()) 1659 return Changed; 1660 1661 auto *GVar = dyn_cast<GlobalVariable>(&GV); 1662 if (!GVar) 1663 return Changed; 1664 1665 if (GVar->isConstant() || !GVar->hasInitializer()) 1666 return Changed; 1667 1668 return processInternalGlobal(GVar, GS, GetTTI, GetTLI, LookupDomTree) || 1669 Changed; 1670 } 1671 1672 /// Walk all of the direct calls of the specified function, changing them to 1673 /// FastCC. 1674 static void ChangeCalleesToFastCall(Function *F) { 1675 for (User *U : F->users()) { 1676 if (isa<BlockAddress>(U)) 1677 continue; 1678 cast<CallBase>(U)->setCallingConv(CallingConv::Fast); 1679 } 1680 } 1681 1682 static AttributeList StripAttr(LLVMContext &C, AttributeList Attrs, 1683 Attribute::AttrKind A) { 1684 unsigned AttrIndex; 1685 if (Attrs.hasAttrSomewhere(A, &AttrIndex)) 1686 return Attrs.removeAttributeAtIndex(C, AttrIndex, A); 1687 return Attrs; 1688 } 1689 1690 static void RemoveAttribute(Function *F, Attribute::AttrKind A) { 1691 F->setAttributes(StripAttr(F->getContext(), F->getAttributes(), A)); 1692 for (User *U : F->users()) { 1693 if (isa<BlockAddress>(U)) 1694 continue; 1695 CallBase *CB = cast<CallBase>(U); 1696 CB->setAttributes(StripAttr(F->getContext(), CB->getAttributes(), A)); 1697 } 1698 } 1699 1700 /// Return true if this is a calling convention that we'd like to change. The 1701 /// idea here is that we don't want to mess with the convention if the user 1702 /// explicitly requested something with performance implications like coldcc, 1703 /// GHC, or anyregcc. 1704 static bool hasChangeableCC(Function *F) { 1705 CallingConv::ID CC = F->getCallingConv(); 1706 1707 // FIXME: Is it worth transforming x86_stdcallcc and x86_fastcallcc? 1708 if (CC != CallingConv::C && CC != CallingConv::X86_ThisCall) 1709 return false; 1710 1711 // FIXME: Change CC for the whole chain of musttail calls when possible. 1712 // 1713 // Can't change CC of the function that either has musttail calls, or is a 1714 // musttail callee itself 1715 for (User *U : F->users()) { 1716 if (isa<BlockAddress>(U)) 1717 continue; 1718 CallInst* CI = dyn_cast<CallInst>(U); 1719 if (!CI) 1720 continue; 1721 1722 if (CI->isMustTailCall()) 1723 return false; 1724 } 1725 1726 for (BasicBlock &BB : *F) 1727 if (BB.getTerminatingMustTailCall()) 1728 return false; 1729 1730 return true; 1731 } 1732 1733 /// Return true if the block containing the call site has a BlockFrequency of 1734 /// less than ColdCCRelFreq% of the entry block. 1735 static bool isColdCallSite(CallBase &CB, BlockFrequencyInfo &CallerBFI) { 1736 const BranchProbability ColdProb(ColdCCRelFreq, 100); 1737 auto *CallSiteBB = CB.getParent(); 1738 auto CallSiteFreq = CallerBFI.getBlockFreq(CallSiteBB); 1739 auto CallerEntryFreq = 1740 CallerBFI.getBlockFreq(&(CB.getCaller()->getEntryBlock())); 1741 return CallSiteFreq < CallerEntryFreq * ColdProb; 1742 } 1743 1744 // This function checks if the input function F is cold at all call sites. It 1745 // also looks each call site's containing function, returning false if the 1746 // caller function contains other non cold calls. The input vector AllCallsCold 1747 // contains a list of functions that only have call sites in cold blocks. 1748 static bool 1749 isValidCandidateForColdCC(Function &F, 1750 function_ref<BlockFrequencyInfo &(Function &)> GetBFI, 1751 const std::vector<Function *> &AllCallsCold) { 1752 1753 if (F.user_empty()) 1754 return false; 1755 1756 for (User *U : F.users()) { 1757 if (isa<BlockAddress>(U)) 1758 continue; 1759 1760 CallBase &CB = cast<CallBase>(*U); 1761 Function *CallerFunc = CB.getParent()->getParent(); 1762 BlockFrequencyInfo &CallerBFI = GetBFI(*CallerFunc); 1763 if (!isColdCallSite(CB, CallerBFI)) 1764 return false; 1765 if (!llvm::is_contained(AllCallsCold, CallerFunc)) 1766 return false; 1767 } 1768 return true; 1769 } 1770 1771 static void changeCallSitesToColdCC(Function *F) { 1772 for (User *U : F->users()) { 1773 if (isa<BlockAddress>(U)) 1774 continue; 1775 cast<CallBase>(U)->setCallingConv(CallingConv::Cold); 1776 } 1777 } 1778 1779 // This function iterates over all the call instructions in the input Function 1780 // and checks that all call sites are in cold blocks and are allowed to use the 1781 // coldcc calling convention. 1782 static bool 1783 hasOnlyColdCalls(Function &F, 1784 function_ref<BlockFrequencyInfo &(Function &)> GetBFI) { 1785 for (BasicBlock &BB : F) { 1786 for (Instruction &I : BB) { 1787 if (CallInst *CI = dyn_cast<CallInst>(&I)) { 1788 // Skip over isline asm instructions since they aren't function calls. 1789 if (CI->isInlineAsm()) 1790 continue; 1791 Function *CalledFn = CI->getCalledFunction(); 1792 if (!CalledFn) 1793 return false; 1794 // Skip over intrinsics since they won't remain as function calls. 1795 // Important to do this check before the linkage check below so we 1796 // won't bail out on debug intrinsics, possibly making the generated 1797 // code dependent on the presence of debug info. 1798 if (CalledFn->getIntrinsicID() != Intrinsic::not_intrinsic) 1799 continue; 1800 if (!CalledFn->hasLocalLinkage()) 1801 return false; 1802 // Check if it's valid to use coldcc calling convention. 1803 if (!hasChangeableCC(CalledFn) || CalledFn->isVarArg() || 1804 CalledFn->hasAddressTaken()) 1805 return false; 1806 BlockFrequencyInfo &CallerBFI = GetBFI(F); 1807 if (!isColdCallSite(*CI, CallerBFI)) 1808 return false; 1809 } 1810 } 1811 } 1812 return true; 1813 } 1814 1815 static bool hasMustTailCallers(Function *F) { 1816 for (User *U : F->users()) { 1817 CallBase *CB = dyn_cast<CallBase>(U); 1818 if (!CB) { 1819 assert(isa<BlockAddress>(U) && 1820 "Expected either CallBase or BlockAddress"); 1821 continue; 1822 } 1823 if (CB->isMustTailCall()) 1824 return true; 1825 } 1826 return false; 1827 } 1828 1829 static bool hasInvokeCallers(Function *F) { 1830 for (User *U : F->users()) 1831 if (isa<InvokeInst>(U)) 1832 return true; 1833 return false; 1834 } 1835 1836 static void RemovePreallocated(Function *F) { 1837 RemoveAttribute(F, Attribute::Preallocated); 1838 1839 auto *M = F->getParent(); 1840 1841 IRBuilder<> Builder(M->getContext()); 1842 1843 // Cannot modify users() while iterating over it, so make a copy. 1844 SmallVector<User *, 4> PreallocatedCalls(F->users()); 1845 for (User *U : PreallocatedCalls) { 1846 CallBase *CB = dyn_cast<CallBase>(U); 1847 if (!CB) 1848 continue; 1849 1850 assert( 1851 !CB->isMustTailCall() && 1852 "Shouldn't call RemotePreallocated() on a musttail preallocated call"); 1853 // Create copy of call without "preallocated" operand bundle. 1854 SmallVector<OperandBundleDef, 1> OpBundles; 1855 CB->getOperandBundlesAsDefs(OpBundles); 1856 CallBase *PreallocatedSetup = nullptr; 1857 for (auto *It = OpBundles.begin(); It != OpBundles.end(); ++It) { 1858 if (It->getTag() == "preallocated") { 1859 PreallocatedSetup = cast<CallBase>(*It->input_begin()); 1860 OpBundles.erase(It); 1861 break; 1862 } 1863 } 1864 assert(PreallocatedSetup && "Did not find preallocated bundle"); 1865 uint64_t ArgCount = 1866 cast<ConstantInt>(PreallocatedSetup->getArgOperand(0))->getZExtValue(); 1867 1868 assert((isa<CallInst>(CB) || isa<InvokeInst>(CB)) && 1869 "Unknown indirect call type"); 1870 CallBase *NewCB = CallBase::Create(CB, OpBundles, CB); 1871 CB->replaceAllUsesWith(NewCB); 1872 NewCB->takeName(CB); 1873 CB->eraseFromParent(); 1874 1875 Builder.SetInsertPoint(PreallocatedSetup); 1876 auto *StackSave = 1877 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stacksave)); 1878 1879 Builder.SetInsertPoint(NewCB->getNextNonDebugInstruction()); 1880 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackrestore), 1881 StackSave); 1882 1883 // Replace @llvm.call.preallocated.arg() with alloca. 1884 // Cannot modify users() while iterating over it, so make a copy. 1885 // @llvm.call.preallocated.arg() can be called with the same index multiple 1886 // times. So for each @llvm.call.preallocated.arg(), we see if we have 1887 // already created a Value* for the index, and if not, create an alloca and 1888 // bitcast right after the @llvm.call.preallocated.setup() so that it 1889 // dominates all uses. 1890 SmallVector<Value *, 2> ArgAllocas(ArgCount); 1891 SmallVector<User *, 2> PreallocatedArgs(PreallocatedSetup->users()); 1892 for (auto *User : PreallocatedArgs) { 1893 auto *UseCall = cast<CallBase>(User); 1894 assert(UseCall->getCalledFunction()->getIntrinsicID() == 1895 Intrinsic::call_preallocated_arg && 1896 "preallocated token use was not a llvm.call.preallocated.arg"); 1897 uint64_t AllocArgIndex = 1898 cast<ConstantInt>(UseCall->getArgOperand(1))->getZExtValue(); 1899 Value *AllocaReplacement = ArgAllocas[AllocArgIndex]; 1900 if (!AllocaReplacement) { 1901 auto AddressSpace = UseCall->getType()->getPointerAddressSpace(); 1902 auto *ArgType = 1903 UseCall->getFnAttr(Attribute::Preallocated).getValueAsType(); 1904 auto *InsertBefore = PreallocatedSetup->getNextNonDebugInstruction(); 1905 Builder.SetInsertPoint(InsertBefore); 1906 auto *Alloca = 1907 Builder.CreateAlloca(ArgType, AddressSpace, nullptr, "paarg"); 1908 auto *BitCast = Builder.CreateBitCast( 1909 Alloca, Type::getInt8PtrTy(M->getContext()), UseCall->getName()); 1910 ArgAllocas[AllocArgIndex] = BitCast; 1911 AllocaReplacement = BitCast; 1912 } 1913 1914 UseCall->replaceAllUsesWith(AllocaReplacement); 1915 UseCall->eraseFromParent(); 1916 } 1917 // Remove @llvm.call.preallocated.setup(). 1918 cast<Instruction>(PreallocatedSetup)->eraseFromParent(); 1919 } 1920 } 1921 1922 static bool 1923 OptimizeFunctions(Module &M, 1924 function_ref<TargetLibraryInfo &(Function &)> GetTLI, 1925 function_ref<TargetTransformInfo &(Function &)> GetTTI, 1926 function_ref<BlockFrequencyInfo &(Function &)> GetBFI, 1927 function_ref<DominatorTree &(Function &)> LookupDomTree, 1928 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats, 1929 function_ref<void(Function &F)> ChangedCFGCallback, 1930 function_ref<void(Function &F)> DeleteFnCallback) { 1931 1932 bool Changed = false; 1933 1934 std::vector<Function *> AllCallsCold; 1935 for (Function &F : llvm::make_early_inc_range(M)) 1936 if (hasOnlyColdCalls(F, GetBFI)) 1937 AllCallsCold.push_back(&F); 1938 1939 // Optimize functions. 1940 for (Function &F : llvm::make_early_inc_range(M)) { 1941 // Don't perform global opt pass on naked functions; we don't want fast 1942 // calling conventions for naked functions. 1943 if (F.hasFnAttribute(Attribute::Naked)) 1944 continue; 1945 1946 // Functions without names cannot be referenced outside this module. 1947 if (!F.hasName() && !F.isDeclaration() && !F.hasLocalLinkage()) 1948 F.setLinkage(GlobalValue::InternalLinkage); 1949 1950 if (deleteIfDead(F, NotDiscardableComdats, DeleteFnCallback)) { 1951 Changed = true; 1952 continue; 1953 } 1954 1955 // LLVM's definition of dominance allows instructions that are cyclic 1956 // in unreachable blocks, e.g.: 1957 // %pat = select i1 %condition, @global, i16* %pat 1958 // because any instruction dominates an instruction in a block that's 1959 // not reachable from entry. 1960 // So, remove unreachable blocks from the function, because a) there's 1961 // no point in analyzing them and b) GlobalOpt should otherwise grow 1962 // some more complicated logic to break these cycles. 1963 // Notify the analysis manager that we've modified the function's CFG. 1964 if (!F.isDeclaration()) { 1965 if (removeUnreachableBlocks(F)) { 1966 Changed = true; 1967 ChangedCFGCallback(F); 1968 } 1969 } 1970 1971 Changed |= processGlobal(F, GetTTI, GetTLI, LookupDomTree); 1972 1973 if (!F.hasLocalLinkage()) 1974 continue; 1975 1976 // If we have an inalloca parameter that we can safely remove the 1977 // inalloca attribute from, do so. This unlocks optimizations that 1978 // wouldn't be safe in the presence of inalloca. 1979 // FIXME: We should also hoist alloca affected by this to the entry 1980 // block if possible. 1981 if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca) && 1982 !F.hasAddressTaken() && !hasMustTailCallers(&F) && !F.isVarArg()) { 1983 RemoveAttribute(&F, Attribute::InAlloca); 1984 Changed = true; 1985 } 1986 1987 // FIXME: handle invokes 1988 // FIXME: handle musttail 1989 if (F.getAttributes().hasAttrSomewhere(Attribute::Preallocated)) { 1990 if (!F.hasAddressTaken() && !hasMustTailCallers(&F) && 1991 !hasInvokeCallers(&F)) { 1992 RemovePreallocated(&F); 1993 Changed = true; 1994 } 1995 continue; 1996 } 1997 1998 if (hasChangeableCC(&F) && !F.isVarArg() && !F.hasAddressTaken()) { 1999 NumInternalFunc++; 2000 TargetTransformInfo &TTI = GetTTI(F); 2001 // Change the calling convention to coldcc if either stress testing is 2002 // enabled or the target would like to use coldcc on functions which are 2003 // cold at all call sites and the callers contain no other non coldcc 2004 // calls. 2005 if (EnableColdCCStressTest || 2006 (TTI.useColdCCForColdCall(F) && 2007 isValidCandidateForColdCC(F, GetBFI, AllCallsCold))) { 2008 F.setCallingConv(CallingConv::Cold); 2009 changeCallSitesToColdCC(&F); 2010 Changed = true; 2011 NumColdCC++; 2012 } 2013 } 2014 2015 if (hasChangeableCC(&F) && !F.isVarArg() && !F.hasAddressTaken()) { 2016 // If this function has a calling convention worth changing, is not a 2017 // varargs function, and is only called directly, promote it to use the 2018 // Fast calling convention. 2019 F.setCallingConv(CallingConv::Fast); 2020 ChangeCalleesToFastCall(&F); 2021 ++NumFastCallFns; 2022 Changed = true; 2023 } 2024 2025 if (F.getAttributes().hasAttrSomewhere(Attribute::Nest) && 2026 !F.hasAddressTaken()) { 2027 // The function is not used by a trampoline intrinsic, so it is safe 2028 // to remove the 'nest' attribute. 2029 RemoveAttribute(&F, Attribute::Nest); 2030 ++NumNestRemoved; 2031 Changed = true; 2032 } 2033 } 2034 return Changed; 2035 } 2036 2037 static bool 2038 OptimizeGlobalVars(Module &M, 2039 function_ref<TargetTransformInfo &(Function &)> GetTTI, 2040 function_ref<TargetLibraryInfo &(Function &)> GetTLI, 2041 function_ref<DominatorTree &(Function &)> LookupDomTree, 2042 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) { 2043 bool Changed = false; 2044 2045 for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) { 2046 // Global variables without names cannot be referenced outside this module. 2047 if (!GV.hasName() && !GV.isDeclaration() && !GV.hasLocalLinkage()) 2048 GV.setLinkage(GlobalValue::InternalLinkage); 2049 // Simplify the initializer. 2050 if (GV.hasInitializer()) 2051 if (auto *C = dyn_cast<Constant>(GV.getInitializer())) { 2052 auto &DL = M.getDataLayout(); 2053 // TLI is not used in the case of a Constant, so use default nullptr 2054 // for that optional parameter, since we don't have a Function to 2055 // provide GetTLI anyway. 2056 Constant *New = ConstantFoldConstant(C, DL, /*TLI*/ nullptr); 2057 if (New != C) 2058 GV.setInitializer(New); 2059 } 2060 2061 if (deleteIfDead(GV, NotDiscardableComdats)) { 2062 Changed = true; 2063 continue; 2064 } 2065 2066 Changed |= processGlobal(GV, GetTTI, GetTLI, LookupDomTree); 2067 } 2068 return Changed; 2069 } 2070 2071 /// Evaluate static constructors in the function, if we can. Return true if we 2072 /// can, false otherwise. 2073 static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL, 2074 TargetLibraryInfo *TLI) { 2075 // Skip external functions. 2076 if (F->isDeclaration()) 2077 return false; 2078 // Call the function. 2079 Evaluator Eval(DL, TLI); 2080 Constant *RetValDummy; 2081 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy, 2082 SmallVector<Constant*, 0>()); 2083 2084 if (EvalSuccess) { 2085 ++NumCtorsEvaluated; 2086 2087 // We succeeded at evaluation: commit the result. 2088 auto NewInitializers = Eval.getMutatedInitializers(); 2089 LLVM_DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '" 2090 << F->getName() << "' to " << NewInitializers.size() 2091 << " stores.\n"); 2092 for (const auto &Pair : NewInitializers) 2093 Pair.first->setInitializer(Pair.second); 2094 for (GlobalVariable *GV : Eval.getInvariants()) 2095 GV->setConstant(true); 2096 } 2097 2098 return EvalSuccess; 2099 } 2100 2101 static int compareNames(Constant *const *A, Constant *const *B) { 2102 Value *AStripped = (*A)->stripPointerCasts(); 2103 Value *BStripped = (*B)->stripPointerCasts(); 2104 return AStripped->getName().compare(BStripped->getName()); 2105 } 2106 2107 static void setUsedInitializer(GlobalVariable &V, 2108 const SmallPtrSetImpl<GlobalValue *> &Init) { 2109 if (Init.empty()) { 2110 V.eraseFromParent(); 2111 return; 2112 } 2113 2114 // Get address space of pointers in the array of pointers. 2115 const Type *UsedArrayType = V.getValueType(); 2116 const auto *VAT = cast<ArrayType>(UsedArrayType); 2117 const auto *VEPT = cast<PointerType>(VAT->getArrayElementType()); 2118 2119 // Type of pointer to the array of pointers. 2120 PointerType *Int8PtrTy = 2121 Type::getInt8PtrTy(V.getContext(), VEPT->getAddressSpace()); 2122 2123 SmallVector<Constant *, 8> UsedArray; 2124 for (GlobalValue *GV : Init) { 2125 Constant *Cast = 2126 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, Int8PtrTy); 2127 UsedArray.push_back(Cast); 2128 } 2129 2130 // Sort to get deterministic order. 2131 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames); 2132 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size()); 2133 2134 Module *M = V.getParent(); 2135 V.removeFromParent(); 2136 GlobalVariable *NV = 2137 new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage, 2138 ConstantArray::get(ATy, UsedArray), ""); 2139 NV->takeName(&V); 2140 NV->setSection("llvm.metadata"); 2141 delete &V; 2142 } 2143 2144 namespace { 2145 2146 /// An easy to access representation of llvm.used and llvm.compiler.used. 2147 class LLVMUsed { 2148 SmallPtrSet<GlobalValue *, 4> Used; 2149 SmallPtrSet<GlobalValue *, 4> CompilerUsed; 2150 GlobalVariable *UsedV; 2151 GlobalVariable *CompilerUsedV; 2152 2153 public: 2154 LLVMUsed(Module &M) { 2155 SmallVector<GlobalValue *, 4> Vec; 2156 UsedV = collectUsedGlobalVariables(M, Vec, false); 2157 Used = {Vec.begin(), Vec.end()}; 2158 Vec.clear(); 2159 CompilerUsedV = collectUsedGlobalVariables(M, Vec, true); 2160 CompilerUsed = {Vec.begin(), Vec.end()}; 2161 } 2162 2163 using iterator = SmallPtrSet<GlobalValue *, 4>::iterator; 2164 using used_iterator_range = iterator_range<iterator>; 2165 2166 iterator usedBegin() { return Used.begin(); } 2167 iterator usedEnd() { return Used.end(); } 2168 2169 used_iterator_range used() { 2170 return used_iterator_range(usedBegin(), usedEnd()); 2171 } 2172 2173 iterator compilerUsedBegin() { return CompilerUsed.begin(); } 2174 iterator compilerUsedEnd() { return CompilerUsed.end(); } 2175 2176 used_iterator_range compilerUsed() { 2177 return used_iterator_range(compilerUsedBegin(), compilerUsedEnd()); 2178 } 2179 2180 bool usedCount(GlobalValue *GV) const { return Used.count(GV); } 2181 2182 bool compilerUsedCount(GlobalValue *GV) const { 2183 return CompilerUsed.count(GV); 2184 } 2185 2186 bool usedErase(GlobalValue *GV) { return Used.erase(GV); } 2187 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); } 2188 bool usedInsert(GlobalValue *GV) { return Used.insert(GV).second; } 2189 2190 bool compilerUsedInsert(GlobalValue *GV) { 2191 return CompilerUsed.insert(GV).second; 2192 } 2193 2194 void syncVariablesAndSets() { 2195 if (UsedV) 2196 setUsedInitializer(*UsedV, Used); 2197 if (CompilerUsedV) 2198 setUsedInitializer(*CompilerUsedV, CompilerUsed); 2199 } 2200 }; 2201 2202 } // end anonymous namespace 2203 2204 static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) { 2205 if (GA.use_empty()) // No use at all. 2206 return false; 2207 2208 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) && 2209 "We should have removed the duplicated " 2210 "element from llvm.compiler.used"); 2211 if (!GA.hasOneUse()) 2212 // Strictly more than one use. So at least one is not in llvm.used and 2213 // llvm.compiler.used. 2214 return true; 2215 2216 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used. 2217 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA); 2218 } 2219 2220 static bool mayHaveOtherReferences(GlobalValue &GV, const LLVMUsed &U) { 2221 if (!GV.hasLocalLinkage()) 2222 return true; 2223 2224 return U.usedCount(&GV) || U.compilerUsedCount(&GV); 2225 } 2226 2227 static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U, 2228 bool &RenameTarget) { 2229 RenameTarget = false; 2230 bool Ret = false; 2231 if (hasUseOtherThanLLVMUsed(GA, U)) 2232 Ret = true; 2233 2234 // If the alias is externally visible, we may still be able to simplify it. 2235 if (!mayHaveOtherReferences(GA, U)) 2236 return Ret; 2237 2238 // If the aliasee has internal linkage and no other references (e.g., 2239 // @llvm.used, @llvm.compiler.used), give it the name and linkage of the 2240 // alias, and delete the alias. This turns: 2241 // define internal ... @f(...) 2242 // @a = alias ... @f 2243 // into: 2244 // define ... @a(...) 2245 Constant *Aliasee = GA.getAliasee(); 2246 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts()); 2247 if (mayHaveOtherReferences(*Target, U)) 2248 return Ret; 2249 2250 RenameTarget = true; 2251 return true; 2252 } 2253 2254 static bool 2255 OptimizeGlobalAliases(Module &M, 2256 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) { 2257 bool Changed = false; 2258 LLVMUsed Used(M); 2259 2260 for (GlobalValue *GV : Used.used()) 2261 Used.compilerUsedErase(GV); 2262 2263 // Return whether GV is explicitly or implicitly dso_local and not replaceable 2264 // by another definition in the current linkage unit. 2265 auto IsModuleLocal = [](GlobalValue &GV) { 2266 return !GlobalValue::isInterposableLinkage(GV.getLinkage()) && 2267 (GV.isDSOLocal() || GV.isImplicitDSOLocal()); 2268 }; 2269 2270 for (GlobalAlias &J : llvm::make_early_inc_range(M.aliases())) { 2271 // Aliases without names cannot be referenced outside this module. 2272 if (!J.hasName() && !J.isDeclaration() && !J.hasLocalLinkage()) 2273 J.setLinkage(GlobalValue::InternalLinkage); 2274 2275 if (deleteIfDead(J, NotDiscardableComdats)) { 2276 Changed = true; 2277 continue; 2278 } 2279 2280 // If the alias can change at link time, nothing can be done - bail out. 2281 if (!IsModuleLocal(J)) 2282 continue; 2283 2284 Constant *Aliasee = J.getAliasee(); 2285 GlobalValue *Target = dyn_cast<GlobalValue>(Aliasee->stripPointerCasts()); 2286 // We can't trivially replace the alias with the aliasee if the aliasee is 2287 // non-trivial in some way. We also can't replace the alias with the aliasee 2288 // if the aliasee may be preemptible at runtime. On ELF, a non-preemptible 2289 // alias can be used to access the definition as if preemption did not 2290 // happen. 2291 // TODO: Try to handle non-zero GEPs of local aliasees. 2292 if (!Target || !IsModuleLocal(*Target)) 2293 continue; 2294 2295 Target->removeDeadConstantUsers(); 2296 2297 // Make all users of the alias use the aliasee instead. 2298 bool RenameTarget; 2299 if (!hasUsesToReplace(J, Used, RenameTarget)) 2300 continue; 2301 2302 J.replaceAllUsesWith(ConstantExpr::getBitCast(Aliasee, J.getType())); 2303 ++NumAliasesResolved; 2304 Changed = true; 2305 2306 if (RenameTarget) { 2307 // Give the aliasee the name, linkage and other attributes of the alias. 2308 Target->takeName(&J); 2309 Target->setLinkage(J.getLinkage()); 2310 Target->setDSOLocal(J.isDSOLocal()); 2311 Target->setVisibility(J.getVisibility()); 2312 Target->setDLLStorageClass(J.getDLLStorageClass()); 2313 2314 if (Used.usedErase(&J)) 2315 Used.usedInsert(Target); 2316 2317 if (Used.compilerUsedErase(&J)) 2318 Used.compilerUsedInsert(Target); 2319 } else if (mayHaveOtherReferences(J, Used)) 2320 continue; 2321 2322 // Delete the alias. 2323 M.eraseAlias(&J); 2324 ++NumAliasesRemoved; 2325 Changed = true; 2326 } 2327 2328 Used.syncVariablesAndSets(); 2329 2330 return Changed; 2331 } 2332 2333 static Function * 2334 FindCXAAtExit(Module &M, function_ref<TargetLibraryInfo &(Function &)> GetTLI) { 2335 // Hack to get a default TLI before we have actual Function. 2336 auto FuncIter = M.begin(); 2337 if (FuncIter == M.end()) 2338 return nullptr; 2339 auto *TLI = &GetTLI(*FuncIter); 2340 2341 LibFunc F = LibFunc_cxa_atexit; 2342 if (!TLI->has(F)) 2343 return nullptr; 2344 2345 Function *Fn = M.getFunction(TLI->getName(F)); 2346 if (!Fn) 2347 return nullptr; 2348 2349 // Now get the actual TLI for Fn. 2350 TLI = &GetTLI(*Fn); 2351 2352 // Make sure that the function has the correct prototype. 2353 if (!TLI->getLibFunc(*Fn, F) || F != LibFunc_cxa_atexit) 2354 return nullptr; 2355 2356 return Fn; 2357 } 2358 2359 /// Returns whether the given function is an empty C++ destructor and can 2360 /// therefore be eliminated. 2361 /// Note that we assume that other optimization passes have already simplified 2362 /// the code so we simply check for 'ret'. 2363 static bool cxxDtorIsEmpty(const Function &Fn) { 2364 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and 2365 // nounwind, but that doesn't seem worth doing. 2366 if (Fn.isDeclaration()) 2367 return false; 2368 2369 for (const auto &I : Fn.getEntryBlock()) { 2370 if (I.isDebugOrPseudoInst()) 2371 continue; 2372 if (isa<ReturnInst>(I)) 2373 return true; 2374 break; 2375 } 2376 return false; 2377 } 2378 2379 static bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) { 2380 /// Itanium C++ ABI p3.3.5: 2381 /// 2382 /// After constructing a global (or local static) object, that will require 2383 /// destruction on exit, a termination function is registered as follows: 2384 /// 2385 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d ); 2386 /// 2387 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the 2388 /// call f(p) when DSO d is unloaded, before all such termination calls 2389 /// registered before this one. It returns zero if registration is 2390 /// successful, nonzero on failure. 2391 2392 // This pass will look for calls to __cxa_atexit where the function is trivial 2393 // and remove them. 2394 bool Changed = false; 2395 2396 for (User *U : llvm::make_early_inc_range(CXAAtExitFn->users())) { 2397 // We're only interested in calls. Theoretically, we could handle invoke 2398 // instructions as well, but neither llvm-gcc nor clang generate invokes 2399 // to __cxa_atexit. 2400 CallInst *CI = dyn_cast<CallInst>(U); 2401 if (!CI) 2402 continue; 2403 2404 Function *DtorFn = 2405 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts()); 2406 if (!DtorFn || !cxxDtorIsEmpty(*DtorFn)) 2407 continue; 2408 2409 // Just remove the call. 2410 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType())); 2411 CI->eraseFromParent(); 2412 2413 ++NumCXXDtorsRemoved; 2414 2415 Changed |= true; 2416 } 2417 2418 return Changed; 2419 } 2420 2421 static bool 2422 optimizeGlobalsInModule(Module &M, const DataLayout &DL, 2423 function_ref<TargetLibraryInfo &(Function &)> GetTLI, 2424 function_ref<TargetTransformInfo &(Function &)> GetTTI, 2425 function_ref<BlockFrequencyInfo &(Function &)> GetBFI, 2426 function_ref<DominatorTree &(Function &)> LookupDomTree, 2427 function_ref<void(Function &F)> ChangedCFGCallback, 2428 function_ref<void(Function &F)> DeleteFnCallback) { 2429 SmallPtrSet<const Comdat *, 8> NotDiscardableComdats; 2430 bool Changed = false; 2431 bool LocalChange = true; 2432 std::optional<uint32_t> FirstNotFullyEvaluatedPriority; 2433 2434 while (LocalChange) { 2435 LocalChange = false; 2436 2437 NotDiscardableComdats.clear(); 2438 for (const GlobalVariable &GV : M.globals()) 2439 if (const Comdat *C = GV.getComdat()) 2440 if (!GV.isDiscardableIfUnused() || !GV.use_empty()) 2441 NotDiscardableComdats.insert(C); 2442 for (Function &F : M) 2443 if (const Comdat *C = F.getComdat()) 2444 if (!F.isDefTriviallyDead()) 2445 NotDiscardableComdats.insert(C); 2446 for (GlobalAlias &GA : M.aliases()) 2447 if (const Comdat *C = GA.getComdat()) 2448 if (!GA.isDiscardableIfUnused() || !GA.use_empty()) 2449 NotDiscardableComdats.insert(C); 2450 2451 // Delete functions that are trivially dead, ccc -> fastcc 2452 LocalChange |= OptimizeFunctions(M, GetTLI, GetTTI, GetBFI, LookupDomTree, 2453 NotDiscardableComdats, ChangedCFGCallback, 2454 DeleteFnCallback); 2455 2456 // Optimize global_ctors list. 2457 LocalChange |= 2458 optimizeGlobalCtorsList(M, [&](uint32_t Priority, Function *F) { 2459 if (FirstNotFullyEvaluatedPriority && 2460 *FirstNotFullyEvaluatedPriority != Priority) 2461 return false; 2462 bool Evaluated = EvaluateStaticConstructor(F, DL, &GetTLI(*F)); 2463 if (!Evaluated) 2464 FirstNotFullyEvaluatedPriority = Priority; 2465 return Evaluated; 2466 }); 2467 2468 // Optimize non-address-taken globals. 2469 LocalChange |= OptimizeGlobalVars(M, GetTTI, GetTLI, LookupDomTree, 2470 NotDiscardableComdats); 2471 2472 // Resolve aliases, when possible. 2473 LocalChange |= OptimizeGlobalAliases(M, NotDiscardableComdats); 2474 2475 // Try to remove trivial global destructors if they are not removed 2476 // already. 2477 Function *CXAAtExitFn = FindCXAAtExit(M, GetTLI); 2478 if (CXAAtExitFn) 2479 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn); 2480 2481 Changed |= LocalChange; 2482 } 2483 2484 // TODO: Move all global ctors functions to the end of the module for code 2485 // layout. 2486 2487 return Changed; 2488 } 2489 2490 PreservedAnalyses GlobalOptPass::run(Module &M, ModuleAnalysisManager &AM) { 2491 auto &DL = M.getDataLayout(); 2492 auto &FAM = 2493 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 2494 auto LookupDomTree = [&FAM](Function &F) -> DominatorTree &{ 2495 return FAM.getResult<DominatorTreeAnalysis>(F); 2496 }; 2497 auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & { 2498 return FAM.getResult<TargetLibraryAnalysis>(F); 2499 }; 2500 auto GetTTI = [&FAM](Function &F) -> TargetTransformInfo & { 2501 return FAM.getResult<TargetIRAnalysis>(F); 2502 }; 2503 2504 auto GetBFI = [&FAM](Function &F) -> BlockFrequencyInfo & { 2505 return FAM.getResult<BlockFrequencyAnalysis>(F); 2506 }; 2507 auto ChangedCFGCallback = [&FAM](Function &F) { 2508 FAM.invalidate(F, PreservedAnalyses::none()); 2509 }; 2510 auto DeleteFnCallback = [&FAM](Function &F) { FAM.clear(F, F.getName()); }; 2511 2512 if (!optimizeGlobalsInModule(M, DL, GetTLI, GetTTI, GetBFI, LookupDomTree, 2513 ChangedCFGCallback, DeleteFnCallback)) 2514 return PreservedAnalyses::all(); 2515 2516 PreservedAnalyses PA = PreservedAnalyses::none(); 2517 // We made sure to clear analyses for deleted functions. 2518 PA.preserve<FunctionAnalysisManagerModuleProxy>(); 2519 // The only place we modify the CFG is when calling 2520 // removeUnreachableBlocks(), but there we make sure to invalidate analyses 2521 // for modified functions. 2522 PA.preserveSet<CFGAnalyses>(); 2523 return PA; 2524 } 2525