1 //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===// 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 file defines the PassManagerBuilder class, which is used to set up a 11 // "standard" optimization sequence suitable for languages like C and C++. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 16 #include "llvm-c/Transforms/PassManagerBuilder.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Analysis/BasicAliasAnalysis.h" 19 #include "llvm/Analysis/CFLAndersAliasAnalysis.h" 20 #include "llvm/Analysis/CFLSteensAliasAnalysis.h" 21 #include "llvm/Analysis/GlobalsModRef.h" 22 #include "llvm/Analysis/InlineCost.h" 23 #include "llvm/Analysis/Passes.h" 24 #include "llvm/Analysis/ScopedNoAliasAA.h" 25 #include "llvm/Analysis/TargetLibraryInfo.h" 26 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/LegacyPassManager.h" 29 #include "llvm/IR/ModuleSummaryIndex.h" 30 #include "llvm/IR/Verifier.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/ManagedStatic.h" 33 #include "llvm/Target/TargetMachine.h" 34 #include "llvm/Transforms/IPO.h" 35 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h" 36 #include "llvm/Transforms/IPO/FunctionAttrs.h" 37 #include "llvm/Transforms/IPO/InferFunctionAttrs.h" 38 #include "llvm/Transforms/Instrumentation.h" 39 #include "llvm/Transforms/Scalar.h" 40 #include "llvm/Transforms/Scalar/GVN.h" 41 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" 42 #include "llvm/Transforms/Vectorize.h" 43 44 using namespace llvm; 45 46 static cl::opt<bool> 47 RunLoopVectorization("vectorize-loops", cl::Hidden, 48 cl::desc("Run the Loop vectorization passes")); 49 50 static cl::opt<bool> 51 RunSLPVectorization("vectorize-slp", cl::Hidden, 52 cl::desc("Run the SLP vectorization passes")); 53 54 static cl::opt<bool> 55 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden, 56 cl::desc("Run the BB vectorization passes")); 57 58 static cl::opt<bool> 59 UseGVNAfterVectorization("use-gvn-after-vectorization", 60 cl::init(false), cl::Hidden, 61 cl::desc("Run GVN instead of Early CSE after vectorization passes")); 62 63 static cl::opt<bool> ExtraVectorizerPasses( 64 "extra-vectorizer-passes", cl::init(false), cl::Hidden, 65 cl::desc("Run cleanup optimization passes after vectorization.")); 66 67 static cl::opt<bool> 68 RunLoopRerolling("reroll-loops", cl::Hidden, 69 cl::desc("Run the loop rerolling pass")); 70 71 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false), 72 cl::Hidden, 73 cl::desc("Run the load combining pass")); 74 75 static cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden, 76 cl::desc("Run the NewGVN pass")); 77 78 static cl::opt<bool> 79 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization", 80 cl::init(true), cl::Hidden, 81 cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop " 82 "vectorizer instead of before")); 83 84 // Experimental option to use CFL-AA 85 enum class CFLAAType { None, Steensgaard, Andersen, Both }; 86 static cl::opt<CFLAAType> 87 UseCFLAA("use-cfl-aa", cl::init(CFLAAType::None), cl::Hidden, 88 cl::desc("Enable the new, experimental CFL alias analysis"), 89 cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"), 90 clEnumValN(CFLAAType::Steensgaard, "steens", 91 "Enable unification-based CFL-AA"), 92 clEnumValN(CFLAAType::Andersen, "anders", 93 "Enable inclusion-based CFL-AA"), 94 clEnumValN(CFLAAType::Both, "both", 95 "Enable both variants of CFL-AA"))); 96 97 static cl::opt<bool> EnableLoopInterchange( 98 "enable-loopinterchange", cl::init(false), cl::Hidden, 99 cl::desc("Enable the new, experimental LoopInterchange Pass")); 100 101 static cl::opt<bool> EnableNonLTOGlobalsModRef( 102 "enable-non-lto-gmr", cl::init(true), cl::Hidden, 103 cl::desc( 104 "Enable the GlobalsModRef AliasAnalysis outside of the LTO pipeline.")); 105 106 static cl::opt<bool> EnableLoopLoadElim( 107 "enable-loop-load-elim", cl::init(true), cl::Hidden, 108 cl::desc("Enable the LoopLoadElimination Pass")); 109 110 static cl::opt<bool> 111 EnablePrepareForThinLTO("prepare-for-thinlto", cl::init(false), cl::Hidden, 112 cl::desc("Enable preparation for ThinLTO.")); 113 114 static cl::opt<bool> RunPGOInstrGen( 115 "profile-generate", cl::init(false), cl::Hidden, 116 cl::desc("Enable PGO instrumentation.")); 117 118 static cl::opt<std::string> 119 PGOOutputFile("profile-generate-file", cl::init(""), cl::Hidden, 120 cl::desc("Specify the path of profile data file.")); 121 122 static cl::opt<std::string> RunPGOInstrUse( 123 "profile-use", cl::init(""), cl::Hidden, cl::value_desc("filename"), 124 cl::desc("Enable use phase of PGO instrumentation and specify the path " 125 "of profile data file")); 126 127 static cl::opt<bool> UseLoopVersioningLICM( 128 "enable-loop-versioning-licm", cl::init(false), cl::Hidden, 129 cl::desc("Enable the experimental Loop Versioning LICM pass")); 130 131 static cl::opt<bool> 132 DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden, 133 cl::desc("Disable pre-instrumentation inliner")); 134 135 static cl::opt<int> PreInlineThreshold( 136 "preinline-threshold", cl::Hidden, cl::init(75), cl::ZeroOrMore, 137 cl::desc("Control the amount of inlining in pre-instrumentation inliner " 138 "(default = 75)")); 139 140 static cl::opt<bool> EnableGVNHoist( 141 "enable-gvn-hoist", cl::init(false), cl::Hidden, 142 cl::desc("Enable the GVN hoisting pass (default = off)")); 143 144 static cl::opt<bool> 145 DisableLibCallsShrinkWrap("disable-libcalls-shrinkwrap", cl::init(false), 146 cl::Hidden, 147 cl::desc("Disable shrink-wrap library calls")); 148 149 static cl::opt<bool> 150 EnableSimpleLoopUnswitch("enable-simple-loop-unswitch", cl::init(false), 151 cl::Hidden, 152 cl::desc("Enable the simple loop unswitch pass.")); 153 154 PassManagerBuilder::PassManagerBuilder() { 155 OptLevel = 2; 156 SizeLevel = 0; 157 LibraryInfo = nullptr; 158 Inliner = nullptr; 159 DisableUnitAtATime = false; 160 DisableUnrollLoops = false; 161 BBVectorize = RunBBVectorization; 162 SLPVectorize = RunSLPVectorization; 163 LoopVectorize = RunLoopVectorization; 164 RerollLoops = RunLoopRerolling; 165 LoadCombine = RunLoadCombine; 166 NewGVN = RunNewGVN; 167 DisableGVNLoadPRE = false; 168 VerifyInput = false; 169 VerifyOutput = false; 170 MergeFunctions = false; 171 PrepareForLTO = false; 172 EnablePGOInstrGen = RunPGOInstrGen; 173 PGOInstrGen = PGOOutputFile; 174 PGOInstrUse = RunPGOInstrUse; 175 PrepareForThinLTO = EnablePrepareForThinLTO; 176 PerformThinLTO = false; 177 DivergentTarget = false; 178 } 179 180 PassManagerBuilder::~PassManagerBuilder() { 181 delete LibraryInfo; 182 delete Inliner; 183 } 184 185 /// Set of global extensions, automatically added as part of the standard set. 186 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy, 187 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions; 188 189 void PassManagerBuilder::addGlobalExtension( 190 PassManagerBuilder::ExtensionPointTy Ty, 191 PassManagerBuilder::ExtensionFn Fn) { 192 GlobalExtensions->push_back(std::make_pair(Ty, std::move(Fn))); 193 } 194 195 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) { 196 Extensions.push_back(std::make_pair(Ty, std::move(Fn))); 197 } 198 199 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy, 200 legacy::PassManagerBase &PM) const { 201 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i) 202 if ((*GlobalExtensions)[i].first == ETy) 203 (*GlobalExtensions)[i].second(*this, PM); 204 for (unsigned i = 0, e = Extensions.size(); i != e; ++i) 205 if (Extensions[i].first == ETy) 206 Extensions[i].second(*this, PM); 207 } 208 209 void PassManagerBuilder::addInitialAliasAnalysisPasses( 210 legacy::PassManagerBase &PM) const { 211 switch (UseCFLAA) { 212 case CFLAAType::Steensgaard: 213 PM.add(createCFLSteensAAWrapperPass()); 214 break; 215 case CFLAAType::Andersen: 216 PM.add(createCFLAndersAAWrapperPass()); 217 break; 218 case CFLAAType::Both: 219 PM.add(createCFLSteensAAWrapperPass()); 220 PM.add(createCFLAndersAAWrapperPass()); 221 break; 222 default: 223 break; 224 } 225 226 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that 227 // BasicAliasAnalysis wins if they disagree. This is intended to help 228 // support "obvious" type-punning idioms. 229 PM.add(createTypeBasedAAWrapperPass()); 230 PM.add(createScopedNoAliasAAWrapperPass()); 231 } 232 233 void PassManagerBuilder::addInstructionCombiningPass( 234 legacy::PassManagerBase &PM) const { 235 bool ExpensiveCombines = OptLevel > 2; 236 PM.add(createInstructionCombiningPass(ExpensiveCombines)); 237 } 238 239 void PassManagerBuilder::populateFunctionPassManager( 240 legacy::FunctionPassManager &FPM) { 241 addExtensionsToPM(EP_EarlyAsPossible, FPM); 242 243 // Add LibraryInfo if we have some. 244 if (LibraryInfo) 245 FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 246 247 if (OptLevel == 0) return; 248 249 addInitialAliasAnalysisPasses(FPM); 250 251 FPM.add(createCFGSimplificationPass()); 252 FPM.add(createSROAPass()); 253 FPM.add(createEarlyCSEPass()); 254 FPM.add(createLowerExpectIntrinsicPass()); 255 } 256 257 // Do PGO instrumentation generation or use pass as the option specified. 258 void PassManagerBuilder::addPGOInstrPasses(legacy::PassManagerBase &MPM) { 259 if (!EnablePGOInstrGen && PGOInstrUse.empty()) 260 return; 261 // Perform the preinline and cleanup passes for O1 and above. 262 // And avoid doing them if optimizing for size. 263 if (OptLevel > 0 && SizeLevel == 0 && !DisablePreInliner) { 264 // Create preinline pass. We construct an InlineParams object and specify 265 // the threshold here to avoid the command line options of the regular 266 // inliner to influence pre-inlining. The only fields of InlineParams we 267 // care about are DefaultThreshold and HintThreshold. 268 InlineParams IP; 269 IP.DefaultThreshold = PreInlineThreshold; 270 // FIXME: The hint threshold has the same value used by the regular inliner. 271 // This should probably be lowered after performance testing. 272 IP.HintThreshold = 325; 273 274 MPM.add(createFunctionInliningPass(IP)); 275 MPM.add(createSROAPass()); 276 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies 277 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs 278 MPM.add(createInstructionCombiningPass()); // Combine silly seq's 279 addExtensionsToPM(EP_Peephole, MPM); 280 } 281 if (EnablePGOInstrGen) { 282 MPM.add(createPGOInstrumentationGenLegacyPass()); 283 // Add the profile lowering pass. 284 InstrProfOptions Options; 285 if (!PGOInstrGen.empty()) 286 Options.InstrProfileOutput = PGOInstrGen; 287 MPM.add(createInstrProfilingLegacyPass(Options)); 288 } 289 if (!PGOInstrUse.empty()) 290 MPM.add(createPGOInstrumentationUseLegacyPass(PGOInstrUse)); 291 // Indirect call promotion that promotes intra-module targets only. 292 // For ThinLTO this is done earlier due to interactions with globalopt 293 // for imported functions. We don't run this at -O0. 294 if (OptLevel > 0) 295 MPM.add( 296 createPGOIndirectCallPromotionLegacyPass(false, !PGOSampleUse.empty())); 297 } 298 void PassManagerBuilder::addFunctionSimplificationPasses( 299 legacy::PassManagerBase &MPM) { 300 // Start of function pass. 301 // Break up aggregate allocas, using SSAUpdater. 302 MPM.add(createSROAPass()); 303 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies 304 if (EnableGVNHoist) 305 MPM.add(createGVNHoistPass()); 306 // Speculative execution if the target has divergent branches; otherwise nop. 307 MPM.add(createSpeculativeExecutionIfHasBranchDivergencePass()); 308 MPM.add(createJumpThreadingPass()); // Thread jumps. 309 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals 310 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs 311 // Combine silly seq's 312 addInstructionCombiningPass(MPM); 313 if (SizeLevel == 0 && !DisableLibCallsShrinkWrap) 314 MPM.add(createLibCallsShrinkWrapPass()); 315 addExtensionsToPM(EP_Peephole, MPM); 316 317 // Optimize memory intrinsic calls based on the profiled size information. 318 if (SizeLevel == 0) 319 MPM.add(createPGOMemOPSizeOptLegacyPass()); 320 321 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls 322 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs 323 MPM.add(createReassociatePass()); // Reassociate expressions 324 // Rotate Loop - disable header duplication at -Oz 325 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1)); 326 MPM.add(createLICMPass()); // Hoist loop invariants 327 if (EnableSimpleLoopUnswitch) 328 MPM.add(createSimpleLoopUnswitchLegacyPass()); 329 else 330 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget)); 331 MPM.add(createCFGSimplificationPass()); 332 addInstructionCombiningPass(MPM); 333 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars 334 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset. 335 addExtensionsToPM(EP_LateLoopOptimizations, MPM); 336 MPM.add(createLoopDeletionPass()); // Delete dead loops 337 338 if (EnableLoopInterchange) { 339 MPM.add(createLoopInterchangePass()); // Interchange loops 340 MPM.add(createCFGSimplificationPass()); 341 } 342 if (!DisableUnrollLoops) 343 MPM.add(createSimpleLoopUnrollPass(OptLevel)); // Unroll small loops 344 addExtensionsToPM(EP_LoopOptimizerEnd, MPM); 345 346 if (OptLevel > 1) { 347 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds 348 MPM.add(NewGVN ? createNewGVNPass() 349 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies 350 } 351 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset 352 MPM.add(createSCCPPass()); // Constant prop with SCCP 353 354 // Delete dead bit computations (instcombine runs after to fold away the dead 355 // computations, and then ADCE will run later to exploit any new DCE 356 // opportunities that creates). 357 MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations 358 359 // Run instcombine after redundancy elimination to exploit opportunities 360 // opened up by them. 361 addInstructionCombiningPass(MPM); 362 addExtensionsToPM(EP_Peephole, MPM); 363 MPM.add(createJumpThreadingPass()); // Thread jumps 364 MPM.add(createCorrelatedValuePropagationPass()); 365 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores 366 MPM.add(createLICMPass()); 367 368 addExtensionsToPM(EP_ScalarOptimizerLate, MPM); 369 370 if (RerollLoops) 371 MPM.add(createLoopRerollPass()); 372 if (!RunSLPAfterLoopVectorization) { 373 if (SLPVectorize) 374 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains. 375 376 if (BBVectorize) { 377 MPM.add(createBBVectorizePass()); 378 addInstructionCombiningPass(MPM); 379 addExtensionsToPM(EP_Peephole, MPM); 380 if (OptLevel > 1 && UseGVNAfterVectorization) 381 MPM.add(NewGVN 382 ? createNewGVNPass() 383 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies 384 else 385 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies 386 387 // BBVectorize may have significantly shortened a loop body; unroll again. 388 if (!DisableUnrollLoops) 389 MPM.add(createLoopUnrollPass(OptLevel)); 390 } 391 } 392 393 if (LoadCombine) 394 MPM.add(createLoadCombinePass()); 395 396 MPM.add(createAggressiveDCEPass()); // Delete dead instructions 397 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs 398 // Clean up after everything. 399 addInstructionCombiningPass(MPM); 400 addExtensionsToPM(EP_Peephole, MPM); 401 } 402 403 void PassManagerBuilder::populateModulePassManager( 404 legacy::PassManagerBase &MPM) { 405 if (!PGOSampleUse.empty()) { 406 MPM.add(createPruneEHPass()); 407 MPM.add(createSampleProfileLoaderPass(PGOSampleUse)); 408 } 409 410 // Allow forcing function attributes as a debugging and tuning aid. 411 MPM.add(createForceFunctionAttrsLegacyPass()); 412 413 // If all optimizations are disabled, just run the always-inline pass and, 414 // if enabled, the function merging pass. 415 if (OptLevel == 0) { 416 addPGOInstrPasses(MPM); 417 if (Inliner) { 418 MPM.add(Inliner); 419 Inliner = nullptr; 420 } 421 422 // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly 423 // creates a CGSCC pass manager, but we don't want to add extensions into 424 // that pass manager. To prevent this we insert a no-op module pass to reset 425 // the pass manager to get the same behavior as EP_OptimizerLast in non-O0 426 // builds. The function merging pass is 427 if (MergeFunctions) 428 MPM.add(createMergeFunctionsPass()); 429 else if (!GlobalExtensions->empty() || !Extensions.empty()) 430 MPM.add(createBarrierNoopPass()); 431 432 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM); 433 434 // Rename anon globals to be able to export them in the summary. 435 // This has to be done after we add the extensions to the pass manager 436 // as there could be passes (e.g. Adddress sanitizer) which introduce 437 // new unnamed globals. 438 if (PrepareForThinLTO) 439 MPM.add(createNameAnonGlobalPass()); 440 return; 441 } 442 443 // Add LibraryInfo if we have some. 444 if (LibraryInfo) 445 MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 446 447 addInitialAliasAnalysisPasses(MPM); 448 449 // For ThinLTO there are two passes of indirect call promotion. The 450 // first is during the compile phase when PerformThinLTO=false and 451 // intra-module indirect call targets are promoted. The second is during 452 // the ThinLTO backend when PerformThinLTO=true, when we promote imported 453 // inter-module indirect calls. For that we perform indirect call promotion 454 // earlier in the pass pipeline, here before globalopt. Otherwise imported 455 // available_externally functions look unreferenced and are removed. 456 if (PerformThinLTO) 457 MPM.add(createPGOIndirectCallPromotionLegacyPass(/*InLTO = */ true, 458 !PGOSampleUse.empty())); 459 460 // For SamplePGO in ThinLTO compile phase, we do not want to unroll loops 461 // as it will change the CFG too much to make the 2nd profile annotation 462 // in backend more difficult. 463 bool PrepareForThinLTOUsingPGOSampleProfile = 464 PrepareForThinLTO && !PGOSampleUse.empty(); 465 if (PrepareForThinLTOUsingPGOSampleProfile) 466 DisableUnrollLoops = true; 467 468 if (!DisableUnitAtATime) { 469 // Infer attributes about declarations if possible. 470 MPM.add(createInferFunctionAttrsLegacyPass()); 471 472 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM); 473 474 MPM.add(createIPSCCPPass()); // IP SCCP 475 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars 476 // Promote any localized global vars. 477 MPM.add(createPromoteMemoryToRegisterPass()); 478 479 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination 480 481 addInstructionCombiningPass(MPM); // Clean up after IPCP & DAE 482 addExtensionsToPM(EP_Peephole, MPM); 483 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE 484 } 485 486 // For SamplePGO in ThinLTO compile phase, we do not want to do indirect 487 // call promotion as it will change the CFG too much to make the 2nd 488 // profile annotation in backend more difficult. 489 // PGO instrumentation is added during the compile phase for ThinLTO, do 490 // not run it a second time 491 if (!PerformThinLTO && !PrepareForThinLTOUsingPGOSampleProfile) 492 addPGOInstrPasses(MPM); 493 494 if (EnableNonLTOGlobalsModRef) 495 // We add a module alias analysis pass here. In part due to bugs in the 496 // analysis infrastructure this "works" in that the analysis stays alive 497 // for the entire SCC pass run below. 498 MPM.add(createGlobalsAAWrapperPass()); 499 500 // Start of CallGraph SCC passes. 501 if (!DisableUnitAtATime) 502 MPM.add(createPruneEHPass()); // Remove dead EH info 503 if (Inliner) { 504 MPM.add(Inliner); 505 Inliner = nullptr; 506 } 507 if (!DisableUnitAtATime) 508 MPM.add(createPostOrderFunctionAttrsLegacyPass()); 509 if (OptLevel > 2) 510 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args 511 512 addExtensionsToPM(EP_CGSCCOptimizerLate, MPM); 513 addFunctionSimplificationPasses(MPM); 514 515 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC 516 // pass manager that we are specifically trying to avoid. To prevent this 517 // we must insert a no-op module pass to reset the pass manager. 518 MPM.add(createBarrierNoopPass()); 519 520 if (!DisableUnitAtATime && OptLevel > 1 && !PrepareForLTO && 521 !PrepareForThinLTO) 522 // Remove avail extern fns and globals definitions if we aren't 523 // compiling an object file for later LTO. For LTO we want to preserve 524 // these so they are eligible for inlining at link-time. Note if they 525 // are unreferenced they will be removed by GlobalDCE later, so 526 // this only impacts referenced available externally globals. 527 // Eventually they will be suppressed during codegen, but eliminating 528 // here enables more opportunity for GlobalDCE as it may make 529 // globals referenced by available external functions dead 530 // and saves running remaining passes on the eliminated functions. 531 MPM.add(createEliminateAvailableExternallyPass()); 532 533 if (!DisableUnitAtATime) 534 MPM.add(createReversePostOrderFunctionAttrsPass()); 535 536 // If we are planning to perform ThinLTO later, let's not bloat the code with 537 // unrolling/vectorization/... now. We'll first run the inliner + CGSCC passes 538 // during ThinLTO and perform the rest of the optimizations afterward. 539 if (PrepareForThinLTO) { 540 // Reduce the size of the IR as much as possible. 541 MPM.add(createGlobalOptimizerPass()); 542 // Rename anon globals to be able to export them in the summary. 543 MPM.add(createNameAnonGlobalPass()); 544 return; 545 } 546 547 if (PerformThinLTO) 548 // Optimize globals now when performing ThinLTO, this enables more 549 // optimizations later. 550 MPM.add(createGlobalOptimizerPass()); 551 552 // Scheduling LoopVersioningLICM when inlining is over, because after that 553 // we may see more accurate aliasing. Reason to run this late is that too 554 // early versioning may prevent further inlining due to increase of code 555 // size. By placing it just after inlining other optimizations which runs 556 // later might get benefit of no-alias assumption in clone loop. 557 if (UseLoopVersioningLICM) { 558 MPM.add(createLoopVersioningLICMPass()); // Do LoopVersioningLICM 559 MPM.add(createLICMPass()); // Hoist loop invariants 560 } 561 562 if (EnableNonLTOGlobalsModRef) 563 // We add a fresh GlobalsModRef run at this point. This is particularly 564 // useful as the above will have inlined, DCE'ed, and function-attr 565 // propagated everything. We should at this point have a reasonably minimal 566 // and richly annotated call graph. By computing aliasing and mod/ref 567 // information for all local globals here, the late loop passes and notably 568 // the vectorizer will be able to use them to help recognize vectorizable 569 // memory operations. 570 // 571 // Note that this relies on a bug in the pass manager which preserves 572 // a module analysis into a function pass pipeline (and throughout it) so 573 // long as the first function pass doesn't invalidate the module analysis. 574 // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for 575 // this to work. Fortunately, it is trivial to preserve AliasAnalysis 576 // (doing nothing preserves it as it is required to be conservatively 577 // correct in the face of IR changes). 578 MPM.add(createGlobalsAAWrapperPass()); 579 580 MPM.add(createFloat2IntPass()); 581 582 addExtensionsToPM(EP_VectorizerStart, MPM); 583 584 // Re-rotate loops in all our loop nests. These may have fallout out of 585 // rotated form due to GVN or other transformations, and the vectorizer relies 586 // on the rotated form. Disable header duplication at -Oz. 587 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1)); 588 589 // Distribute loops to allow partial vectorization. I.e. isolate dependences 590 // into separate loop that would otherwise inhibit vectorization. This is 591 // currently only performed for loops marked with the metadata 592 // llvm.loop.distribute=true or when -enable-loop-distribute is specified. 593 MPM.add(createLoopDistributePass()); 594 595 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize)); 596 597 // Eliminate loads by forwarding stores from the previous iteration to loads 598 // of the current iteration. 599 if (EnableLoopLoadElim) 600 MPM.add(createLoopLoadEliminationPass()); 601 602 // FIXME: Because of #pragma vectorize enable, the passes below are always 603 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when 604 // on -O1 and no #pragma is found). Would be good to have these two passes 605 // as function calls, so that we can only pass them when the vectorizer 606 // changed the code. 607 addInstructionCombiningPass(MPM); 608 if (OptLevel > 1 && ExtraVectorizerPasses) { 609 // At higher optimization levels, try to clean up any runtime overlap and 610 // alignment checks inserted by the vectorizer. We want to track correllated 611 // runtime checks for two inner loops in the same outer loop, fold any 612 // common computations, hoist loop-invariant aspects out of any outer loop, 613 // and unswitch the runtime checks if possible. Once hoisted, we may have 614 // dead (or speculatable) control flows or more combining opportunities. 615 MPM.add(createEarlyCSEPass()); 616 MPM.add(createCorrelatedValuePropagationPass()); 617 addInstructionCombiningPass(MPM); 618 MPM.add(createLICMPass()); 619 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget)); 620 MPM.add(createCFGSimplificationPass()); 621 addInstructionCombiningPass(MPM); 622 } 623 624 if (RunSLPAfterLoopVectorization) { 625 if (SLPVectorize) { 626 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains. 627 if (OptLevel > 1 && ExtraVectorizerPasses) { 628 MPM.add(createEarlyCSEPass()); 629 } 630 } 631 632 if (BBVectorize) { 633 MPM.add(createBBVectorizePass()); 634 addInstructionCombiningPass(MPM); 635 addExtensionsToPM(EP_Peephole, MPM); 636 if (OptLevel > 1 && UseGVNAfterVectorization) 637 MPM.add(NewGVN 638 ? createNewGVNPass() 639 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies 640 else 641 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies 642 643 // BBVectorize may have significantly shortened a loop body; unroll again. 644 if (!DisableUnrollLoops) 645 MPM.add(createLoopUnrollPass(OptLevel)); 646 } 647 } 648 649 addExtensionsToPM(EP_Peephole, MPM); 650 MPM.add(createLateCFGSimplificationPass()); // Switches to lookup tables 651 addInstructionCombiningPass(MPM); 652 653 if (!DisableUnrollLoops) { 654 MPM.add(createLoopUnrollPass(OptLevel)); // Unroll small loops 655 656 // LoopUnroll may generate some redundency to cleanup. 657 addInstructionCombiningPass(MPM); 658 659 // Runtime unrolling will introduce runtime check in loop prologue. If the 660 // unrolled loop is a inner loop, then the prologue will be inside the 661 // outer loop. LICM pass can help to promote the runtime check out if the 662 // checked value is loop invariant. 663 MPM.add(createLICMPass()); 664 } 665 666 // After vectorization and unrolling, assume intrinsics may tell us more 667 // about pointer alignments. 668 MPM.add(createAlignmentFromAssumptionsPass()); 669 670 if (!DisableUnitAtATime) { 671 // FIXME: We shouldn't bother with this anymore. 672 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes 673 674 // GlobalOpt already deletes dead functions and globals, at -O2 try a 675 // late pass of GlobalDCE. It is capable of deleting dead cycles. 676 if (OptLevel > 1) { 677 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals. 678 MPM.add(createConstantMergePass()); // Merge dup global constants 679 } 680 } 681 682 if (MergeFunctions) 683 MPM.add(createMergeFunctionsPass()); 684 685 // LoopSink pass sinks instructions hoisted by LICM, which serves as a 686 // canonicalization pass that enables other optimizations. As a result, 687 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM 688 // result too early. 689 MPM.add(createLoopSinkPass()); 690 // Get rid of LCSSA nodes. 691 MPM.add(createInstructionSimplifierPass()); 692 693 // LoopSink (and other loop passes since the last simplifyCFG) might have 694 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG. 695 MPM.add(createCFGSimplificationPass()); 696 697 addExtensionsToPM(EP_OptimizerLast, MPM); 698 } 699 700 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) { 701 // Remove unused virtual tables to improve the quality of code generated by 702 // whole-program devirtualization and bitset lowering. 703 PM.add(createGlobalDCEPass()); 704 705 // Provide AliasAnalysis services for optimizations. 706 addInitialAliasAnalysisPasses(PM); 707 708 // Allow forcing function attributes as a debugging and tuning aid. 709 PM.add(createForceFunctionAttrsLegacyPass()); 710 711 // Infer attributes about declarations if possible. 712 PM.add(createInferFunctionAttrsLegacyPass()); 713 714 if (OptLevel > 1) { 715 // Indirect call promotion. This should promote all the targets that are 716 // left by the earlier promotion pass that promotes intra-module targets. 717 // This two-step promotion is to save the compile time. For LTO, it should 718 // produce the same result as if we only do promotion here. 719 PM.add( 720 createPGOIndirectCallPromotionLegacyPass(true, !PGOSampleUse.empty())); 721 722 // Propagate constants at call sites into the functions they call. This 723 // opens opportunities for globalopt (and inlining) by substituting function 724 // pointers passed as arguments to direct uses of functions. 725 PM.add(createIPSCCPPass()); 726 } 727 728 // Infer attributes about definitions. The readnone attribute in particular is 729 // required for virtual constant propagation. 730 PM.add(createPostOrderFunctionAttrsLegacyPass()); 731 PM.add(createReversePostOrderFunctionAttrsPass()); 732 733 // Split globals using inrange annotations on GEP indices. This can help 734 // improve the quality of generated code when virtual constant propagation or 735 // control flow integrity are enabled. 736 PM.add(createGlobalSplitPass()); 737 738 // Apply whole-program devirtualization and virtual constant propagation. 739 PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr)); 740 741 // That's all we need at opt level 1. 742 if (OptLevel == 1) 743 return; 744 745 // Now that we internalized some globals, see if we can hack on them! 746 PM.add(createGlobalOptimizerPass()); 747 // Promote any localized global vars. 748 PM.add(createPromoteMemoryToRegisterPass()); 749 750 // Linking modules together can lead to duplicated global constants, only 751 // keep one copy of each constant. 752 PM.add(createConstantMergePass()); 753 754 // Remove unused arguments from functions. 755 PM.add(createDeadArgEliminationPass()); 756 757 // Reduce the code after globalopt and ipsccp. Both can open up significant 758 // simplification opportunities, and both can propagate functions through 759 // function pointers. When this happens, we often have to resolve varargs 760 // calls, etc, so let instcombine do this. 761 addInstructionCombiningPass(PM); 762 addExtensionsToPM(EP_Peephole, PM); 763 764 // Inline small functions 765 bool RunInliner = Inliner; 766 if (RunInliner) { 767 PM.add(Inliner); 768 Inliner = nullptr; 769 } 770 771 PM.add(createPruneEHPass()); // Remove dead EH info. 772 773 // Optimize globals again if we ran the inliner. 774 if (RunInliner) 775 PM.add(createGlobalOptimizerPass()); 776 PM.add(createGlobalDCEPass()); // Remove dead functions. 777 778 // If we didn't decide to inline a function, check to see if we can 779 // transform it to pass arguments by value instead of by reference. 780 PM.add(createArgumentPromotionPass()); 781 782 // The IPO passes may leave cruft around. Clean up after them. 783 addInstructionCombiningPass(PM); 784 addExtensionsToPM(EP_Peephole, PM); 785 PM.add(createJumpThreadingPass()); 786 787 // Break up allocas 788 PM.add(createSROAPass()); 789 790 // Run a few AA driven optimizations here and now, to cleanup the code. 791 PM.add(createPostOrderFunctionAttrsLegacyPass()); // Add nocapture. 792 PM.add(createGlobalsAAWrapperPass()); // IP alias analysis. 793 794 PM.add(createLICMPass()); // Hoist loop invariants. 795 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds. 796 PM.add(NewGVN ? createNewGVNPass() 797 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies. 798 PM.add(createMemCpyOptPass()); // Remove dead memcpys. 799 800 // Nuke dead stores. 801 PM.add(createDeadStoreEliminationPass()); 802 803 // More loops are countable; try to optimize them. 804 PM.add(createIndVarSimplifyPass()); 805 PM.add(createLoopDeletionPass()); 806 if (EnableLoopInterchange) 807 PM.add(createLoopInterchangePass()); 808 809 if (!DisableUnrollLoops) 810 PM.add(createSimpleLoopUnrollPass(OptLevel)); // Unroll small loops 811 PM.add(createLoopVectorizePass(true, LoopVectorize)); 812 // The vectorizer may have significantly shortened a loop body; unroll again. 813 if (!DisableUnrollLoops) 814 PM.add(createLoopUnrollPass(OptLevel)); 815 816 // Now that we've optimized loops (in particular loop induction variables), 817 // we may have exposed more scalar opportunities. Run parts of the scalar 818 // optimizer again at this point. 819 addInstructionCombiningPass(PM); // Initial cleanup 820 PM.add(createCFGSimplificationPass()); // if-convert 821 PM.add(createSCCPPass()); // Propagate exposed constants 822 addInstructionCombiningPass(PM); // Clean up again 823 PM.add(createBitTrackingDCEPass()); 824 825 // More scalar chains could be vectorized due to more alias information 826 if (RunSLPAfterLoopVectorization) 827 if (SLPVectorize) 828 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains. 829 830 // After vectorization, assume intrinsics may tell us more about pointer 831 // alignments. 832 PM.add(createAlignmentFromAssumptionsPass()); 833 834 if (LoadCombine) 835 PM.add(createLoadCombinePass()); 836 837 // Cleanup and simplify the code after the scalar optimizations. 838 addInstructionCombiningPass(PM); 839 addExtensionsToPM(EP_Peephole, PM); 840 841 PM.add(createJumpThreadingPass()); 842 } 843 844 void PassManagerBuilder::addLateLTOOptimizationPasses( 845 legacy::PassManagerBase &PM) { 846 // Delete basic blocks, which optimization passes may have killed. 847 PM.add(createCFGSimplificationPass()); 848 849 // Drop bodies of available externally objects to improve GlobalDCE. 850 PM.add(createEliminateAvailableExternallyPass()); 851 852 // Now that we have optimized the program, discard unreachable functions. 853 PM.add(createGlobalDCEPass()); 854 855 // FIXME: this is profitable (for compiler time) to do at -O0 too, but 856 // currently it damages debug info. 857 if (MergeFunctions) 858 PM.add(createMergeFunctionsPass()); 859 } 860 861 void PassManagerBuilder::populateThinLTOPassManager( 862 legacy::PassManagerBase &PM) { 863 PerformThinLTO = true; 864 865 if (VerifyInput) 866 PM.add(createVerifierPass()); 867 868 if (ImportSummary) { 869 // These passes import type identifier resolutions for whole-program 870 // devirtualization and CFI. They must run early because other passes may 871 // disturb the specific instruction patterns that these passes look for, 872 // creating dependencies on resolutions that may not appear in the summary. 873 // 874 // For example, GVN may transform the pattern assume(type.test) appearing in 875 // two basic blocks into assume(phi(type.test, type.test)), which would 876 // transform a dependency on a WPD resolution into a dependency on a type 877 // identifier resolution for CFI. 878 // 879 // Also, WPD has access to more precise information than ICP and can 880 // devirtualize more effectively, so it should operate on the IR first. 881 PM.add(createWholeProgramDevirtPass(nullptr, ImportSummary)); 882 PM.add(createLowerTypeTestsPass(nullptr, ImportSummary)); 883 } 884 885 populateModulePassManager(PM); 886 887 if (VerifyOutput) 888 PM.add(createVerifierPass()); 889 PerformThinLTO = false; 890 } 891 892 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) { 893 if (LibraryInfo) 894 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 895 896 if (VerifyInput) 897 PM.add(createVerifierPass()); 898 899 if (OptLevel != 0) 900 addLTOOptimizationPasses(PM); 901 902 // Create a function that performs CFI checks for cross-DSO calls with targets 903 // in the current module. 904 PM.add(createCrossDSOCFIPass()); 905 906 // Lower type metadata and the type.test intrinsic. This pass supports Clang's 907 // control flow integrity mechanisms (-fsanitize=cfi*) and needs to run at 908 // link time if CFI is enabled. The pass does nothing if CFI is disabled. 909 PM.add(createLowerTypeTestsPass(ExportSummary, nullptr)); 910 911 if (OptLevel != 0) 912 addLateLTOOptimizationPasses(PM); 913 914 if (VerifyOutput) 915 PM.add(createVerifierPass()); 916 } 917 918 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) { 919 return reinterpret_cast<PassManagerBuilder*>(P); 920 } 921 922 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) { 923 return reinterpret_cast<LLVMPassManagerBuilderRef>(P); 924 } 925 926 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() { 927 PassManagerBuilder *PMB = new PassManagerBuilder(); 928 return wrap(PMB); 929 } 930 931 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) { 932 PassManagerBuilder *Builder = unwrap(PMB); 933 delete Builder; 934 } 935 936 void 937 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB, 938 unsigned OptLevel) { 939 PassManagerBuilder *Builder = unwrap(PMB); 940 Builder->OptLevel = OptLevel; 941 } 942 943 void 944 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB, 945 unsigned SizeLevel) { 946 PassManagerBuilder *Builder = unwrap(PMB); 947 Builder->SizeLevel = SizeLevel; 948 } 949 950 void 951 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB, 952 LLVMBool Value) { 953 PassManagerBuilder *Builder = unwrap(PMB); 954 Builder->DisableUnitAtATime = Value; 955 } 956 957 void 958 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB, 959 LLVMBool Value) { 960 PassManagerBuilder *Builder = unwrap(PMB); 961 Builder->DisableUnrollLoops = Value; 962 } 963 964 void 965 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB, 966 LLVMBool Value) { 967 // NOTE: The simplify-libcalls pass has been removed. 968 } 969 970 void 971 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB, 972 unsigned Threshold) { 973 PassManagerBuilder *Builder = unwrap(PMB); 974 Builder->Inliner = createFunctionInliningPass(Threshold); 975 } 976 977 void 978 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB, 979 LLVMPassManagerRef PM) { 980 PassManagerBuilder *Builder = unwrap(PMB); 981 legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM); 982 Builder->populateFunctionPassManager(*FPM); 983 } 984 985 void 986 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB, 987 LLVMPassManagerRef PM) { 988 PassManagerBuilder *Builder = unwrap(PMB); 989 legacy::PassManagerBase *MPM = unwrap(PM); 990 Builder->populateModulePassManager(*MPM); 991 } 992 993 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB, 994 LLVMPassManagerRef PM, 995 LLVMBool Internalize, 996 LLVMBool RunInliner) { 997 PassManagerBuilder *Builder = unwrap(PMB); 998 legacy::PassManagerBase *LPM = unwrap(PM); 999 1000 // A small backwards compatibility hack. populateLTOPassManager used to take 1001 // an RunInliner option. 1002 if (RunInliner && !Builder->Inliner) 1003 Builder->Inliner = createFunctionInliningPass(); 1004 1005 Builder->populateLTOPassManager(*LPM); 1006 } 1007