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