1 //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the PassManagerBuilder class, which is used to set up a 10 // "standard" optimization sequence suitable for languages like C and C++. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 15 #include "llvm-c/Transforms/PassManagerBuilder.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Analysis/CFLAndersAliasAnalysis.h" 19 #include "llvm/Analysis/CFLSteensAliasAnalysis.h" 20 #include "llvm/Analysis/GlobalsModRef.h" 21 #include "llvm/Analysis/InlineCost.h" 22 #include "llvm/Analysis/ScopedNoAliasAA.h" 23 #include "llvm/Analysis/TargetLibraryInfo.h" 24 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 25 #include "llvm/IR/LegacyPassManager.h" 26 #include "llvm/IR/Verifier.h" 27 #include "llvm/Support/CommandLine.h" 28 #include "llvm/Support/ManagedStatic.h" 29 #include "llvm/Target/CGPassBuilderOption.h" 30 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h" 31 #include "llvm/Transforms/IPO.h" 32 #include "llvm/Transforms/IPO/Attributor.h" 33 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h" 34 #include "llvm/Transforms/IPO/FunctionAttrs.h" 35 #include "llvm/Transforms/IPO/InferFunctionAttrs.h" 36 #include "llvm/Transforms/InstCombine/InstCombine.h" 37 #include "llvm/Transforms/Instrumentation.h" 38 #include "llvm/Transforms/Scalar.h" 39 #include "llvm/Transforms/Scalar/GVN.h" 40 #include "llvm/Transforms/Scalar/LICM.h" 41 #include "llvm/Transforms/Scalar/LoopUnrollPass.h" 42 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" 43 #include "llvm/Transforms/Utils.h" 44 #include "llvm/Transforms/Vectorize.h" 45 46 using namespace llvm; 47 48 namespace llvm { 49 cl::opt<bool> RunPartialInlining("enable-partial-inlining", cl::init(false), 50 cl::Hidden, cl::ZeroOrMore, 51 cl::desc("Run Partial inlinining pass")); 52 53 static cl::opt<bool> 54 UseGVNAfterVectorization("use-gvn-after-vectorization", 55 cl::init(false), cl::Hidden, 56 cl::desc("Run GVN instead of Early CSE after vectorization passes")); 57 58 cl::opt<bool> ExtraVectorizerPasses( 59 "extra-vectorizer-passes", cl::init(false), cl::Hidden, 60 cl::desc("Run cleanup optimization passes after vectorization.")); 61 62 static cl::opt<bool> 63 RunLoopRerolling("reroll-loops", cl::Hidden, 64 cl::desc("Run the loop rerolling pass")); 65 66 cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden, 67 cl::desc("Run the NewGVN pass")); 68 69 // Experimental option to use CFL-AA 70 static cl::opt<::CFLAAType> 71 UseCFLAA("use-cfl-aa", cl::init(::CFLAAType::None), cl::Hidden, 72 cl::desc("Enable the new, experimental CFL alias analysis"), 73 cl::values(clEnumValN(::CFLAAType::None, "none", "Disable CFL-AA"), 74 clEnumValN(::CFLAAType::Steensgaard, "steens", 75 "Enable unification-based CFL-AA"), 76 clEnumValN(::CFLAAType::Andersen, "anders", 77 "Enable inclusion-based CFL-AA"), 78 clEnumValN(::CFLAAType::Both, "both", 79 "Enable both variants of CFL-AA"))); 80 81 cl::opt<bool> EnableLoopInterchange( 82 "enable-loopinterchange", cl::init(false), cl::Hidden, 83 cl::desc("Enable the experimental LoopInterchange Pass")); 84 85 cl::opt<bool> EnableUnrollAndJam("enable-unroll-and-jam", cl::init(false), 86 cl::Hidden, 87 cl::desc("Enable Unroll And Jam Pass")); 88 89 cl::opt<bool> EnableLoopFlatten("enable-loop-flatten", cl::init(false), 90 cl::Hidden, 91 cl::desc("Enable the LoopFlatten Pass")); 92 93 cl::opt<bool> EnableDFAJumpThreading("enable-dfa-jump-thread", 94 cl::desc("Enable DFA jump threading."), 95 cl::init(false), cl::Hidden); 96 97 static cl::opt<bool> 98 EnablePrepareForThinLTO("prepare-for-thinlto", cl::init(false), cl::Hidden, 99 cl::desc("Enable preparation for ThinLTO.")); 100 101 static cl::opt<bool> 102 EnablePerformThinLTO("perform-thinlto", cl::init(false), cl::Hidden, 103 cl::desc("Enable performing ThinLTO.")); 104 105 cl::opt<bool> EnableHotColdSplit("hot-cold-split", cl::init(false), 106 cl::ZeroOrMore, cl::desc("Enable hot-cold splitting pass")); 107 108 cl::opt<bool> EnableIROutliner("ir-outliner", cl::init(false), cl::Hidden, 109 cl::desc("Enable ir outliner pass")); 110 111 static cl::opt<bool> UseLoopVersioningLICM( 112 "enable-loop-versioning-licm", cl::init(false), cl::Hidden, 113 cl::desc("Enable the experimental Loop Versioning LICM pass")); 114 115 cl::opt<bool> 116 DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden, 117 cl::desc("Disable pre-instrumentation inliner")); 118 119 cl::opt<int> PreInlineThreshold( 120 "preinline-threshold", cl::Hidden, cl::init(75), cl::ZeroOrMore, 121 cl::desc("Control the amount of inlining in pre-instrumentation inliner " 122 "(default = 75)")); 123 124 cl::opt<bool> 125 EnableGVNHoist("enable-gvn-hoist", cl::init(false), cl::ZeroOrMore, 126 cl::desc("Enable the GVN hoisting pass (default = off)")); 127 128 static cl::opt<bool> 129 DisableLibCallsShrinkWrap("disable-libcalls-shrinkwrap", cl::init(false), 130 cl::Hidden, 131 cl::desc("Disable shrink-wrap library calls")); 132 133 cl::opt<bool> 134 EnableGVNSink("enable-gvn-sink", cl::init(false), cl::ZeroOrMore, 135 cl::desc("Enable the GVN sinking pass (default = off)")); 136 137 // This option is used in simplifying testing SampleFDO optimizations for 138 // profile loading. 139 cl::opt<bool> 140 EnableCHR("enable-chr", cl::init(true), cl::Hidden, 141 cl::desc("Enable control height reduction optimization (CHR)")); 142 143 cl::opt<bool> FlattenedProfileUsed( 144 "flattened-profile-used", cl::init(false), cl::Hidden, 145 cl::desc("Indicate the sample profile being used is flattened, i.e., " 146 "no inline hierachy exists in the profile. ")); 147 148 cl::opt<bool> EnableOrderFileInstrumentation( 149 "enable-order-file-instrumentation", cl::init(false), cl::Hidden, 150 cl::desc("Enable order file instrumentation (default = off)")); 151 152 cl::opt<bool> EnableMatrix( 153 "enable-matrix", cl::init(false), cl::Hidden, 154 cl::desc("Enable lowering of the matrix intrinsics")); 155 156 cl::opt<bool> EnableConstraintElimination( 157 "enable-constraint-elimination", cl::init(false), cl::Hidden, 158 cl::desc( 159 "Enable pass to eliminate conditions based on linear constraints.")); 160 161 cl::opt<bool> EnableFunctionSpecialization( 162 "enable-function-specialization", cl::init(false), cl::Hidden, 163 cl::desc("Enable Function Specialization pass")); 164 165 cl::opt<AttributorRunOption> AttributorRun( 166 "attributor-enable", cl::Hidden, cl::init(AttributorRunOption::NONE), 167 cl::desc("Enable the attributor inter-procedural deduction pass."), 168 cl::values(clEnumValN(AttributorRunOption::ALL, "all", 169 "enable all attributor runs"), 170 clEnumValN(AttributorRunOption::MODULE, "module", 171 "enable module-wide attributor runs"), 172 clEnumValN(AttributorRunOption::CGSCC, "cgscc", 173 "enable call graph SCC attributor runs"), 174 clEnumValN(AttributorRunOption::NONE, "none", 175 "disable attributor runs"))); 176 177 extern cl::opt<bool> EnableKnowledgeRetention; 178 } // namespace llvm 179 180 PassManagerBuilder::PassManagerBuilder() { 181 OptLevel = 2; 182 SizeLevel = 0; 183 LibraryInfo = nullptr; 184 Inliner = nullptr; 185 DisableUnrollLoops = false; 186 SLPVectorize = false; 187 LoopVectorize = true; 188 LoopsInterleaved = true; 189 RerollLoops = RunLoopRerolling; 190 NewGVN = RunNewGVN; 191 LicmMssaOptCap = SetLicmMssaOptCap; 192 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap; 193 DisableGVNLoadPRE = false; 194 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll; 195 VerifyInput = false; 196 VerifyOutput = false; 197 MergeFunctions = false; 198 PrepareForLTO = false; 199 EnablePGOInstrGen = false; 200 EnablePGOCSInstrGen = false; 201 EnablePGOCSInstrUse = false; 202 PGOInstrGen = ""; 203 PGOInstrUse = ""; 204 PGOSampleUse = ""; 205 PrepareForThinLTO = EnablePrepareForThinLTO; 206 PerformThinLTO = EnablePerformThinLTO; 207 DivergentTarget = false; 208 CallGraphProfile = true; 209 } 210 211 PassManagerBuilder::~PassManagerBuilder() { 212 delete LibraryInfo; 213 delete Inliner; 214 } 215 216 /// Set of global extensions, automatically added as part of the standard set. 217 static ManagedStatic< 218 SmallVector<std::tuple<PassManagerBuilder::ExtensionPointTy, 219 PassManagerBuilder::ExtensionFn, 220 PassManagerBuilder::GlobalExtensionID>, 221 8>> 222 GlobalExtensions; 223 static PassManagerBuilder::GlobalExtensionID GlobalExtensionsCounter; 224 225 /// Check if GlobalExtensions is constructed and not empty. 226 /// Since GlobalExtensions is a managed static, calling 'empty()' will trigger 227 /// the construction of the object. 228 static bool GlobalExtensionsNotEmpty() { 229 return GlobalExtensions.isConstructed() && !GlobalExtensions->empty(); 230 } 231 232 PassManagerBuilder::GlobalExtensionID 233 PassManagerBuilder::addGlobalExtension(PassManagerBuilder::ExtensionPointTy Ty, 234 PassManagerBuilder::ExtensionFn Fn) { 235 auto ExtensionID = GlobalExtensionsCounter++; 236 GlobalExtensions->push_back(std::make_tuple(Ty, std::move(Fn), ExtensionID)); 237 return ExtensionID; 238 } 239 240 void PassManagerBuilder::removeGlobalExtension( 241 PassManagerBuilder::GlobalExtensionID ExtensionID) { 242 // RegisterStandardPasses may try to call this function after GlobalExtensions 243 // has already been destroyed; doing so should not generate an error. 244 if (!GlobalExtensions.isConstructed()) 245 return; 246 247 auto GlobalExtension = 248 llvm::find_if(*GlobalExtensions, [ExtensionID](const auto &elem) { 249 return std::get<2>(elem) == ExtensionID; 250 }); 251 assert(GlobalExtension != GlobalExtensions->end() && 252 "The extension ID to be removed should always be valid."); 253 254 GlobalExtensions->erase(GlobalExtension); 255 } 256 257 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) { 258 Extensions.push_back(std::make_pair(Ty, std::move(Fn))); 259 } 260 261 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy, 262 legacy::PassManagerBase &PM) const { 263 if (GlobalExtensionsNotEmpty()) { 264 for (auto &Ext : *GlobalExtensions) { 265 if (std::get<0>(Ext) == ETy) 266 std::get<1>(Ext)(*this, PM); 267 } 268 } 269 for (unsigned i = 0, e = Extensions.size(); i != e; ++i) 270 if (Extensions[i].first == ETy) 271 Extensions[i].second(*this, PM); 272 } 273 274 void PassManagerBuilder::addInitialAliasAnalysisPasses( 275 legacy::PassManagerBase &PM) const { 276 switch (UseCFLAA) { 277 case ::CFLAAType::Steensgaard: 278 PM.add(createCFLSteensAAWrapperPass()); 279 break; 280 case ::CFLAAType::Andersen: 281 PM.add(createCFLAndersAAWrapperPass()); 282 break; 283 case ::CFLAAType::Both: 284 PM.add(createCFLSteensAAWrapperPass()); 285 PM.add(createCFLAndersAAWrapperPass()); 286 break; 287 default: 288 break; 289 } 290 291 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that 292 // BasicAliasAnalysis wins if they disagree. This is intended to help 293 // support "obvious" type-punning idioms. 294 PM.add(createTypeBasedAAWrapperPass()); 295 PM.add(createScopedNoAliasAAWrapperPass()); 296 } 297 298 void PassManagerBuilder::populateFunctionPassManager( 299 legacy::FunctionPassManager &FPM) { 300 addExtensionsToPM(EP_EarlyAsPossible, FPM); 301 302 // Add LibraryInfo if we have some. 303 if (LibraryInfo) 304 FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 305 306 // The backends do not handle matrix intrinsics currently. 307 // Make sure they are also lowered in O0. 308 // FIXME: A lightweight version of the pass should run in the backend 309 // pipeline on demand. 310 if (EnableMatrix && OptLevel == 0) 311 FPM.add(createLowerMatrixIntrinsicsMinimalPass()); 312 313 if (OptLevel == 0) return; 314 315 addInitialAliasAnalysisPasses(FPM); 316 317 // Lower llvm.expect to metadata before attempting transforms. 318 // Compare/branch metadata may alter the behavior of passes like SimplifyCFG. 319 FPM.add(createLowerExpectIntrinsicPass()); 320 FPM.add(createCFGSimplificationPass()); 321 FPM.add(createSROAPass()); 322 FPM.add(createEarlyCSEPass()); 323 } 324 325 void PassManagerBuilder::addFunctionSimplificationPasses( 326 legacy::PassManagerBase &MPM) { 327 // Start of function pass. 328 // Break up aggregate allocas, using SSAUpdater. 329 assert(OptLevel >= 1 && "Calling function optimizer with no optimization level!"); 330 MPM.add(createSROAPass()); 331 MPM.add(createEarlyCSEPass(true /* Enable mem-ssa. */)); // Catch trivial redundancies 332 if (EnableKnowledgeRetention) 333 MPM.add(createAssumeSimplifyPass()); 334 335 if (OptLevel > 1) { 336 if (EnableGVNHoist) 337 MPM.add(createGVNHoistPass()); 338 if (EnableGVNSink) { 339 MPM.add(createGVNSinkPass()); 340 MPM.add(createCFGSimplificationPass( 341 SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 342 } 343 } 344 345 if (EnableConstraintElimination) 346 MPM.add(createConstraintEliminationPass()); 347 348 if (OptLevel > 1) { 349 // Speculative execution if the target has divergent branches; otherwise nop. 350 MPM.add(createSpeculativeExecutionIfHasBranchDivergencePass()); 351 352 MPM.add(createJumpThreadingPass()); // Thread jumps. 353 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals 354 } 355 MPM.add( 356 createCFGSimplificationPass(SimplifyCFGOptions().convertSwitchRangeToICmp( 357 true))); // Merge & remove BBs 358 // Combine silly seq's 359 if (OptLevel > 2) 360 MPM.add(createAggressiveInstCombinerPass()); 361 MPM.add(createInstructionCombiningPass()); 362 if (SizeLevel == 0 && !DisableLibCallsShrinkWrap) 363 MPM.add(createLibCallsShrinkWrapPass()); 364 addExtensionsToPM(EP_Peephole, MPM); 365 366 // TODO: Investigate the cost/benefit of tail call elimination on debugging. 367 if (OptLevel > 1) 368 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls 369 MPM.add( 370 createCFGSimplificationPass(SimplifyCFGOptions().convertSwitchRangeToICmp( 371 true))); // Merge & remove BBs 372 MPM.add(createReassociatePass()); // Reassociate expressions 373 374 // The matrix extension can introduce large vector operations early, which can 375 // benefit from running vector-combine early on. 376 if (EnableMatrix) 377 MPM.add(createVectorCombinePass()); 378 379 // Begin the loop pass pipeline. 380 381 // The simple loop unswitch pass relies on separate cleanup passes. Schedule 382 // them first so when we re-process a loop they run before other loop 383 // passes. 384 MPM.add(createLoopInstSimplifyPass()); 385 MPM.add(createLoopSimplifyCFGPass()); 386 387 // Try to remove as much code from the loop header as possible, 388 // to reduce amount of IR that will have to be duplicated. However, 389 // do not perform speculative hoisting the first time as LICM 390 // will destroy metadata that may not need to be destroyed if run 391 // after loop rotation. 392 // TODO: Investigate promotion cap for O1. 393 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 394 /*AllowSpeculation=*/false)); 395 // Rotate Loop - disable header duplication at -Oz 396 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1, PrepareForLTO)); 397 // TODO: Investigate promotion cap for O1. 398 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 399 /*AllowSpeculation=*/true)); 400 MPM.add(createSimpleLoopUnswitchLegacyPass(OptLevel == 3)); 401 // FIXME: We break the loop pass pipeline here in order to do full 402 // simplifycfg. Eventually loop-simplifycfg should be enhanced to replace the 403 // need for this. 404 MPM.add(createCFGSimplificationPass( 405 SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 406 MPM.add(createInstructionCombiningPass()); 407 // We resume loop passes creating a second loop pipeline here. 408 if (EnableLoopFlatten) { 409 MPM.add(createLoopFlattenPass()); // Flatten loops 410 MPM.add(createLoopSimplifyCFGPass()); 411 } 412 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset. 413 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars 414 addExtensionsToPM(EP_LateLoopOptimizations, MPM); 415 MPM.add(createLoopDeletionPass()); // Delete dead loops 416 417 if (EnableLoopInterchange) 418 MPM.add(createLoopInterchangePass()); // Interchange loops 419 420 // Unroll small loops and perform peeling. 421 MPM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops, 422 ForgetAllSCEVInLoopUnroll)); 423 addExtensionsToPM(EP_LoopOptimizerEnd, MPM); 424 // This ends the loop pass pipelines. 425 426 // Break up allocas that may now be splittable after loop unrolling. 427 MPM.add(createSROAPass()); 428 429 if (OptLevel > 1) { 430 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds 431 MPM.add(NewGVN ? createNewGVNPass() 432 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies 433 } 434 MPM.add(createSCCPPass()); // Constant prop with SCCP 435 436 if (EnableConstraintElimination) 437 MPM.add(createConstraintEliminationPass()); 438 439 // Delete dead bit computations (instcombine runs after to fold away the dead 440 // computations, and then ADCE will run later to exploit any new DCE 441 // opportunities that creates). 442 MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations 443 444 // Run instcombine after redundancy elimination to exploit opportunities 445 // opened up by them. 446 MPM.add(createInstructionCombiningPass()); 447 addExtensionsToPM(EP_Peephole, MPM); 448 if (OptLevel > 1) { 449 if (EnableDFAJumpThreading && SizeLevel == 0) 450 MPM.add(createDFAJumpThreadingPass()); 451 452 MPM.add(createJumpThreadingPass()); // Thread jumps 453 MPM.add(createCorrelatedValuePropagationPass()); 454 } 455 MPM.add(createAggressiveDCEPass()); // Delete dead instructions 456 457 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset 458 // TODO: Investigate if this is too expensive at O1. 459 if (OptLevel > 1) { 460 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores 461 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 462 /*AllowSpeculation=*/true)); 463 } 464 465 addExtensionsToPM(EP_ScalarOptimizerLate, MPM); 466 467 if (RerollLoops) 468 MPM.add(createLoopRerollPass()); 469 470 // Merge & remove BBs and sink & hoist common instructions. 471 MPM.add(createCFGSimplificationPass( 472 SimplifyCFGOptions().hoistCommonInsts(true).sinkCommonInsts(true))); 473 // Clean up after everything. 474 MPM.add(createInstructionCombiningPass()); 475 addExtensionsToPM(EP_Peephole, MPM); 476 477 if (EnableCHR && OptLevel >= 3 && 478 (!PGOInstrUse.empty() || !PGOSampleUse.empty() || EnablePGOCSInstrGen)) 479 MPM.add(createControlHeightReductionLegacyPass()); 480 } 481 482 /// FIXME: Should LTO cause any differences to this set of passes? 483 void PassManagerBuilder::addVectorPasses(legacy::PassManagerBase &PM, 484 bool IsFullLTO) { 485 PM.add(createLoopVectorizePass(!LoopsInterleaved, !LoopVectorize)); 486 487 if (IsFullLTO) { 488 // The vectorizer may have significantly shortened a loop body; unroll 489 // again. Unroll small loops to hide loop backedge latency and saturate any 490 // parallel execution resources of an out-of-order processor. We also then 491 // need to clean up redundancies and loop invariant code. 492 // FIXME: It would be really good to use a loop-integrated instruction 493 // combiner for cleanup here so that the unrolling and LICM can be pipelined 494 // across the loop nests. 495 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll 496 if (EnableUnrollAndJam && !DisableUnrollLoops) 497 PM.add(createLoopUnrollAndJamPass(OptLevel)); 498 PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops, 499 ForgetAllSCEVInLoopUnroll)); 500 PM.add(createWarnMissedTransformationsPass()); 501 } 502 503 if (!IsFullLTO) { 504 // Eliminate loads by forwarding stores from the previous iteration to loads 505 // of the current iteration. 506 PM.add(createLoopLoadEliminationPass()); 507 } 508 // Cleanup after the loop optimization passes. 509 PM.add(createInstructionCombiningPass()); 510 511 if (OptLevel > 1 && ExtraVectorizerPasses) { 512 // At higher optimization levels, try to clean up any runtime overlap and 513 // alignment checks inserted by the vectorizer. We want to track correlated 514 // runtime checks for two inner loops in the same outer loop, fold any 515 // common computations, hoist loop-invariant aspects out of any outer loop, 516 // and unswitch the runtime checks if possible. Once hoisted, we may have 517 // dead (or speculatable) control flows or more combining opportunities. 518 PM.add(createEarlyCSEPass()); 519 PM.add(createCorrelatedValuePropagationPass()); 520 PM.add(createInstructionCombiningPass()); 521 PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 522 /*AllowSpeculation=*/true)); 523 PM.add(createSimpleLoopUnswitchLegacyPass()); 524 PM.add(createCFGSimplificationPass( 525 SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 526 PM.add(createInstructionCombiningPass()); 527 } 528 529 // Now that we've formed fast to execute loop structures, we do further 530 // optimizations. These are run afterward as they might block doing complex 531 // analyses and transforms such as what are needed for loop vectorization. 532 533 // Cleanup after loop vectorization, etc. Simplification passes like CVP and 534 // GVN, loop transforms, and others have already run, so it's now better to 535 // convert to more optimized IR using more aggressive simplify CFG options. 536 // The extra sinking transform can create larger basic blocks, so do this 537 // before SLP vectorization. 538 PM.add(createCFGSimplificationPass(SimplifyCFGOptions() 539 .forwardSwitchCondToPhi(true) 540 .convertSwitchRangeToICmp(true) 541 .convertSwitchToLookupTable(true) 542 .needCanonicalLoops(false) 543 .hoistCommonInsts(true) 544 .sinkCommonInsts(true))); 545 546 if (IsFullLTO) { 547 PM.add(createSCCPPass()); // Propagate exposed constants 548 PM.add(createInstructionCombiningPass()); // Clean up again 549 PM.add(createBitTrackingDCEPass()); 550 } 551 552 // Optimize parallel scalar instruction chains into SIMD instructions. 553 if (SLPVectorize) { 554 PM.add(createSLPVectorizerPass()); 555 if (OptLevel > 1 && ExtraVectorizerPasses) 556 PM.add(createEarlyCSEPass()); 557 } 558 559 // Enhance/cleanup vector code. 560 PM.add(createVectorCombinePass()); 561 562 if (!IsFullLTO) { 563 addExtensionsToPM(EP_Peephole, PM); 564 PM.add(createInstructionCombiningPass()); 565 566 if (EnableUnrollAndJam && !DisableUnrollLoops) { 567 // Unroll and Jam. We do this before unroll but need to be in a separate 568 // loop pass manager in order for the outer loop to be processed by 569 // unroll and jam before the inner loop is unrolled. 570 PM.add(createLoopUnrollAndJamPass(OptLevel)); 571 } 572 573 // Unroll small loops 574 PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops, 575 ForgetAllSCEVInLoopUnroll)); 576 577 if (!DisableUnrollLoops) { 578 // LoopUnroll may generate some redundency to cleanup. 579 PM.add(createInstructionCombiningPass()); 580 581 // Runtime unrolling will introduce runtime check in loop prologue. If the 582 // unrolled loop is a inner loop, then the prologue will be inside the 583 // outer loop. LICM pass can help to promote the runtime check out if the 584 // checked value is loop invariant. 585 PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 586 /*AllowSpeculation=*/true)); 587 } 588 589 PM.add(createWarnMissedTransformationsPass()); 590 } 591 592 // After vectorization and unrolling, assume intrinsics may tell us more 593 // about pointer alignments. 594 PM.add(createAlignmentFromAssumptionsPass()); 595 596 if (IsFullLTO) 597 PM.add(createInstructionCombiningPass()); 598 } 599 600 void PassManagerBuilder::populateModulePassManager( 601 legacy::PassManagerBase &MPM) { 602 MPM.add(createAnnotation2MetadataLegacyPass()); 603 604 if (!PGOSampleUse.empty()) { 605 MPM.add(createPruneEHPass()); 606 // In ThinLTO mode, when flattened profile is used, all the available 607 // profile information will be annotated in PreLink phase so there is 608 // no need to load the profile again in PostLink. 609 if (!(FlattenedProfileUsed && PerformThinLTO)) 610 MPM.add(createSampleProfileLoaderPass(PGOSampleUse)); 611 } 612 613 // Allow forcing function attributes as a debugging and tuning aid. 614 MPM.add(createForceFunctionAttrsLegacyPass()); 615 616 // If all optimizations are disabled, just run the always-inline pass and, 617 // if enabled, the function merging pass. 618 if (OptLevel == 0) { 619 if (Inliner) { 620 MPM.add(Inliner); 621 Inliner = nullptr; 622 } 623 624 // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly 625 // creates a CGSCC pass manager, but we don't want to add extensions into 626 // that pass manager. To prevent this we insert a no-op module pass to reset 627 // the pass manager to get the same behavior as EP_OptimizerLast in non-O0 628 // builds. The function merging pass is 629 if (MergeFunctions) 630 MPM.add(createMergeFunctionsPass()); 631 else if (GlobalExtensionsNotEmpty() || !Extensions.empty()) 632 MPM.add(createBarrierNoopPass()); 633 634 if (PerformThinLTO) { 635 MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true)); 636 // Drop available_externally and unreferenced globals. This is necessary 637 // with ThinLTO in order to avoid leaving undefined references to dead 638 // globals in the object file. 639 MPM.add(createEliminateAvailableExternallyPass()); 640 MPM.add(createGlobalDCEPass()); 641 } 642 643 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM); 644 645 if (PrepareForLTO || PrepareForThinLTO) { 646 MPM.add(createCanonicalizeAliasesPass()); 647 // Rename anon globals to be able to export them in the summary. 648 // This has to be done after we add the extensions to the pass manager 649 // as there could be passes (e.g. Adddress sanitizer) which introduce 650 // new unnamed globals. 651 MPM.add(createNameAnonGlobalPass()); 652 } 653 654 MPM.add(createAnnotationRemarksLegacyPass()); 655 return; 656 } 657 658 // Add LibraryInfo if we have some. 659 if (LibraryInfo) 660 MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 661 662 addInitialAliasAnalysisPasses(MPM); 663 664 // For ThinLTO there are two passes of indirect call promotion. The 665 // first is during the compile phase when PerformThinLTO=false and 666 // intra-module indirect call targets are promoted. The second is during 667 // the ThinLTO backend when PerformThinLTO=true, when we promote imported 668 // inter-module indirect calls. For that we perform indirect call promotion 669 // earlier in the pass pipeline, here before globalopt. Otherwise imported 670 // available_externally functions look unreferenced and are removed. 671 if (PerformThinLTO) { 672 MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true)); 673 } 674 675 // For SamplePGO in ThinLTO compile phase, we do not want to unroll loops 676 // as it will change the CFG too much to make the 2nd profile annotation 677 // in backend more difficult. 678 bool PrepareForThinLTOUsingPGOSampleProfile = 679 PrepareForThinLTO && !PGOSampleUse.empty(); 680 if (PrepareForThinLTOUsingPGOSampleProfile) 681 DisableUnrollLoops = true; 682 683 // Infer attributes about declarations if possible. 684 MPM.add(createInferFunctionAttrsLegacyPass()); 685 686 // Infer attributes on declarations, call sites, arguments, etc. 687 if (AttributorRun & AttributorRunOption::MODULE) 688 MPM.add(createAttributorLegacyPass()); 689 690 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM); 691 692 if (OptLevel > 2) 693 MPM.add(createCallSiteSplittingPass()); 694 695 // Propage constant function arguments by specializing the functions. 696 if (OptLevel > 2 && EnableFunctionSpecialization) 697 MPM.add(createFunctionSpecializationPass()); 698 699 MPM.add(createIPSCCPPass()); // IP SCCP 700 MPM.add(createCalledValuePropagationPass()); 701 702 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars 703 // Promote any localized global vars. 704 MPM.add(createPromoteMemoryToRegisterPass()); 705 706 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination 707 708 MPM.add(createInstructionCombiningPass()); // Clean up after IPCP & DAE 709 addExtensionsToPM(EP_Peephole, MPM); 710 MPM.add( 711 createCFGSimplificationPass(SimplifyCFGOptions().convertSwitchRangeToICmp( 712 true))); // Clean up after IPCP & DAE 713 714 // We add a module alias analysis pass here. In part due to bugs in the 715 // analysis infrastructure this "works" in that the analysis stays alive 716 // for the entire SCC pass run below. 717 MPM.add(createGlobalsAAWrapperPass()); 718 719 // Start of CallGraph SCC passes. 720 MPM.add(createPruneEHPass()); // Remove dead EH info 721 bool RunInliner = false; 722 if (Inliner) { 723 MPM.add(Inliner); 724 Inliner = nullptr; 725 RunInliner = true; 726 } 727 728 // Infer attributes on declarations, call sites, arguments, etc. for an SCC. 729 if (AttributorRun & AttributorRunOption::CGSCC) 730 MPM.add(createAttributorCGSCCLegacyPass()); 731 732 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if 733 // there are no OpenMP runtime calls present in the module. 734 if (OptLevel > 1) 735 MPM.add(createOpenMPOptCGSCCLegacyPass()); 736 737 MPM.add(createPostOrderFunctionAttrsLegacyPass()); 738 if (OptLevel > 2) 739 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args 740 741 addExtensionsToPM(EP_CGSCCOptimizerLate, MPM); 742 addFunctionSimplificationPasses(MPM); 743 744 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC 745 // pass manager that we are specifically trying to avoid. To prevent this 746 // we must insert a no-op module pass to reset the pass manager. 747 MPM.add(createBarrierNoopPass()); 748 749 if (RunPartialInlining) 750 MPM.add(createPartialInliningPass()); 751 752 if (OptLevel > 1 && !PrepareForLTO && !PrepareForThinLTO) 753 // Remove avail extern fns and globals definitions if we aren't 754 // compiling an object file for later LTO. For LTO we want to preserve 755 // these so they are eligible for inlining at link-time. Note if they 756 // are unreferenced they will be removed by GlobalDCE later, so 757 // this only impacts referenced available externally globals. 758 // Eventually they will be suppressed during codegen, but eliminating 759 // here enables more opportunity for GlobalDCE as it may make 760 // globals referenced by available external functions dead 761 // and saves running remaining passes on the eliminated functions. 762 MPM.add(createEliminateAvailableExternallyPass()); 763 764 if (EnableOrderFileInstrumentation) 765 MPM.add(createInstrOrderFilePass()); 766 767 MPM.add(createReversePostOrderFunctionAttrsPass()); 768 769 // The inliner performs some kind of dead code elimination as it goes, 770 // but there are cases that are not really caught by it. We might 771 // at some point consider teaching the inliner about them, but it 772 // is OK for now to run GlobalOpt + GlobalDCE in tandem as their 773 // benefits generally outweight the cost, making the whole pipeline 774 // faster. 775 if (RunInliner) { 776 MPM.add(createGlobalOptimizerPass()); 777 MPM.add(createGlobalDCEPass()); 778 } 779 780 // If we are planning to perform ThinLTO later, let's not bloat the code with 781 // unrolling/vectorization/... now. We'll first run the inliner + CGSCC passes 782 // during ThinLTO and perform the rest of the optimizations afterward. 783 if (PrepareForThinLTO) { 784 // Ensure we perform any last passes, but do so before renaming anonymous 785 // globals in case the passes add any. 786 addExtensionsToPM(EP_OptimizerLast, MPM); 787 MPM.add(createCanonicalizeAliasesPass()); 788 // Rename anon globals to be able to export them in the summary. 789 MPM.add(createNameAnonGlobalPass()); 790 return; 791 } 792 793 if (PerformThinLTO) 794 // Optimize globals now when performing ThinLTO, this enables more 795 // optimizations later. 796 MPM.add(createGlobalOptimizerPass()); 797 798 // Scheduling LoopVersioningLICM when inlining is over, because after that 799 // we may see more accurate aliasing. Reason to run this late is that too 800 // early versioning may prevent further inlining due to increase of code 801 // size. By placing it just after inlining other optimizations which runs 802 // later might get benefit of no-alias assumption in clone loop. 803 if (UseLoopVersioningLICM) { 804 MPM.add(createLoopVersioningLICMPass()); // Do LoopVersioningLICM 805 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 806 /*AllowSpeculation=*/true)); 807 } 808 809 // We add a fresh GlobalsModRef run at this point. This is particularly 810 // useful as the above will have inlined, DCE'ed, and function-attr 811 // propagated everything. We should at this point have a reasonably minimal 812 // and richly annotated call graph. By computing aliasing and mod/ref 813 // information for all local globals here, the late loop passes and notably 814 // the vectorizer will be able to use them to help recognize vectorizable 815 // memory operations. 816 // 817 // Note that this relies on a bug in the pass manager which preserves 818 // a module analysis into a function pass pipeline (and throughout it) so 819 // long as the first function pass doesn't invalidate the module analysis. 820 // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for 821 // this to work. Fortunately, it is trivial to preserve AliasAnalysis 822 // (doing nothing preserves it as it is required to be conservatively 823 // correct in the face of IR changes). 824 MPM.add(createGlobalsAAWrapperPass()); 825 826 MPM.add(createFloat2IntPass()); 827 MPM.add(createLowerConstantIntrinsicsPass()); 828 829 if (EnableMatrix) { 830 MPM.add(createLowerMatrixIntrinsicsPass()); 831 // CSE the pointer arithmetic of the column vectors. This allows alias 832 // analysis to establish no-aliasing between loads and stores of different 833 // columns of the same matrix. 834 MPM.add(createEarlyCSEPass(false)); 835 } 836 837 addExtensionsToPM(EP_VectorizerStart, MPM); 838 839 // Re-rotate loops in all our loop nests. These may have fallout out of 840 // rotated form due to GVN or other transformations, and the vectorizer relies 841 // on the rotated form. Disable header duplication at -Oz. 842 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1, PrepareForLTO)); 843 844 // Distribute loops to allow partial vectorization. I.e. isolate dependences 845 // into separate loop that would otherwise inhibit vectorization. This is 846 // currently only performed for loops marked with the metadata 847 // llvm.loop.distribute=true or when -enable-loop-distribute is specified. 848 MPM.add(createLoopDistributePass()); 849 850 addVectorPasses(MPM, /* IsFullLTO */ false); 851 852 // FIXME: We shouldn't bother with this anymore. 853 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes 854 855 // GlobalOpt already deletes dead functions and globals, at -O2 try a 856 // late pass of GlobalDCE. It is capable of deleting dead cycles. 857 if (OptLevel > 1) { 858 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals. 859 MPM.add(createConstantMergePass()); // Merge dup global constants 860 } 861 862 // See comment in the new PM for justification of scheduling splitting at 863 // this stage (\ref buildModuleSimplificationPipeline). 864 if (EnableHotColdSplit && !(PrepareForLTO || PrepareForThinLTO)) 865 MPM.add(createHotColdSplittingPass()); 866 867 if (EnableIROutliner) 868 MPM.add(createIROutlinerPass()); 869 870 if (MergeFunctions) 871 MPM.add(createMergeFunctionsPass()); 872 873 // Add Module flag "CG Profile" based on Branch Frequency Information. 874 if (CallGraphProfile) 875 MPM.add(createCGProfileLegacyPass()); 876 877 // LoopSink pass sinks instructions hoisted by LICM, which serves as a 878 // canonicalization pass that enables other optimizations. As a result, 879 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM 880 // result too early. 881 MPM.add(createLoopSinkPass()); 882 // Get rid of LCSSA nodes. 883 MPM.add(createInstSimplifyLegacyPass()); 884 885 // This hoists/decomposes div/rem ops. It should run after other sink/hoist 886 // passes to avoid re-sinking, but before SimplifyCFG because it can allow 887 // flattening of blocks. 888 MPM.add(createDivRemPairsPass()); 889 890 // LoopSink (and other loop passes since the last simplifyCFG) might have 891 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG. 892 MPM.add(createCFGSimplificationPass( 893 SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 894 895 addExtensionsToPM(EP_OptimizerLast, MPM); 896 897 if (PrepareForLTO) { 898 MPM.add(createCanonicalizeAliasesPass()); 899 // Rename anon globals to be able to handle them in the summary 900 MPM.add(createNameAnonGlobalPass()); 901 } 902 903 MPM.add(createAnnotationRemarksLegacyPass()); 904 } 905 906 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) { 907 // Load sample profile before running the LTO optimization pipeline. 908 if (!PGOSampleUse.empty()) { 909 PM.add(createPruneEHPass()); 910 PM.add(createSampleProfileLoaderPass(PGOSampleUse)); 911 } 912 913 // Remove unused virtual tables to improve the quality of code generated by 914 // whole-program devirtualization and bitset lowering. 915 PM.add(createGlobalDCEPass()); 916 917 // Provide AliasAnalysis services for optimizations. 918 addInitialAliasAnalysisPasses(PM); 919 920 // Allow forcing function attributes as a debugging and tuning aid. 921 PM.add(createForceFunctionAttrsLegacyPass()); 922 923 // Infer attributes about declarations if possible. 924 PM.add(createInferFunctionAttrsLegacyPass()); 925 926 if (OptLevel > 1) { 927 // Split call-site with more constrained arguments. 928 PM.add(createCallSiteSplittingPass()); 929 930 // Propage constant function arguments by specializing the functions. 931 if (EnableFunctionSpecialization && OptLevel > 2) 932 PM.add(createFunctionSpecializationPass()); 933 934 // Propagate constants at call sites into the functions they call. This 935 // opens opportunities for globalopt (and inlining) by substituting function 936 // pointers passed as arguments to direct uses of functions. 937 PM.add(createIPSCCPPass()); 938 939 // Attach metadata to indirect call sites indicating the set of functions 940 // they may target at run-time. This should follow IPSCCP. 941 PM.add(createCalledValuePropagationPass()); 942 943 // Infer attributes on declarations, call sites, arguments, etc. 944 if (AttributorRun & AttributorRunOption::MODULE) 945 PM.add(createAttributorLegacyPass()); 946 } 947 948 // Infer attributes about definitions. The readnone attribute in particular is 949 // required for virtual constant propagation. 950 PM.add(createPostOrderFunctionAttrsLegacyPass()); 951 PM.add(createReversePostOrderFunctionAttrsPass()); 952 953 // Split globals using inrange annotations on GEP indices. This can help 954 // improve the quality of generated code when virtual constant propagation or 955 // control flow integrity are enabled. 956 PM.add(createGlobalSplitPass()); 957 958 // Apply whole-program devirtualization and virtual constant propagation. 959 PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr)); 960 961 // That's all we need at opt level 1. 962 if (OptLevel == 1) 963 return; 964 965 // Now that we internalized some globals, see if we can hack on them! 966 PM.add(createGlobalOptimizerPass()); 967 // Promote any localized global vars. 968 PM.add(createPromoteMemoryToRegisterPass()); 969 970 // Linking modules together can lead to duplicated global constants, only 971 // keep one copy of each constant. 972 PM.add(createConstantMergePass()); 973 974 // Remove unused arguments from functions. 975 PM.add(createDeadArgEliminationPass()); 976 977 // Reduce the code after globalopt and ipsccp. Both can open up significant 978 // simplification opportunities, and both can propagate functions through 979 // function pointers. When this happens, we often have to resolve varargs 980 // calls, etc, so let instcombine do this. 981 if (OptLevel > 2) 982 PM.add(createAggressiveInstCombinerPass()); 983 PM.add(createInstructionCombiningPass()); 984 addExtensionsToPM(EP_Peephole, PM); 985 986 // Inline small functions 987 bool RunInliner = Inliner; 988 if (RunInliner) { 989 PM.add(Inliner); 990 Inliner = nullptr; 991 } 992 993 PM.add(createPruneEHPass()); // Remove dead EH info. 994 995 // Infer attributes on declarations, call sites, arguments, etc. for an SCC. 996 if (AttributorRun & AttributorRunOption::CGSCC) 997 PM.add(createAttributorCGSCCLegacyPass()); 998 999 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if 1000 // there are no OpenMP runtime calls present in the module. 1001 if (OptLevel > 1) 1002 PM.add(createOpenMPOptCGSCCLegacyPass()); 1003 1004 // Optimize globals again if we ran the inliner. 1005 if (RunInliner) 1006 PM.add(createGlobalOptimizerPass()); 1007 PM.add(createGlobalDCEPass()); // Remove dead functions. 1008 1009 // If we didn't decide to inline a function, check to see if we can 1010 // transform it to pass arguments by value instead of by reference. 1011 PM.add(createArgumentPromotionPass()); 1012 1013 // The IPO passes may leave cruft around. Clean up after them. 1014 PM.add(createInstructionCombiningPass()); 1015 addExtensionsToPM(EP_Peephole, PM); 1016 PM.add(createJumpThreadingPass(/*FreezeSelectCond*/ true)); 1017 1018 // Break up allocas 1019 PM.add(createSROAPass()); 1020 1021 // LTO provides additional opportunities for tailcall elimination due to 1022 // link-time inlining, and visibility of nocapture attribute. 1023 if (OptLevel > 1) 1024 PM.add(createTailCallEliminationPass()); 1025 1026 // Infer attributes on declarations, call sites, arguments, etc. 1027 PM.add(createPostOrderFunctionAttrsLegacyPass()); // Add nocapture. 1028 // Run a few AA driven optimizations here and now, to cleanup the code. 1029 PM.add(createGlobalsAAWrapperPass()); // IP alias analysis. 1030 1031 PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 1032 /*AllowSpeculation=*/true)); 1033 PM.add(NewGVN ? createNewGVNPass() 1034 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies. 1035 PM.add(createMemCpyOptPass()); // Remove dead memcpys. 1036 1037 // Nuke dead stores. 1038 PM.add(createDeadStoreEliminationPass()); 1039 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds. 1040 1041 // More loops are countable; try to optimize them. 1042 if (EnableLoopFlatten) 1043 PM.add(createLoopFlattenPass()); 1044 PM.add(createIndVarSimplifyPass()); 1045 PM.add(createLoopDeletionPass()); 1046 if (EnableLoopInterchange) 1047 PM.add(createLoopInterchangePass()); 1048 1049 if (EnableConstraintElimination) 1050 PM.add(createConstraintEliminationPass()); 1051 1052 // Unroll small loops and perform peeling. 1053 PM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops, 1054 ForgetAllSCEVInLoopUnroll)); 1055 PM.add(createLoopDistributePass()); 1056 1057 addVectorPasses(PM, /* IsFullLTO */ true); 1058 1059 addExtensionsToPM(EP_Peephole, PM); 1060 1061 PM.add(createJumpThreadingPass(/*FreezeSelectCond*/ true)); 1062 } 1063 1064 void PassManagerBuilder::addLateLTOOptimizationPasses( 1065 legacy::PassManagerBase &PM) { 1066 // See comment in the new PM for justification of scheduling splitting at 1067 // this stage (\ref buildLTODefaultPipeline). 1068 if (EnableHotColdSplit) 1069 PM.add(createHotColdSplittingPass()); 1070 1071 // Delete basic blocks, which optimization passes may have killed. 1072 PM.add( 1073 createCFGSimplificationPass(SimplifyCFGOptions().hoistCommonInsts(true))); 1074 1075 // Drop bodies of available externally objects to improve GlobalDCE. 1076 PM.add(createEliminateAvailableExternallyPass()); 1077 1078 // Now that we have optimized the program, discard unreachable functions. 1079 PM.add(createGlobalDCEPass()); 1080 1081 // FIXME: this is profitable (for compiler time) to do at -O0 too, but 1082 // currently it damages debug info. 1083 if (MergeFunctions) 1084 PM.add(createMergeFunctionsPass()); 1085 } 1086 1087 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() { 1088 PassManagerBuilder *PMB = new PassManagerBuilder(); 1089 return wrap(PMB); 1090 } 1091 1092 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) { 1093 PassManagerBuilder *Builder = unwrap(PMB); 1094 delete Builder; 1095 } 1096 1097 void 1098 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB, 1099 unsigned OptLevel) { 1100 PassManagerBuilder *Builder = unwrap(PMB); 1101 Builder->OptLevel = OptLevel; 1102 } 1103 1104 void 1105 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB, 1106 unsigned SizeLevel) { 1107 PassManagerBuilder *Builder = unwrap(PMB); 1108 Builder->SizeLevel = SizeLevel; 1109 } 1110 1111 void 1112 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB, 1113 LLVMBool Value) { 1114 // NOTE: The DisableUnitAtATime switch has been removed. 1115 } 1116 1117 void 1118 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB, 1119 LLVMBool Value) { 1120 PassManagerBuilder *Builder = unwrap(PMB); 1121 Builder->DisableUnrollLoops = Value; 1122 } 1123 1124 void 1125 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB, 1126 LLVMBool Value) { 1127 // NOTE: The simplify-libcalls pass has been removed. 1128 } 1129 1130 void 1131 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB, 1132 unsigned Threshold) { 1133 PassManagerBuilder *Builder = unwrap(PMB); 1134 Builder->Inliner = createFunctionInliningPass(Threshold); 1135 } 1136 1137 void 1138 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB, 1139 LLVMPassManagerRef PM) { 1140 PassManagerBuilder *Builder = unwrap(PMB); 1141 legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM); 1142 Builder->populateFunctionPassManager(*FPM); 1143 } 1144 1145 void 1146 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB, 1147 LLVMPassManagerRef PM) { 1148 PassManagerBuilder *Builder = unwrap(PMB); 1149 legacy::PassManagerBase *MPM = unwrap(PM); 1150 Builder->populateModulePassManager(*MPM); 1151 } 1152