1 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file was developed by the LLVM research group and is distributed under 6 // the University of Illinois Open Source 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 #define DEBUG_TYPE "globalopt" 17 #include "llvm/Transforms/IPO.h" 18 #include "llvm/CallingConv.h" 19 #include "llvm/Constants.h" 20 #include "llvm/DerivedTypes.h" 21 #include "llvm/Instructions.h" 22 #include "llvm/IntrinsicInst.h" 23 #include "llvm/Module.h" 24 #include "llvm/Pass.h" 25 #include "llvm/Support/Debug.h" 26 #include "llvm/Target/TargetData.h" 27 #include "llvm/Transforms/Utils/Local.h" 28 #include "llvm/ADT/Statistic.h" 29 #include "llvm/ADT/StringExtras.h" 30 #include <set> 31 #include <algorithm> 32 using namespace llvm; 33 34 namespace { 35 Statistic<> NumMarked ("globalopt", "Number of globals marked constant"); 36 Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken " 37 "into scalars"); 38 Statistic<> NumSubstitute("globalopt", 39 "Number of globals with initializers stored into them"); 40 Statistic<> NumDeleted ("globalopt", "Number of globals deleted"); 41 Statistic<> NumFnDeleted("globalopt", "Number of functions deleted"); 42 Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized"); 43 Statistic<> NumLocalized("globalopt", "Number of globals localized"); 44 Statistic<> NumShrunkToBool("globalopt", 45 "Number of global vars shrunk to booleans"); 46 Statistic<> NumFastCallFns("globalopt", 47 "Number of functions converted to fastcc"); 48 49 struct GlobalOpt : public ModulePass { 50 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 51 AU.addRequired<TargetData>(); 52 } 53 54 bool runOnModule(Module &M); 55 56 private: 57 bool ProcessInternalGlobal(GlobalVariable *GV, Module::global_iterator &GVI); 58 }; 59 60 RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer"); 61 } 62 63 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); } 64 65 /// GlobalStatus - As we analyze each global, keep track of some information 66 /// about it. If we find out that the address of the global is taken, none of 67 /// this info will be accurate. 68 struct GlobalStatus { 69 /// isLoaded - True if the global is ever loaded. If the global isn't ever 70 /// loaded it can be deleted. 71 bool isLoaded; 72 73 /// StoredType - Keep track of what stores to the global look like. 74 /// 75 enum StoredType { 76 /// NotStored - There is no store to this global. It can thus be marked 77 /// constant. 78 NotStored, 79 80 /// isInitializerStored - This global is stored to, but the only thing 81 /// stored is the constant it was initialized with. This is only tracked 82 /// for scalar globals. 83 isInitializerStored, 84 85 /// isStoredOnce - This global is stored to, but only its initializer and 86 /// one other value is ever stored to it. If this global isStoredOnce, we 87 /// track the value stored to it in StoredOnceValue below. This is only 88 /// tracked for scalar globals. 89 isStoredOnce, 90 91 /// isStored - This global is stored to by multiple values or something else 92 /// that we cannot track. 93 isStored 94 } StoredType; 95 96 /// StoredOnceValue - If only one value (besides the initializer constant) is 97 /// ever stored to this global, keep track of what value it is. 98 Value *StoredOnceValue; 99 100 // AccessingFunction/HasMultipleAccessingFunctions - These start out 101 // null/false. When the first accessing function is noticed, it is recorded. 102 // When a second different accessing function is noticed, 103 // HasMultipleAccessingFunctions is set to true. 104 Function *AccessingFunction; 105 bool HasMultipleAccessingFunctions; 106 107 // HasNonInstructionUser - Set to true if this global has a user that is not 108 // an instruction (e.g. a constant expr or GV initializer). 109 bool HasNonInstructionUser; 110 111 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of 112 /// the global exist. Such users include GEP instruction with variable 113 /// indexes, and non-gep/load/store users like constant expr casts. 114 bool isNotSuitableForSRA; 115 116 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0), 117 AccessingFunction(0), HasMultipleAccessingFunctions(false), 118 HasNonInstructionUser(false), isNotSuitableForSRA(false) {} 119 }; 120 121 122 123 /// ConstantIsDead - Return true if the specified constant is (transitively) 124 /// dead. The constant may be used by other constants (e.g. constant arrays and 125 /// constant exprs) as long as they are dead, but it cannot be used by anything 126 /// else. 127 static bool ConstantIsDead(Constant *C) { 128 if (isa<GlobalValue>(C)) return false; 129 130 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI) 131 if (Constant *CU = dyn_cast<Constant>(*UI)) { 132 if (!ConstantIsDead(CU)) return false; 133 } else 134 return false; 135 return true; 136 } 137 138 139 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus 140 /// structure. If the global has its address taken, return true to indicate we 141 /// can't do anything with it. 142 /// 143 static bool AnalyzeGlobal(Value *V, GlobalStatus &GS, 144 std::set<PHINode*> &PHIUsers) { 145 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI) 146 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) { 147 GS.HasNonInstructionUser = true; 148 149 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true; 150 if (CE->getOpcode() != Instruction::GetElementPtr) 151 GS.isNotSuitableForSRA = true; 152 else if (!GS.isNotSuitableForSRA) { 153 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we 154 // don't like < 3 operand CE's, and we don't like non-constant integer 155 // indices. 156 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue()) 157 GS.isNotSuitableForSRA = true; 158 else { 159 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i) 160 if (!isa<ConstantInt>(CE->getOperand(i))) { 161 GS.isNotSuitableForSRA = true; 162 break; 163 } 164 } 165 } 166 167 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) { 168 if (!GS.HasMultipleAccessingFunctions) { 169 Function *F = I->getParent()->getParent(); 170 if (GS.AccessingFunction == 0) 171 GS.AccessingFunction = F; 172 else if (GS.AccessingFunction != F) 173 GS.HasMultipleAccessingFunctions = true; 174 } 175 if (isa<LoadInst>(I)) { 176 GS.isLoaded = true; 177 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 178 // Don't allow a store OF the address, only stores TO the address. 179 if (SI->getOperand(0) == V) return true; 180 181 // If this is a direct store to the global (i.e., the global is a scalar 182 // value, not an aggregate), keep more specific information about 183 // stores. 184 if (GS.StoredType != GlobalStatus::isStored) 185 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){ 186 Value *StoredVal = SI->getOperand(0); 187 if (StoredVal == GV->getInitializer()) { 188 if (GS.StoredType < GlobalStatus::isInitializerStored) 189 GS.StoredType = GlobalStatus::isInitializerStored; 190 } else if (isa<LoadInst>(StoredVal) && 191 cast<LoadInst>(StoredVal)->getOperand(0) == GV) { 192 // G = G 193 if (GS.StoredType < GlobalStatus::isInitializerStored) 194 GS.StoredType = GlobalStatus::isInitializerStored; 195 } else if (GS.StoredType < GlobalStatus::isStoredOnce) { 196 GS.StoredType = GlobalStatus::isStoredOnce; 197 GS.StoredOnceValue = StoredVal; 198 } else if (GS.StoredType == GlobalStatus::isStoredOnce && 199 GS.StoredOnceValue == StoredVal) { 200 // noop. 201 } else { 202 GS.StoredType = GlobalStatus::isStored; 203 } 204 } else { 205 GS.StoredType = GlobalStatus::isStored; 206 } 207 } else if (isa<GetElementPtrInst>(I)) { 208 if (AnalyzeGlobal(I, GS, PHIUsers)) return true; 209 210 // If the first two indices are constants, this can be SRA'd. 211 if (isa<GlobalVariable>(I->getOperand(0))) { 212 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) || 213 !cast<Constant>(I->getOperand(1))->isNullValue() || 214 !isa<ConstantInt>(I->getOperand(2))) 215 GS.isNotSuitableForSRA = true; 216 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){ 217 if (CE->getOpcode() != Instruction::GetElementPtr || 218 CE->getNumOperands() < 3 || I->getNumOperands() < 2 || 219 !isa<Constant>(I->getOperand(0)) || 220 !cast<Constant>(I->getOperand(0))->isNullValue()) 221 GS.isNotSuitableForSRA = true; 222 } else { 223 GS.isNotSuitableForSRA = true; 224 } 225 } else if (isa<SelectInst>(I)) { 226 if (AnalyzeGlobal(I, GS, PHIUsers)) return true; 227 GS.isNotSuitableForSRA = true; 228 } else if (PHINode *PN = dyn_cast<PHINode>(I)) { 229 // PHI nodes we can check just like select or GEP instructions, but we 230 // have to be careful about infinite recursion. 231 if (PHIUsers.insert(PN).second) // Not already visited. 232 if (AnalyzeGlobal(I, GS, PHIUsers)) return true; 233 GS.isNotSuitableForSRA = true; 234 } else if (isa<SetCondInst>(I)) { 235 GS.isNotSuitableForSRA = true; 236 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) { 237 if (I->getOperand(1) == V) 238 GS.StoredType = GlobalStatus::isStored; 239 if (I->getOperand(2) == V) 240 GS.isLoaded = true; 241 GS.isNotSuitableForSRA = true; 242 } else if (isa<MemSetInst>(I)) { 243 assert(I->getOperand(1) == V && "Memset only takes one pointer!"); 244 GS.StoredType = GlobalStatus::isStored; 245 GS.isNotSuitableForSRA = true; 246 } else { 247 return true; // Any other non-load instruction might take address! 248 } 249 } else if (Constant *C = dyn_cast<Constant>(*UI)) { 250 GS.HasNonInstructionUser = true; 251 // We might have a dead and dangling constant hanging off of here. 252 if (!ConstantIsDead(C)) 253 return true; 254 } else { 255 GS.HasNonInstructionUser = true; 256 // Otherwise must be some other user. 257 return true; 258 } 259 260 return false; 261 } 262 263 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) { 264 ConstantInt *CI = dyn_cast<ConstantInt>(Idx); 265 if (!CI) return 0; 266 unsigned IdxV = (unsigned)CI->getRawValue(); 267 268 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) { 269 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV); 270 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) { 271 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV); 272 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) { 273 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV); 274 } else if (isa<ConstantAggregateZero>(Agg)) { 275 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) { 276 if (IdxV < STy->getNumElements()) 277 return Constant::getNullValue(STy->getElementType(IdxV)); 278 } else if (const SequentialType *STy = 279 dyn_cast<SequentialType>(Agg->getType())) { 280 return Constant::getNullValue(STy->getElementType()); 281 } 282 } else if (isa<UndefValue>(Agg)) { 283 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) { 284 if (IdxV < STy->getNumElements()) 285 return UndefValue::get(STy->getElementType(IdxV)); 286 } else if (const SequentialType *STy = 287 dyn_cast<SequentialType>(Agg->getType())) { 288 return UndefValue::get(STy->getElementType()); 289 } 290 } 291 return 0; 292 } 293 294 static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) { 295 if (Init == 0) return 0; 296 if (GEP->getNumOperands() == 1 || 297 !isa<Constant>(GEP->getOperand(1)) || 298 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 299 return 0; 300 301 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) { 302 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i)); 303 if (!Idx) return 0; 304 Init = getAggregateConstantElement(Init, Idx); 305 if (Init == 0) return 0; 306 } 307 return Init; 308 } 309 310 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all 311 /// users of the global, cleaning up the obvious ones. This is largely just a 312 /// quick scan over the use list to clean up the easy and obvious cruft. This 313 /// returns true if it made a change. 314 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) { 315 bool Changed = false; 316 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) { 317 User *U = *UI++; 318 319 if (LoadInst *LI = dyn_cast<LoadInst>(U)) { 320 if (Init) { 321 // Replace the load with the initializer. 322 LI->replaceAllUsesWith(Init); 323 LI->eraseFromParent(); 324 Changed = true; 325 } 326 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 327 // Store must be unreachable or storing Init into the global. 328 SI->eraseFromParent(); 329 Changed = true; 330 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) { 331 if (CE->getOpcode() == Instruction::GetElementPtr) { 332 Constant *SubInit = TraverseGEPInitializer(CE, Init); 333 Changed |= CleanupConstantGlobalUsers(CE, SubInit); 334 } else if (CE->getOpcode() == Instruction::Cast && 335 isa<PointerType>(CE->getType())) { 336 // Pointer cast, delete any stores and memsets to the global. 337 Changed |= CleanupConstantGlobalUsers(CE, 0); 338 } 339 340 if (CE->use_empty()) { 341 CE->destroyConstant(); 342 Changed = true; 343 } 344 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) { 345 Constant *SubInit = TraverseGEPInitializer(GEP, Init); 346 Changed |= CleanupConstantGlobalUsers(GEP, SubInit); 347 348 if (GEP->use_empty()) { 349 GEP->eraseFromParent(); 350 Changed = true; 351 } 352 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv 353 if (MI->getRawDest() == V) { 354 MI->eraseFromParent(); 355 Changed = true; 356 } 357 358 } else if (Constant *C = dyn_cast<Constant>(U)) { 359 // If we have a chain of dead constantexprs or other things dangling from 360 // us, and if they are all dead, nuke them without remorse. 361 if (ConstantIsDead(C)) { 362 C->destroyConstant(); 363 // This could have invalidated UI, start over from scratch. 364 CleanupConstantGlobalUsers(V, Init); 365 return true; 366 } 367 } 368 } 369 return Changed; 370 } 371 372 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global 373 /// variable. This opens the door for other optimizations by exposing the 374 /// behavior of the program in a more fine-grained way. We have determined that 375 /// this transformation is safe already. We return the first global variable we 376 /// insert so that the caller can reprocess it. 377 static GlobalVariable *SRAGlobal(GlobalVariable *GV) { 378 assert(GV->hasInternalLinkage() && !GV->isConstant()); 379 Constant *Init = GV->getInitializer(); 380 const Type *Ty = Init->getType(); 381 382 std::vector<GlobalVariable*> NewGlobals; 383 Module::GlobalListType &Globals = GV->getParent()->getGlobalList(); 384 385 if (const StructType *STy = dyn_cast<StructType>(Ty)) { 386 NewGlobals.reserve(STy->getNumElements()); 387 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 388 Constant *In = getAggregateConstantElement(Init, 389 ConstantUInt::get(Type::UIntTy, i)); 390 assert(In && "Couldn't get element of initializer?"); 391 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false, 392 GlobalVariable::InternalLinkage, 393 In, GV->getName()+"."+utostr(i)); 394 Globals.insert(GV, NGV); 395 NewGlobals.push_back(NGV); 396 } 397 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) { 398 unsigned NumElements = 0; 399 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy)) 400 NumElements = ATy->getNumElements(); 401 else if (const PackedType *PTy = dyn_cast<PackedType>(STy)) 402 NumElements = PTy->getNumElements(); 403 else 404 assert(0 && "Unknown aggregate sequential type!"); 405 406 if (NumElements > 16 && GV->hasNUsesOrMore(16)) 407 return 0; // It's not worth it. 408 NewGlobals.reserve(NumElements); 409 for (unsigned i = 0, e = NumElements; i != e; ++i) { 410 Constant *In = getAggregateConstantElement(Init, 411 ConstantUInt::get(Type::UIntTy, i)); 412 assert(In && "Couldn't get element of initializer?"); 413 414 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false, 415 GlobalVariable::InternalLinkage, 416 In, GV->getName()+"."+utostr(i)); 417 Globals.insert(GV, NGV); 418 NewGlobals.push_back(NGV); 419 } 420 } 421 422 if (NewGlobals.empty()) 423 return 0; 424 425 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV); 426 427 Constant *NullInt = Constant::getNullValue(Type::IntTy); 428 429 // Loop over all of the uses of the global, replacing the constantexpr geps, 430 // with smaller constantexpr geps or direct references. 431 while (!GV->use_empty()) { 432 User *GEP = GV->use_back(); 433 assert(((isa<ConstantExpr>(GEP) && 434 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)|| 435 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!"); 436 437 // Ignore the 1th operand, which has to be zero or else the program is quite 438 // broken (undefined). Get the 2nd operand, which is the structure or array 439 // index. 440 unsigned Val = 441 (unsigned)cast<ConstantInt>(GEP->getOperand(2))->getRawValue(); 442 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access. 443 444 Value *NewPtr = NewGlobals[Val]; 445 446 // Form a shorter GEP if needed. 447 if (GEP->getNumOperands() > 3) 448 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) { 449 std::vector<Constant*> Idxs; 450 Idxs.push_back(NullInt); 451 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i) 452 Idxs.push_back(CE->getOperand(i)); 453 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs); 454 } else { 455 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP); 456 std::vector<Value*> Idxs; 457 Idxs.push_back(NullInt); 458 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i) 459 Idxs.push_back(GEPI->getOperand(i)); 460 NewPtr = new GetElementPtrInst(NewPtr, Idxs, 461 GEPI->getName()+"."+utostr(Val), GEPI); 462 } 463 GEP->replaceAllUsesWith(NewPtr); 464 465 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP)) 466 GEPI->eraseFromParent(); 467 else 468 cast<ConstantExpr>(GEP)->destroyConstant(); 469 } 470 471 // Delete the old global, now that it is dead. 472 Globals.erase(GV); 473 ++NumSRA; 474 475 // Loop over the new globals array deleting any globals that are obviously 476 // dead. This can arise due to scalarization of a structure or an array that 477 // has elements that are dead. 478 unsigned FirstGlobal = 0; 479 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i) 480 if (NewGlobals[i]->use_empty()) { 481 Globals.erase(NewGlobals[i]); 482 if (FirstGlobal == i) ++FirstGlobal; 483 } 484 485 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0; 486 } 487 488 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified 489 /// value will trap if the value is dynamically null. 490 static bool AllUsesOfValueWillTrapIfNull(Value *V) { 491 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI) 492 if (isa<LoadInst>(*UI)) { 493 // Will trap. 494 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) { 495 if (SI->getOperand(0) == V) { 496 //std::cerr << "NONTRAPPING USE: " << **UI; 497 return false; // Storing the value. 498 } 499 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) { 500 if (CI->getOperand(0) != V) { 501 //std::cerr << "NONTRAPPING USE: " << **UI; 502 return false; // Not calling the ptr 503 } 504 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) { 505 if (II->getOperand(0) != V) { 506 //std::cerr << "NONTRAPPING USE: " << **UI; 507 return false; // Not calling the ptr 508 } 509 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) { 510 if (!AllUsesOfValueWillTrapIfNull(CI)) return false; 511 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) { 512 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false; 513 } else if (isa<SetCondInst>(*UI) && 514 isa<ConstantPointerNull>(UI->getOperand(1))) { 515 // Ignore setcc X, null 516 } else { 517 //std::cerr << "NONTRAPPING USE: " << **UI; 518 return false; 519 } 520 return true; 521 } 522 523 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads 524 /// from GV will trap if the loaded value is null. Note that this also permits 525 /// comparisons of the loaded value against null, as a special case. 526 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) { 527 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI) 528 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) { 529 if (!AllUsesOfValueWillTrapIfNull(LI)) 530 return false; 531 } else if (isa<StoreInst>(*UI)) { 532 // Ignore stores to the global. 533 } else { 534 // We don't know or understand this user, bail out. 535 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI; 536 return false; 537 } 538 539 return true; 540 } 541 542 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) { 543 bool Changed = false; 544 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) { 545 Instruction *I = cast<Instruction>(*UI++); 546 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 547 LI->setOperand(0, NewV); 548 Changed = true; 549 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 550 if (SI->getOperand(1) == V) { 551 SI->setOperand(1, NewV); 552 Changed = true; 553 } 554 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) { 555 if (I->getOperand(0) == V) { 556 // Calling through the pointer! Turn into a direct call, but be careful 557 // that the pointer is not also being passed as an argument. 558 I->setOperand(0, NewV); 559 Changed = true; 560 bool PassedAsArg = false; 561 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i) 562 if (I->getOperand(i) == V) { 563 PassedAsArg = true; 564 I->setOperand(i, NewV); 565 } 566 567 if (PassedAsArg) { 568 // Being passed as an argument also. Be careful to not invalidate UI! 569 UI = V->use_begin(); 570 } 571 } 572 } else if (CastInst *CI = dyn_cast<CastInst>(I)) { 573 Changed |= OptimizeAwayTrappingUsesOfValue(CI, 574 ConstantExpr::getCast(NewV, CI->getType())); 575 if (CI->use_empty()) { 576 Changed = true; 577 CI->eraseFromParent(); 578 } 579 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { 580 // Should handle GEP here. 581 std::vector<Constant*> Indices; 582 Indices.reserve(GEPI->getNumOperands()-1); 583 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i) 584 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i))) 585 Indices.push_back(C); 586 else 587 break; 588 if (Indices.size() == GEPI->getNumOperands()-1) 589 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI, 590 ConstantExpr::getGetElementPtr(NewV, Indices)); 591 if (GEPI->use_empty()) { 592 Changed = true; 593 GEPI->eraseFromParent(); 594 } 595 } 596 } 597 598 return Changed; 599 } 600 601 602 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null 603 /// value stored into it. If there are uses of the loaded value that would trap 604 /// if the loaded value is dynamically null, then we know that they cannot be 605 /// reachable with a null optimize away the load. 606 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) { 607 std::vector<LoadInst*> Loads; 608 bool Changed = false; 609 610 // Replace all uses of loads with uses of uses of the stored value. 611 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); 612 GUI != E; ++GUI) 613 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) { 614 Loads.push_back(LI); 615 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV); 616 } else { 617 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!"); 618 } 619 620 if (Changed) { 621 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV); 622 ++NumGlobUses; 623 } 624 625 // Delete all of the loads we can, keeping track of whether we nuked them all! 626 bool AllLoadsGone = true; 627 while (!Loads.empty()) { 628 LoadInst *L = Loads.back(); 629 if (L->use_empty()) { 630 L->eraseFromParent(); 631 Changed = true; 632 } else { 633 AllLoadsGone = false; 634 } 635 Loads.pop_back(); 636 } 637 638 // If we nuked all of the loads, then none of the stores are needed either, 639 // nor is the global. 640 if (AllLoadsGone) { 641 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n"); 642 CleanupConstantGlobalUsers(GV, 0); 643 if (GV->use_empty()) { 644 GV->eraseFromParent(); 645 ++NumDeleted; 646 } 647 Changed = true; 648 } 649 return Changed; 650 } 651 652 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the 653 /// instructions that are foldable. 654 static void ConstantPropUsersOf(Value *V) { 655 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) 656 if (Instruction *I = dyn_cast<Instruction>(*UI++)) 657 if (Constant *NewC = ConstantFoldInstruction(I)) { 658 I->replaceAllUsesWith(NewC); 659 660 // Advance UI to the next non-I use to avoid invalidating it! 661 // Instructions could multiply use V. 662 while (UI != E && *UI == I) 663 ++UI; 664 I->eraseFromParent(); 665 } 666 } 667 668 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global 669 /// variable, and transforms the program as if it always contained the result of 670 /// the specified malloc. Because it is always the result of the specified 671 /// malloc, there is no reason to actually DO the malloc. Instead, turn the 672 /// malloc into a global, and any laods of GV as uses of the new global. 673 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, 674 MallocInst *MI) { 675 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI); 676 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize()); 677 678 if (NElements->getRawValue() != 1) { 679 // If we have an array allocation, transform it to a single element 680 // allocation to make the code below simpler. 681 Type *NewTy = ArrayType::get(MI->getAllocatedType(), 682 (unsigned)NElements->getRawValue()); 683 MallocInst *NewMI = 684 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy), 685 MI->getName(), MI); 686 std::vector<Value*> Indices; 687 Indices.push_back(Constant::getNullValue(Type::IntTy)); 688 Indices.push_back(Indices[0]); 689 Value *NewGEP = new GetElementPtrInst(NewMI, Indices, 690 NewMI->getName()+".el0", MI); 691 MI->replaceAllUsesWith(NewGEP); 692 MI->eraseFromParent(); 693 MI = NewMI; 694 } 695 696 // Create the new global variable. The contents of the malloc'd memory is 697 // undefined, so initialize with an undef value. 698 Constant *Init = UndefValue::get(MI->getAllocatedType()); 699 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false, 700 GlobalValue::InternalLinkage, Init, 701 GV->getName()+".body"); 702 GV->getParent()->getGlobalList().insert(GV, NewGV); 703 704 // Anything that used the malloc now uses the global directly. 705 MI->replaceAllUsesWith(NewGV); 706 707 Constant *RepValue = NewGV; 708 if (NewGV->getType() != GV->getType()->getElementType()) 709 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType()); 710 711 // If there is a comparison against null, we will insert a global bool to 712 // keep track of whether the global was initialized yet or not. 713 GlobalVariable *InitBool = 714 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage, 715 ConstantBool::False, GV->getName()+".init"); 716 bool InitBoolUsed = false; 717 718 // Loop over all uses of GV, processing them in turn. 719 std::vector<StoreInst*> Stores; 720 while (!GV->use_empty()) 721 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) { 722 while (!LI->use_empty()) { 723 Use &LoadUse = LI->use_begin().getUse(); 724 if (!isa<SetCondInst>(LoadUse.getUser())) 725 LoadUse = RepValue; 726 else { 727 // Replace the setcc X, 0 with a use of the bool value. 728 SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser()); 729 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI); 730 InitBoolUsed = true; 731 switch (SCI->getOpcode()) { 732 default: assert(0 && "Unknown opcode!"); 733 case Instruction::SetLT: 734 LV = ConstantBool::False; // X < null -> always false 735 break; 736 case Instruction::SetEQ: 737 case Instruction::SetLE: 738 LV = BinaryOperator::createNot(LV, "notinit", SCI); 739 break; 740 case Instruction::SetNE: 741 case Instruction::SetGE: 742 case Instruction::SetGT: 743 break; // no change. 744 } 745 SCI->replaceAllUsesWith(LV); 746 SCI->eraseFromParent(); 747 } 748 } 749 LI->eraseFromParent(); 750 } else { 751 StoreInst *SI = cast<StoreInst>(GV->use_back()); 752 // The global is initialized when the store to it occurs. 753 new StoreInst(ConstantBool::True, InitBool, SI); 754 SI->eraseFromParent(); 755 } 756 757 // If the initialization boolean was used, insert it, otherwise delete it. 758 if (!InitBoolUsed) { 759 while (!InitBool->use_empty()) // Delete initializations 760 cast<Instruction>(InitBool->use_back())->eraseFromParent(); 761 delete InitBool; 762 } else 763 GV->getParent()->getGlobalList().insert(GV, InitBool); 764 765 766 // Now the GV is dead, nuke it and the malloc. 767 GV->eraseFromParent(); 768 MI->eraseFromParent(); 769 770 // To further other optimizations, loop over all users of NewGV and try to 771 // constant prop them. This will promote GEP instructions with constant 772 // indices into GEP constant-exprs, which will allow global-opt to hack on it. 773 ConstantPropUsersOf(NewGV); 774 if (RepValue != NewGV) 775 ConstantPropUsersOf(RepValue); 776 777 return NewGV; 778 } 779 780 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking 781 /// to make sure that there are no complex uses of V. We permit simple things 782 /// like dereferencing the pointer, but not storing through the address, unless 783 /// it is to the specified global. 784 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V, 785 GlobalVariable *GV) { 786 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI) 787 if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) { 788 // Fine, ignore. 789 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) { 790 if (SI->getOperand(0) == V && SI->getOperand(1) != GV) 791 return false; // Storing the pointer itself... bad. 792 // Otherwise, storing through it, or storing into GV... fine. 793 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) { 794 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV)) 795 return false; 796 } else { 797 return false; 798 } 799 return true; 800 801 } 802 803 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge 804 // that only one value (besides its initializer) is ever stored to the global. 805 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, 806 Module::global_iterator &GVI, TargetData &TD) { 807 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal)) 808 StoredOnceVal = CI->getOperand(0); 809 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){ 810 // "getelementptr Ptr, 0, 0, 0" is really just a cast. 811 bool IsJustACast = true; 812 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i) 813 if (!isa<Constant>(GEPI->getOperand(i)) || 814 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) { 815 IsJustACast = false; 816 break; 817 } 818 if (IsJustACast) 819 StoredOnceVal = GEPI->getOperand(0); 820 } 821 822 // If we are dealing with a pointer global that is initialized to null and 823 // only has one (non-null) value stored into it, then we can optimize any 824 // users of the loaded value (often calls and loads) that would trap if the 825 // value was null. 826 if (isa<PointerType>(GV->getInitializer()->getType()) && 827 GV->getInitializer()->isNullValue()) { 828 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) { 829 if (GV->getInitializer()->getType() != SOVC->getType()) 830 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType()); 831 832 // Optimize away any trapping uses of the loaded value. 833 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC)) 834 return true; 835 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) { 836 // If we have a global that is only initialized with a fixed size malloc, 837 // and if all users of the malloc trap, and if the malloc'd address is not 838 // put anywhere else, transform the program to use global memory instead 839 // of malloc'd memory. This eliminates dynamic allocation (good) and 840 // exposes the resultant global to further GlobalOpt (even better). Note 841 // that we restrict this transformation to only working on small 842 // allocations (2048 bytes currently), as we don't want to introduce a 16M 843 // global or something. 844 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) 845 if (MI->getAllocatedType()->isSized() && 846 NElements->getRawValue()* 847 TD.getTypeSize(MI->getAllocatedType()) < 2048 && 848 AllUsesOfLoadedValueWillTrapIfNull(GV) && 849 ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV)) { 850 GVI = OptimizeGlobalAddressOfMalloc(GV, MI); 851 return true; 852 } 853 } 854 } 855 856 return false; 857 } 858 859 /// ShrinkGlobalToBoolean - At this point, we have learned that the only two 860 /// values ever stored into GV are its initializer and OtherVal. 861 static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) { 862 // Create the new global, initializing it to false. 863 GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false, 864 GlobalValue::InternalLinkage, ConstantBool::False, GV->getName()+".b"); 865 GV->getParent()->getGlobalList().insert(GV, NewGV); 866 867 Constant *InitVal = GV->getInitializer(); 868 assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!"); 869 870 // If initialized to zero and storing one into the global, we can use a cast 871 // instead of a select to synthesize the desired value. 872 bool IsOneZero = false; 873 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) 874 IsOneZero = InitVal->isNullValue() && CI->equalsInt(1); 875 876 while (!GV->use_empty()) { 877 Instruction *UI = cast<Instruction>(GV->use_back()); 878 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) { 879 // Change the store into a boolean store. 880 bool StoringOther = SI->getOperand(0) == OtherVal; 881 // Only do this if we weren't storing a loaded value. 882 Value *StoreVal; 883 if (StoringOther || SI->getOperand(0) == InitVal) 884 StoreVal = ConstantBool::get(StoringOther); 885 else { 886 // Otherwise, we are storing a previously loaded copy. To do this, 887 // change the copy from copying the original value to just copying the 888 // bool. 889 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0)); 890 891 // If we're already replaced the input, StoredVal will be a cast or 892 // select instruction. If not, it will be a load of the original 893 // global. 894 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) { 895 assert(LI->getOperand(0) == GV && "Not a copy!"); 896 // Insert a new load, to preserve the saved value. 897 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI); 898 } else { 899 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) && 900 "This is not a form that we understand!"); 901 StoreVal = StoredVal->getOperand(0); 902 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!"); 903 } 904 } 905 new StoreInst(StoreVal, NewGV, SI); 906 } else if (!UI->use_empty()) { 907 // Change the load into a load of bool then a select. 908 LoadInst *LI = cast<LoadInst>(UI); 909 910 std::string Name = LI->getName(); LI->setName(""); 911 LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI); 912 Value *NSI; 913 if (IsOneZero) 914 NSI = new CastInst(NLI, LI->getType(), Name, LI); 915 else 916 NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI); 917 LI->replaceAllUsesWith(NSI); 918 } 919 UI->eraseFromParent(); 920 } 921 922 GV->eraseFromParent(); 923 } 924 925 926 /// ProcessInternalGlobal - Analyze the specified global variable and optimize 927 /// it if possible. If we make a change, return true. 928 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV, 929 Module::global_iterator &GVI) { 930 std::set<PHINode*> PHIUsers; 931 GlobalStatus GS; 932 PHIUsers.clear(); 933 GV->removeDeadConstantUsers(); 934 935 if (GV->use_empty()) { 936 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV); 937 GV->eraseFromParent(); 938 ++NumDeleted; 939 return true; 940 } 941 942 if (!AnalyzeGlobal(GV, GS, PHIUsers)) { 943 // If this is a first class global and has only one accessing function 944 // and this function is main (which we know is not recursive we can make 945 // this global a local variable) we replace the global with a local alloca 946 // in this function. 947 // 948 // NOTE: It doesn't make sense to promote non first class types since we 949 // are just replacing static memory to stack memory. 950 if (!GS.HasMultipleAccessingFunctions && 951 GS.AccessingFunction && !GS.HasNonInstructionUser && 952 GV->getType()->getElementType()->isFirstClassType() && 953 GS.AccessingFunction->getName() == "main" && 954 GS.AccessingFunction->hasExternalLinkage()) { 955 DEBUG(std::cerr << "LOCALIZING GLOBAL: " << *GV); 956 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin(); 957 const Type* ElemTy = GV->getType()->getElementType(); 958 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI); 959 if (!isa<UndefValue>(GV->getInitializer())) 960 new StoreInst(GV->getInitializer(), Alloca, FirstI); 961 962 GV->replaceAllUsesWith(Alloca); 963 GV->eraseFromParent(); 964 ++NumLocalized; 965 return true; 966 } 967 // If the global is never loaded (but may be stored to), it is dead. 968 // Delete it now. 969 if (!GS.isLoaded) { 970 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV); 971 972 // Delete any stores we can find to the global. We may not be able to 973 // make it completely dead though. 974 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer()); 975 976 // If the global is dead now, delete it. 977 if (GV->use_empty()) { 978 GV->eraseFromParent(); 979 ++NumDeleted; 980 Changed = true; 981 } 982 return Changed; 983 984 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) { 985 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV); 986 GV->setConstant(true); 987 988 // Clean up any obviously simplifiable users now. 989 CleanupConstantGlobalUsers(GV, GV->getInitializer()); 990 991 // If the global is dead now, just nuke it. 992 if (GV->use_empty()) { 993 DEBUG(std::cerr << " *** Marking constant allowed us to simplify " 994 "all users and delete global!\n"); 995 GV->eraseFromParent(); 996 ++NumDeleted; 997 } 998 999 ++NumMarked; 1000 return true; 1001 } else if (!GS.isNotSuitableForSRA && 1002 !GV->getInitializer()->getType()->isFirstClassType()) { 1003 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) { 1004 GVI = FirstNewGV; // Don't skip the newly produced globals! 1005 return true; 1006 } 1007 } else if (GS.StoredType == GlobalStatus::isStoredOnce) { 1008 // If the initial value for the global was an undef value, and if only 1009 // one other value was stored into it, we can just change the 1010 // initializer to be an undef value, then delete all stores to the 1011 // global. This allows us to mark it constant. 1012 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) 1013 if (isa<UndefValue>(GV->getInitializer())) { 1014 // Change the initial value here. 1015 GV->setInitializer(SOVConstant); 1016 1017 // Clean up any obviously simplifiable users now. 1018 CleanupConstantGlobalUsers(GV, GV->getInitializer()); 1019 1020 if (GV->use_empty()) { 1021 DEBUG(std::cerr << " *** Substituting initializer allowed us to " 1022 "simplify all users and delete global!\n"); 1023 GV->eraseFromParent(); 1024 ++NumDeleted; 1025 } else { 1026 GVI = GV; 1027 } 1028 ++NumSubstitute; 1029 return true; 1030 } 1031 1032 // Try to optimize globals based on the knowledge that only one value 1033 // (besides its initializer) is ever stored to the global. 1034 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI, 1035 getAnalysis<TargetData>())) 1036 return true; 1037 1038 // Otherwise, if the global was not a boolean, we can shrink it to be a 1039 // boolean. 1040 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) 1041 if (GV->getType()->getElementType() != Type::BoolTy && 1042 !GV->getType()->getElementType()->isFloatingPoint()) { 1043 DEBUG(std::cerr << " *** SHRINKING TO BOOL: " << *GV); 1044 ShrinkGlobalToBoolean(GV, SOVConstant); 1045 ++NumShrunkToBool; 1046 return true; 1047 } 1048 } 1049 } 1050 return false; 1051 } 1052 1053 /// OnlyCalledDirectly - Return true if the specified function is only called 1054 /// directly. In other words, its address is never taken. 1055 static bool OnlyCalledDirectly(Function *F) { 1056 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){ 1057 Instruction *User = dyn_cast<Instruction>(*UI); 1058 if (!User) return false; 1059 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false; 1060 1061 // See if the function address is passed as an argument. 1062 for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i) 1063 if (User->getOperand(i) == F) return false; 1064 } 1065 return true; 1066 } 1067 1068 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified 1069 /// function, changing them to FastCC. 1070 static void ChangeCalleesToFastCall(Function *F) { 1071 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){ 1072 Instruction *User = cast<Instruction>(*UI); 1073 if (CallInst *CI = dyn_cast<CallInst>(User)) 1074 CI->setCallingConv(CallingConv::Fast); 1075 else 1076 cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast); 1077 } 1078 } 1079 1080 bool GlobalOpt::runOnModule(Module &M) { 1081 bool Changed = false; 1082 1083 // As a prepass, delete functions that are trivially dead. 1084 bool LocalChange = true; 1085 while (LocalChange) { 1086 LocalChange = false; 1087 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) { 1088 Function *F = FI++; 1089 F->removeDeadConstantUsers(); 1090 if (F->use_empty() && (F->hasInternalLinkage() || 1091 F->hasLinkOnceLinkage())) { 1092 M.getFunctionList().erase(F); 1093 LocalChange = true; 1094 ++NumFnDeleted; 1095 } else if (F->hasInternalLinkage() && 1096 F->getCallingConv() == CallingConv::C && !F->isVarArg() && 1097 OnlyCalledDirectly(F)) { 1098 // If this function has C calling conventions, is not a varargs 1099 // function, and is only called directly, promote it to use the Fast 1100 // calling convention. 1101 F->setCallingConv(CallingConv::Fast); 1102 ChangeCalleesToFastCall(F); 1103 ++NumFastCallFns; 1104 LocalChange = true; 1105 } 1106 } 1107 Changed |= LocalChange; 1108 } 1109 1110 LocalChange = true; 1111 while (LocalChange) { 1112 LocalChange = false; 1113 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end(); 1114 GVI != E; ) { 1115 GlobalVariable *GV = GVI++; 1116 if (!GV->isConstant() && GV->hasInternalLinkage() && 1117 GV->hasInitializer()) 1118 LocalChange |= ProcessInternalGlobal(GV, GVI); 1119 } 1120 Changed |= LocalChange; 1121 } 1122 return Changed; 1123 } 1124