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