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