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