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