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