PassBuilderPipelines.cpp 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855
  1. //===- Construction of pass pipelines -------------------------------------===//
  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. /// \file
  9. ///
  10. /// This file provides the implementation of the PassBuilder based on our
  11. /// static pass registry as well as related functionality. It also provides
  12. /// helpers to aid in analyzing, debugging, and testing passes and pass
  13. /// pipelines.
  14. ///
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/Analysis/AliasAnalysis.h"
  17. #include "llvm/Analysis/BasicAliasAnalysis.h"
  18. #include "llvm/Analysis/CGSCCPassManager.h"
  19. #include "llvm/Analysis/GlobalsModRef.h"
  20. #include "llvm/Analysis/InlineAdvisor.h"
  21. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  22. #include "llvm/Analysis/ProfileSummaryInfo.h"
  23. #include "llvm/Analysis/ScopedNoAliasAA.h"
  24. #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
  25. #include "llvm/IR/PassManager.h"
  26. #include "llvm/Passes/OptimizationLevel.h"
  27. #include "llvm/Passes/PassBuilder.h"
  28. #include "llvm/Support/CommandLine.h"
  29. #include "llvm/Support/ErrorHandling.h"
  30. #include "llvm/Support/PGOOptions.h"
  31. #include "llvm/Target/TargetMachine.h"
  32. #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
  33. #include "llvm/Transforms/Coroutines/CoroCleanup.h"
  34. #include "llvm/Transforms/Coroutines/CoroEarly.h"
  35. #include "llvm/Transforms/Coroutines/CoroElide.h"
  36. #include "llvm/Transforms/Coroutines/CoroSplit.h"
  37. #include "llvm/Transforms/IPO/AlwaysInliner.h"
  38. #include "llvm/Transforms/IPO/Annotation2Metadata.h"
  39. #include "llvm/Transforms/IPO/ArgumentPromotion.h"
  40. #include "llvm/Transforms/IPO/Attributor.h"
  41. #include "llvm/Transforms/IPO/CalledValuePropagation.h"
  42. #include "llvm/Transforms/IPO/ConstantMerge.h"
  43. #include "llvm/Transforms/IPO/CrossDSOCFI.h"
  44. #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
  45. #include "llvm/Transforms/IPO/ElimAvailExtern.h"
  46. #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
  47. #include "llvm/Transforms/IPO/FunctionAttrs.h"
  48. #include "llvm/Transforms/IPO/GlobalDCE.h"
  49. #include "llvm/Transforms/IPO/GlobalOpt.h"
  50. #include "llvm/Transforms/IPO/GlobalSplit.h"
  51. #include "llvm/Transforms/IPO/HotColdSplitting.h"
  52. #include "llvm/Transforms/IPO/IROutliner.h"
  53. #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
  54. #include "llvm/Transforms/IPO/Inliner.h"
  55. #include "llvm/Transforms/IPO/LowerTypeTests.h"
  56. #include "llvm/Transforms/IPO/MergeFunctions.h"
  57. #include "llvm/Transforms/IPO/ModuleInliner.h"
  58. #include "llvm/Transforms/IPO/OpenMPOpt.h"
  59. #include "llvm/Transforms/IPO/PartialInlining.h"
  60. #include "llvm/Transforms/IPO/SCCP.h"
  61. #include "llvm/Transforms/IPO/SampleProfile.h"
  62. #include "llvm/Transforms/IPO/SampleProfileProbe.h"
  63. #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
  64. #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
  65. #include "llvm/Transforms/InstCombine/InstCombine.h"
  66. #include "llvm/Transforms/Instrumentation/CGProfile.h"
  67. #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
  68. #include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
  69. #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
  70. #include "llvm/Transforms/Instrumentation/MemProfiler.h"
  71. #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
  72. #include "llvm/Transforms/Scalar/ADCE.h"
  73. #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
  74. #include "llvm/Transforms/Scalar/AnnotationRemarks.h"
  75. #include "llvm/Transforms/Scalar/BDCE.h"
  76. #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
  77. #include "llvm/Transforms/Scalar/ConstraintElimination.h"
  78. #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
  79. #include "llvm/Transforms/Scalar/DFAJumpThreading.h"
  80. #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
  81. #include "llvm/Transforms/Scalar/DivRemPairs.h"
  82. #include "llvm/Transforms/Scalar/EarlyCSE.h"
  83. #include "llvm/Transforms/Scalar/Float2Int.h"
  84. #include "llvm/Transforms/Scalar/GVN.h"
  85. #include "llvm/Transforms/Scalar/IndVarSimplify.h"
  86. #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
  87. #include "llvm/Transforms/Scalar/JumpThreading.h"
  88. #include "llvm/Transforms/Scalar/LICM.h"
  89. #include "llvm/Transforms/Scalar/LoopDeletion.h"
  90. #include "llvm/Transforms/Scalar/LoopDistribute.h"
  91. #include "llvm/Transforms/Scalar/LoopFlatten.h"
  92. #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
  93. #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
  94. #include "llvm/Transforms/Scalar/LoopInterchange.h"
  95. #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
  96. #include "llvm/Transforms/Scalar/LoopPassManager.h"
  97. #include "llvm/Transforms/Scalar/LoopRotation.h"
  98. #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
  99. #include "llvm/Transforms/Scalar/LoopSink.h"
  100. #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
  101. #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
  102. #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h"
  103. #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
  104. #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
  105. #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
  106. #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
  107. #include "llvm/Transforms/Scalar/NewGVN.h"
  108. #include "llvm/Transforms/Scalar/Reassociate.h"
  109. #include "llvm/Transforms/Scalar/SCCP.h"
  110. #include "llvm/Transforms/Scalar/SROA.h"
  111. #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
  112. #include "llvm/Transforms/Scalar/SimplifyCFG.h"
  113. #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
  114. #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
  115. #include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
  116. #include "llvm/Transforms/Utils/AddDiscriminators.h"
  117. #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
  118. #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
  119. #include "llvm/Transforms/Utils/InjectTLIMappings.h"
  120. #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
  121. #include "llvm/Transforms/Utils/Mem2Reg.h"
  122. #include "llvm/Transforms/Utils/NameAnonGlobals.h"
  123. #include "llvm/Transforms/Utils/RelLookupTableConverter.h"
  124. #include "llvm/Transforms/Utils/SimplifyCFGOptions.h"
  125. #include "llvm/Transforms/Vectorize/LoopVectorize.h"
  126. #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
  127. #include "llvm/Transforms/Vectorize/VectorCombine.h"
  128. using namespace llvm;
  129. static cl::opt<InliningAdvisorMode> UseInlineAdvisor(
  130. "enable-ml-inliner", cl::init(InliningAdvisorMode::Default), cl::Hidden,
  131. cl::desc("Enable ML policy for inliner. Currently trained for -Oz only"),
  132. cl::values(clEnumValN(InliningAdvisorMode::Default, "default",
  133. "Heuristics-based inliner version."),
  134. clEnumValN(InliningAdvisorMode::Development, "development",
  135. "Use development mode (runtime-loadable model)."),
  136. clEnumValN(InliningAdvisorMode::Release, "release",
  137. "Use release mode (AOT-compiled model).")));
  138. static cl::opt<bool> EnableSyntheticCounts(
  139. "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
  140. cl::desc("Run synthetic function entry count generation "
  141. "pass"));
  142. /// Flag to enable inline deferral during PGO.
  143. static cl::opt<bool>
  144. EnablePGOInlineDeferral("enable-npm-pgo-inline-deferral", cl::init(true),
  145. cl::Hidden,
  146. cl::desc("Enable inline deferral during PGO"));
  147. static cl::opt<bool> EnableMemProfiler("enable-mem-prof", cl::init(false),
  148. cl::Hidden, cl::ZeroOrMore,
  149. cl::desc("Enable memory profiler"));
  150. static cl::opt<bool> EnableModuleInliner("enable-module-inliner",
  151. cl::init(false), cl::Hidden,
  152. cl::desc("Enable module inliner"));
  153. static cl::opt<bool> PerformMandatoryInliningsFirst(
  154. "mandatory-inlining-first", cl::init(true), cl::Hidden, cl::ZeroOrMore,
  155. cl::desc("Perform mandatory inlinings module-wide, before performing "
  156. "inlining."));
  157. static cl::opt<bool> EnableO3NonTrivialUnswitching(
  158. "enable-npm-O3-nontrivial-unswitch", cl::init(true), cl::Hidden,
  159. cl::ZeroOrMore, cl::desc("Enable non-trivial loop unswitching for -O3"));
  160. static cl::opt<bool> EnableEagerlyInvalidateAnalyses(
  161. "eagerly-invalidate-analyses", cl::init(true), cl::Hidden,
  162. cl::desc("Eagerly invalidate more analyses in default pipelines"));
  163. static cl::opt<bool> EnableNoRerunSimplificationPipeline(
  164. "enable-no-rerun-simplification-pipeline", cl::init(false), cl::Hidden,
  165. cl::desc(
  166. "Prevent running the simplification pipeline on a function more "
  167. "than once in the case that SCC mutations cause a function to be "
  168. "visited multiple times as long as the function has not been changed"));
  169. static cl::opt<bool> EnableMergeFunctions(
  170. "enable-merge-functions", cl::init(false), cl::Hidden,
  171. cl::desc("Enable function merging as part of the optimization pipeline"));
  172. PipelineTuningOptions::PipelineTuningOptions() {
  173. LoopInterleaving = true;
  174. LoopVectorization = true;
  175. SLPVectorization = false;
  176. LoopUnrolling = true;
  177. ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
  178. LicmMssaOptCap = SetLicmMssaOptCap;
  179. LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
  180. CallGraphProfile = true;
  181. MergeFunctions = EnableMergeFunctions;
  182. EagerlyInvalidateAnalyses = EnableEagerlyInvalidateAnalyses;
  183. }
  184. namespace llvm {
  185. extern cl::opt<unsigned> MaxDevirtIterations;
  186. extern cl::opt<bool> EnableConstraintElimination;
  187. extern cl::opt<bool> EnableFunctionSpecialization;
  188. extern cl::opt<bool> EnableGVNHoist;
  189. extern cl::opt<bool> EnableGVNSink;
  190. extern cl::opt<bool> EnableHotColdSplit;
  191. extern cl::opt<bool> EnableIROutliner;
  192. extern cl::opt<bool> EnableOrderFileInstrumentation;
  193. extern cl::opt<bool> EnableCHR;
  194. extern cl::opt<bool> EnableLoopInterchange;
  195. extern cl::opt<bool> EnableUnrollAndJam;
  196. extern cl::opt<bool> EnableLoopFlatten;
  197. extern cl::opt<bool> EnableDFAJumpThreading;
  198. extern cl::opt<bool> RunNewGVN;
  199. extern cl::opt<bool> RunPartialInlining;
  200. extern cl::opt<bool> ExtraVectorizerPasses;
  201. extern cl::opt<bool> FlattenedProfileUsed;
  202. extern cl::opt<AttributorRunOption> AttributorRun;
  203. extern cl::opt<bool> EnableKnowledgeRetention;
  204. extern cl::opt<bool> EnableMatrix;
  205. extern cl::opt<bool> DisablePreInliner;
  206. extern cl::opt<int> PreInlineThreshold;
  207. } // namespace llvm
  208. void PassBuilder::invokePeepholeEPCallbacks(FunctionPassManager &FPM,
  209. OptimizationLevel Level) {
  210. for (auto &C : PeepholeEPCallbacks)
  211. C(FPM, Level);
  212. }
  213. // Helper to add AnnotationRemarksPass.
  214. static void addAnnotationRemarksPass(ModulePassManager &MPM) {
  215. FunctionPassManager FPM;
  216. FPM.addPass(AnnotationRemarksPass());
  217. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  218. }
  219. // Helper to check if the current compilation phase is preparing for LTO
  220. static bool isLTOPreLink(ThinOrFullLTOPhase Phase) {
  221. return Phase == ThinOrFullLTOPhase::ThinLTOPreLink ||
  222. Phase == ThinOrFullLTOPhase::FullLTOPreLink;
  223. }
  224. // TODO: Investigate the cost/benefit of tail call elimination on debugging.
  225. FunctionPassManager
  226. PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level,
  227. ThinOrFullLTOPhase Phase) {
  228. FunctionPassManager FPM;
  229. // Form SSA out of local memory accesses after breaking apart aggregates into
  230. // scalars.
  231. FPM.addPass(SROAPass());
  232. // Catch trivial redundancies
  233. FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
  234. // Hoisting of scalars and load expressions.
  235. FPM.addPass(
  236. SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
  237. FPM.addPass(InstCombinePass());
  238. FPM.addPass(LibCallsShrinkWrapPass());
  239. invokePeepholeEPCallbacks(FPM, Level);
  240. FPM.addPass(
  241. SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
  242. // Form canonically associated expression trees, and simplify the trees using
  243. // basic mathematical properties. For example, this will form (nearly)
  244. // minimal multiplication trees.
  245. FPM.addPass(ReassociatePass());
  246. // Add the primary loop simplification pipeline.
  247. // FIXME: Currently this is split into two loop pass pipelines because we run
  248. // some function passes in between them. These can and should be removed
  249. // and/or replaced by scheduling the loop pass equivalents in the correct
  250. // positions. But those equivalent passes aren't powerful enough yet.
  251. // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
  252. // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
  253. // fully replace `SimplifyCFGPass`, and the closest to the other we have is
  254. // `LoopInstSimplify`.
  255. LoopPassManager LPM1, LPM2;
  256. // Simplify the loop body. We do this initially to clean up after other loop
  257. // passes run, either when iterating on a loop or on inner loops with
  258. // implications on the outer loop.
  259. LPM1.addPass(LoopInstSimplifyPass());
  260. LPM1.addPass(LoopSimplifyCFGPass());
  261. // Try to remove as much code from the loop header as possible,
  262. // to reduce amount of IR that will have to be duplicated. However,
  263. // do not perform speculative hoisting the first time as LICM
  264. // will destroy metadata that may not need to be destroyed if run
  265. // after loop rotation.
  266. // TODO: Investigate promotion cap for O1.
  267. LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
  268. /*AllowSpeculation=*/false));
  269. LPM1.addPass(LoopRotatePass(/* Disable header duplication */ true,
  270. isLTOPreLink(Phase)));
  271. // TODO: Investigate promotion cap for O1.
  272. LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
  273. /*AllowSpeculation=*/true));
  274. LPM1.addPass(SimpleLoopUnswitchPass());
  275. if (EnableLoopFlatten)
  276. LPM1.addPass(LoopFlattenPass());
  277. LPM2.addPass(LoopIdiomRecognizePass());
  278. LPM2.addPass(IndVarSimplifyPass());
  279. for (auto &C : LateLoopOptimizationsEPCallbacks)
  280. C(LPM2, Level);
  281. LPM2.addPass(LoopDeletionPass());
  282. if (EnableLoopInterchange)
  283. LPM2.addPass(LoopInterchangePass());
  284. // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
  285. // because it changes IR to makes profile annotation in back compile
  286. // inaccurate. The normal unroller doesn't pay attention to forced full unroll
  287. // attributes so we need to make sure and allow the full unroll pass to pay
  288. // attention to it.
  289. if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt ||
  290. PGOOpt->Action != PGOOptions::SampleUse)
  291. LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
  292. /* OnlyWhenForced= */ !PTO.LoopUnrolling,
  293. PTO.ForgetAllSCEVInLoopUnroll));
  294. for (auto &C : LoopOptimizerEndEPCallbacks)
  295. C(LPM2, Level);
  296. // We provide the opt remark emitter pass for LICM to use. We only need to do
  297. // this once as it is immutable.
  298. FPM.addPass(
  299. RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
  300. FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
  301. /*UseMemorySSA=*/true,
  302. /*UseBlockFrequencyInfo=*/true));
  303. FPM.addPass(
  304. SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
  305. FPM.addPass(InstCombinePass());
  306. // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA.
  307. // *All* loop passes must preserve it, in order to be able to use it.
  308. FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
  309. /*UseMemorySSA=*/false,
  310. /*UseBlockFrequencyInfo=*/false));
  311. // Delete small array after loop unroll.
  312. FPM.addPass(SROAPass());
  313. // Specially optimize memory movement as it doesn't look like dataflow in SSA.
  314. FPM.addPass(MemCpyOptPass());
  315. // Sparse conditional constant propagation.
  316. // FIXME: It isn't clear why we do this *after* loop passes rather than
  317. // before...
  318. FPM.addPass(SCCPPass());
  319. // Delete dead bit computations (instcombine runs after to fold away the dead
  320. // computations, and then ADCE will run later to exploit any new DCE
  321. // opportunities that creates).
  322. FPM.addPass(BDCEPass());
  323. // Run instcombine after redundancy and dead bit elimination to exploit
  324. // opportunities opened up by them.
  325. FPM.addPass(InstCombinePass());
  326. invokePeepholeEPCallbacks(FPM, Level);
  327. FPM.addPass(CoroElidePass());
  328. for (auto &C : ScalarOptimizerLateEPCallbacks)
  329. C(FPM, Level);
  330. // Finally, do an expensive DCE pass to catch all the dead code exposed by
  331. // the simplifications and basic cleanup after all the simplifications.
  332. // TODO: Investigate if this is too expensive.
  333. FPM.addPass(ADCEPass());
  334. FPM.addPass(
  335. SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
  336. FPM.addPass(InstCombinePass());
  337. invokePeepholeEPCallbacks(FPM, Level);
  338. return FPM;
  339. }
  340. FunctionPassManager
  341. PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
  342. ThinOrFullLTOPhase Phase) {
  343. assert(Level != OptimizationLevel::O0 && "Must request optimizations!");
  344. // The O1 pipeline has a separate pipeline creation function to simplify
  345. // construction readability.
  346. if (Level.getSpeedupLevel() == 1)
  347. return buildO1FunctionSimplificationPipeline(Level, Phase);
  348. FunctionPassManager FPM;
  349. // Form SSA out of local memory accesses after breaking apart aggregates into
  350. // scalars.
  351. FPM.addPass(SROAPass());
  352. // Catch trivial redundancies
  353. FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
  354. if (EnableKnowledgeRetention)
  355. FPM.addPass(AssumeSimplifyPass());
  356. // Hoisting of scalars and load expressions.
  357. if (EnableGVNHoist)
  358. FPM.addPass(GVNHoistPass());
  359. // Global value numbering based sinking.
  360. if (EnableGVNSink) {
  361. FPM.addPass(GVNSinkPass());
  362. FPM.addPass(
  363. SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
  364. }
  365. if (EnableConstraintElimination)
  366. FPM.addPass(ConstraintEliminationPass());
  367. // Speculative execution if the target has divergent branches; otherwise nop.
  368. FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true));
  369. // Optimize based on known information about branches, and cleanup afterward.
  370. FPM.addPass(JumpThreadingPass());
  371. FPM.addPass(CorrelatedValuePropagationPass());
  372. FPM.addPass(
  373. SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
  374. FPM.addPass(InstCombinePass());
  375. if (Level == OptimizationLevel::O3)
  376. FPM.addPass(AggressiveInstCombinePass());
  377. if (!Level.isOptimizingForSize())
  378. FPM.addPass(LibCallsShrinkWrapPass());
  379. invokePeepholeEPCallbacks(FPM, Level);
  380. // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
  381. // using the size value profile. Don't perform this when optimizing for size.
  382. if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
  383. !Level.isOptimizingForSize())
  384. FPM.addPass(PGOMemOPSizeOpt());
  385. FPM.addPass(TailCallElimPass());
  386. FPM.addPass(
  387. SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
  388. // Form canonically associated expression trees, and simplify the trees using
  389. // basic mathematical properties. For example, this will form (nearly)
  390. // minimal multiplication trees.
  391. FPM.addPass(ReassociatePass());
  392. // Add the primary loop simplification pipeline.
  393. // FIXME: Currently this is split into two loop pass pipelines because we run
  394. // some function passes in between them. These can and should be removed
  395. // and/or replaced by scheduling the loop pass equivalents in the correct
  396. // positions. But those equivalent passes aren't powerful enough yet.
  397. // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
  398. // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
  399. // fully replace `SimplifyCFGPass`, and the closest to the other we have is
  400. // `LoopInstSimplify`.
  401. LoopPassManager LPM1, LPM2;
  402. // Simplify the loop body. We do this initially to clean up after other loop
  403. // passes run, either when iterating on a loop or on inner loops with
  404. // implications on the outer loop.
  405. LPM1.addPass(LoopInstSimplifyPass());
  406. LPM1.addPass(LoopSimplifyCFGPass());
  407. // Try to remove as much code from the loop header as possible,
  408. // to reduce amount of IR that will have to be duplicated. However,
  409. // do not perform speculative hoisting the first time as LICM
  410. // will destroy metadata that may not need to be destroyed if run
  411. // after loop rotation.
  412. // TODO: Investigate promotion cap for O1.
  413. LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
  414. /*AllowSpeculation=*/false));
  415. // Disable header duplication in loop rotation at -Oz.
  416. LPM1.addPass(
  417. LoopRotatePass(Level != OptimizationLevel::Oz, isLTOPreLink(Phase)));
  418. // TODO: Investigate promotion cap for O1.
  419. LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
  420. /*AllowSpeculation=*/true));
  421. LPM1.addPass(
  422. SimpleLoopUnswitchPass(/* NonTrivial */ Level == OptimizationLevel::O3 &&
  423. EnableO3NonTrivialUnswitching));
  424. if (EnableLoopFlatten)
  425. LPM1.addPass(LoopFlattenPass());
  426. LPM2.addPass(LoopIdiomRecognizePass());
  427. LPM2.addPass(IndVarSimplifyPass());
  428. for (auto &C : LateLoopOptimizationsEPCallbacks)
  429. C(LPM2, Level);
  430. LPM2.addPass(LoopDeletionPass());
  431. if (EnableLoopInterchange)
  432. LPM2.addPass(LoopInterchangePass());
  433. // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
  434. // because it changes IR to makes profile annotation in back compile
  435. // inaccurate. The normal unroller doesn't pay attention to forced full unroll
  436. // attributes so we need to make sure and allow the full unroll pass to pay
  437. // attention to it.
  438. if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt ||
  439. PGOOpt->Action != PGOOptions::SampleUse)
  440. LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
  441. /* OnlyWhenForced= */ !PTO.LoopUnrolling,
  442. PTO.ForgetAllSCEVInLoopUnroll));
  443. for (auto &C : LoopOptimizerEndEPCallbacks)
  444. C(LPM2, Level);
  445. // We provide the opt remark emitter pass for LICM to use. We only need to do
  446. // this once as it is immutable.
  447. FPM.addPass(
  448. RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
  449. FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
  450. /*UseMemorySSA=*/true,
  451. /*UseBlockFrequencyInfo=*/true));
  452. FPM.addPass(
  453. SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
  454. FPM.addPass(InstCombinePass());
  455. // The loop passes in LPM2 (LoopIdiomRecognizePass, IndVarSimplifyPass,
  456. // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
  457. // *All* loop passes must preserve it, in order to be able to use it.
  458. FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
  459. /*UseMemorySSA=*/false,
  460. /*UseBlockFrequencyInfo=*/false));
  461. // Delete small array after loop unroll.
  462. FPM.addPass(SROAPass());
  463. // The matrix extension can introduce large vector operations early, which can
  464. // benefit from running vector-combine early on.
  465. if (EnableMatrix)
  466. FPM.addPass(VectorCombinePass(/*ScalarizationOnly=*/true));
  467. // Eliminate redundancies.
  468. FPM.addPass(MergedLoadStoreMotionPass());
  469. if (RunNewGVN)
  470. FPM.addPass(NewGVNPass());
  471. else
  472. FPM.addPass(GVNPass());
  473. // Sparse conditional constant propagation.
  474. // FIXME: It isn't clear why we do this *after* loop passes rather than
  475. // before...
  476. FPM.addPass(SCCPPass());
  477. // Delete dead bit computations (instcombine runs after to fold away the dead
  478. // computations, and then ADCE will run later to exploit any new DCE
  479. // opportunities that creates).
  480. FPM.addPass(BDCEPass());
  481. // Run instcombine after redundancy and dead bit elimination to exploit
  482. // opportunities opened up by them.
  483. FPM.addPass(InstCombinePass());
  484. invokePeepholeEPCallbacks(FPM, Level);
  485. // Re-consider control flow based optimizations after redundancy elimination,
  486. // redo DCE, etc.
  487. if (EnableDFAJumpThreading && Level.getSizeLevel() == 0)
  488. FPM.addPass(DFAJumpThreadingPass());
  489. FPM.addPass(JumpThreadingPass());
  490. FPM.addPass(CorrelatedValuePropagationPass());
  491. // Finally, do an expensive DCE pass to catch all the dead code exposed by
  492. // the simplifications and basic cleanup after all the simplifications.
  493. // TODO: Investigate if this is too expensive.
  494. FPM.addPass(ADCEPass());
  495. // Specially optimize memory movement as it doesn't look like dataflow in SSA.
  496. FPM.addPass(MemCpyOptPass());
  497. FPM.addPass(DSEPass());
  498. FPM.addPass(createFunctionToLoopPassAdaptor(
  499. LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
  500. /*AllowSpeculation=*/true),
  501. /*UseMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true));
  502. FPM.addPass(CoroElidePass());
  503. for (auto &C : ScalarOptimizerLateEPCallbacks)
  504. C(FPM, Level);
  505. FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions()
  506. .convertSwitchRangeToICmp(true)
  507. .hoistCommonInsts(true)
  508. .sinkCommonInsts(true)));
  509. FPM.addPass(InstCombinePass());
  510. invokePeepholeEPCallbacks(FPM, Level);
  511. if (EnableCHR && Level == OptimizationLevel::O3 && PGOOpt &&
  512. (PGOOpt->Action == PGOOptions::IRUse ||
  513. PGOOpt->Action == PGOOptions::SampleUse))
  514. FPM.addPass(ControlHeightReductionPass());
  515. return FPM;
  516. }
  517. void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) {
  518. MPM.addPass(CanonicalizeAliasesPass());
  519. MPM.addPass(NameAnonGlobalPass());
  520. }
  521. void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM,
  522. OptimizationLevel Level, bool RunProfileGen,
  523. bool IsCS, std::string ProfileFile,
  524. std::string ProfileRemappingFile) {
  525. assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
  526. if (!IsCS && !DisablePreInliner) {
  527. InlineParams IP;
  528. IP.DefaultThreshold = PreInlineThreshold;
  529. // FIXME: The hint threshold has the same value used by the regular inliner
  530. // when not optimzing for size. This should probably be lowered after
  531. // performance testing.
  532. // FIXME: this comment is cargo culted from the old pass manager, revisit).
  533. IP.HintThreshold = Level.isOptimizingForSize() ? PreInlineThreshold : 325;
  534. ModuleInlinerWrapperPass MIWP(IP);
  535. CGSCCPassManager &CGPipeline = MIWP.getPM();
  536. FunctionPassManager FPM;
  537. FPM.addPass(SROAPass());
  538. FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
  539. FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(
  540. true))); // Merge & remove basic blocks.
  541. FPM.addPass(InstCombinePass()); // Combine silly sequences.
  542. invokePeepholeEPCallbacks(FPM, Level);
  543. CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
  544. std::move(FPM), PTO.EagerlyInvalidateAnalyses));
  545. MPM.addPass(std::move(MIWP));
  546. // Delete anything that is now dead to make sure that we don't instrument
  547. // dead code. Instrumentation can end up keeping dead code around and
  548. // dramatically increase code size.
  549. MPM.addPass(GlobalDCEPass());
  550. }
  551. if (!RunProfileGen) {
  552. assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
  553. MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
  554. // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
  555. // RequireAnalysisPass for PSI before subsequent non-module passes.
  556. MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
  557. return;
  558. }
  559. // Perform PGO instrumentation.
  560. MPM.addPass(PGOInstrumentationGen(IsCS));
  561. FunctionPassManager FPM;
  562. // Disable header duplication in loop rotation at -Oz.
  563. FPM.addPass(createFunctionToLoopPassAdaptor(
  564. LoopRotatePass(Level != OptimizationLevel::Oz), /*UseMemorySSA=*/false,
  565. /*UseBlockFrequencyInfo=*/false));
  566. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),
  567. PTO.EagerlyInvalidateAnalyses));
  568. // Add the profile lowering pass.
  569. InstrProfOptions Options;
  570. if (!ProfileFile.empty())
  571. Options.InstrProfileOutput = ProfileFile;
  572. // Do counter promotion at Level greater than O0.
  573. Options.DoCounterPromotion = true;
  574. Options.UseBFIInPromotion = IsCS;
  575. MPM.addPass(InstrProfiling(Options, IsCS));
  576. }
  577. void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM,
  578. bool RunProfileGen, bool IsCS,
  579. std::string ProfileFile,
  580. std::string ProfileRemappingFile) {
  581. if (!RunProfileGen) {
  582. assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
  583. MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
  584. // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
  585. // RequireAnalysisPass for PSI before subsequent non-module passes.
  586. MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
  587. return;
  588. }
  589. // Perform PGO instrumentation.
  590. MPM.addPass(PGOInstrumentationGen(IsCS));
  591. // Add the profile lowering pass.
  592. InstrProfOptions Options;
  593. if (!ProfileFile.empty())
  594. Options.InstrProfileOutput = ProfileFile;
  595. // Do not do counter promotion at O0.
  596. Options.DoCounterPromotion = false;
  597. Options.UseBFIInPromotion = IsCS;
  598. MPM.addPass(InstrProfiling(Options, IsCS));
  599. }
  600. static InlineParams getInlineParamsFromOptLevel(OptimizationLevel Level) {
  601. return getInlineParams(Level.getSpeedupLevel(), Level.getSizeLevel());
  602. }
  603. ModuleInlinerWrapperPass
  604. PassBuilder::buildInlinerPipeline(OptimizationLevel Level,
  605. ThinOrFullLTOPhase Phase) {
  606. InlineParams IP = getInlineParamsFromOptLevel(Level);
  607. if (Phase == ThinOrFullLTOPhase::ThinLTOPreLink && PGOOpt &&
  608. PGOOpt->Action == PGOOptions::SampleUse)
  609. IP.HotCallSiteThreshold = 0;
  610. if (PGOOpt)
  611. IP.EnableDeferral = EnablePGOInlineDeferral;
  612. ModuleInlinerWrapperPass MIWP(IP, PerformMandatoryInliningsFirst,
  613. UseInlineAdvisor, MaxDevirtIterations);
  614. // Require the GlobalsAA analysis for the module so we can query it within
  615. // the CGSCC pipeline.
  616. MIWP.addModulePass(RequireAnalysisPass<GlobalsAA, Module>());
  617. // Invalidate AAManager so it can be recreated and pick up the newly available
  618. // GlobalsAA.
  619. MIWP.addModulePass(
  620. createModuleToFunctionPassAdaptor(InvalidateAnalysisPass<AAManager>()));
  621. // Require the ProfileSummaryAnalysis for the module so we can query it within
  622. // the inliner pass.
  623. MIWP.addModulePass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
  624. // Now begin the main postorder CGSCC pipeline.
  625. // FIXME: The current CGSCC pipeline has its origins in the legacy pass
  626. // manager and trying to emulate its precise behavior. Much of this doesn't
  627. // make a lot of sense and we should revisit the core CGSCC structure.
  628. CGSCCPassManager &MainCGPipeline = MIWP.getPM();
  629. // Note: historically, the PruneEH pass was run first to deduce nounwind and
  630. // generally clean up exception handling overhead. It isn't clear this is
  631. // valuable as the inliner doesn't currently care whether it is inlining an
  632. // invoke or a call.
  633. if (AttributorRun & AttributorRunOption::CGSCC)
  634. MainCGPipeline.addPass(AttributorCGSCCPass());
  635. // Now deduce any function attributes based in the current code.
  636. MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
  637. // When at O3 add argument promotion to the pass pipeline.
  638. // FIXME: It isn't at all clear why this should be limited to O3.
  639. if (Level == OptimizationLevel::O3)
  640. MainCGPipeline.addPass(ArgumentPromotionPass());
  641. // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
  642. // there are no OpenMP runtime calls present in the module.
  643. if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3)
  644. MainCGPipeline.addPass(OpenMPOptCGSCCPass());
  645. for (auto &C : CGSCCOptimizerLateEPCallbacks)
  646. C(MainCGPipeline, Level);
  647. // Lastly, add the core function simplification pipeline nested inside the
  648. // CGSCC walk.
  649. MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
  650. buildFunctionSimplificationPipeline(Level, Phase),
  651. PTO.EagerlyInvalidateAnalyses, EnableNoRerunSimplificationPipeline));
  652. MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0));
  653. if (EnableNoRerunSimplificationPipeline)
  654. MIWP.addLateModulePass(createModuleToFunctionPassAdaptor(
  655. InvalidateAnalysisPass<ShouldNotRunFunctionPassesAnalysis>()));
  656. return MIWP;
  657. }
  658. ModulePassManager
  659. PassBuilder::buildModuleInlinerPipeline(OptimizationLevel Level,
  660. ThinOrFullLTOPhase Phase) {
  661. ModulePassManager MPM;
  662. InlineParams IP = getInlineParamsFromOptLevel(Level);
  663. if (Phase == ThinOrFullLTOPhase::ThinLTOPreLink && PGOOpt &&
  664. PGOOpt->Action == PGOOptions::SampleUse)
  665. IP.HotCallSiteThreshold = 0;
  666. if (PGOOpt)
  667. IP.EnableDeferral = EnablePGOInlineDeferral;
  668. // The inline deferral logic is used to avoid losing some
  669. // inlining chance in future. It is helpful in SCC inliner, in which
  670. // inlining is processed in bottom-up order.
  671. // While in module inliner, the inlining order is a priority-based order
  672. // by default. The inline deferral is unnecessary there. So we disable the
  673. // inline deferral logic in module inliner.
  674. IP.EnableDeferral = false;
  675. MPM.addPass(ModuleInlinerPass(IP, UseInlineAdvisor));
  676. MPM.addPass(createModuleToFunctionPassAdaptor(
  677. buildFunctionSimplificationPipeline(Level, Phase),
  678. PTO.EagerlyInvalidateAnalyses));
  679. MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
  680. CoroSplitPass(Level != OptimizationLevel::O0)));
  681. return MPM;
  682. }
  683. ModulePassManager
  684. PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
  685. ThinOrFullLTOPhase Phase) {
  686. ModulePassManager MPM;
  687. // Place pseudo probe instrumentation as the first pass of the pipeline to
  688. // minimize the impact of optimization changes.
  689. if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
  690. Phase != ThinOrFullLTOPhase::ThinLTOPostLink)
  691. MPM.addPass(SampleProfileProbePass(TM));
  692. bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
  693. // In ThinLTO mode, when flattened profile is used, all the available
  694. // profile information will be annotated in PreLink phase so there is
  695. // no need to load the profile again in PostLink.
  696. bool LoadSampleProfile =
  697. HasSampleProfile &&
  698. !(FlattenedProfileUsed && Phase == ThinOrFullLTOPhase::ThinLTOPostLink);
  699. // During the ThinLTO backend phase we perform early indirect call promotion
  700. // here, before globalopt. Otherwise imported available_externally functions
  701. // look unreferenced and are removed. If we are going to load the sample
  702. // profile then defer until later.
  703. // TODO: See if we can move later and consolidate with the location where
  704. // we perform ICP when we are loading a sample profile.
  705. // TODO: We pass HasSampleProfile (whether there was a sample profile file
  706. // passed to the compile) to the SamplePGO flag of ICP. This is used to
  707. // determine whether the new direct calls are annotated with prof metadata.
  708. // Ideally this should be determined from whether the IR is annotated with
  709. // sample profile, and not whether the a sample profile was provided on the
  710. // command line. E.g. for flattened profiles where we will not be reloading
  711. // the sample profile in the ThinLTO backend, we ideally shouldn't have to
  712. // provide the sample profile file.
  713. if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink && !LoadSampleProfile)
  714. MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
  715. // Do basic inference of function attributes from known properties of system
  716. // libraries and other oracles.
  717. MPM.addPass(InferFunctionAttrsPass());
  718. // Create an early function pass manager to cleanup the output of the
  719. // frontend.
  720. FunctionPassManager EarlyFPM;
  721. // Lower llvm.expect to metadata before attempting transforms.
  722. // Compare/branch metadata may alter the behavior of passes like SimplifyCFG.
  723. EarlyFPM.addPass(LowerExpectIntrinsicPass());
  724. EarlyFPM.addPass(SimplifyCFGPass());
  725. EarlyFPM.addPass(SROAPass());
  726. EarlyFPM.addPass(EarlyCSEPass());
  727. EarlyFPM.addPass(CoroEarlyPass());
  728. if (Level == OptimizationLevel::O3)
  729. EarlyFPM.addPass(CallSiteSplittingPass());
  730. // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
  731. // to convert bitcast to direct calls so that they can be inlined during the
  732. // profile annotation prepration step.
  733. // More details about SamplePGO design can be found in:
  734. // https://research.google.com/pubs/pub45290.html
  735. // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
  736. if (LoadSampleProfile)
  737. EarlyFPM.addPass(InstCombinePass());
  738. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM),
  739. PTO.EagerlyInvalidateAnalyses));
  740. if (LoadSampleProfile) {
  741. // Annotate sample profile right after early FPM to ensure freshness of
  742. // the debug info.
  743. MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
  744. PGOOpt->ProfileRemappingFile, Phase));
  745. // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
  746. // RequireAnalysisPass for PSI before subsequent non-module passes.
  747. MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
  748. // Do not invoke ICP in the LTOPrelink phase as it makes it hard
  749. // for the profile annotation to be accurate in the LTO backend.
  750. if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink &&
  751. Phase != ThinOrFullLTOPhase::FullLTOPreLink)
  752. // We perform early indirect call promotion here, before globalopt.
  753. // This is important for the ThinLTO backend phase because otherwise
  754. // imported available_externally functions look unreferenced and are
  755. // removed.
  756. MPM.addPass(
  757. PGOIndirectCallPromotion(true /* IsInLTO */, true /* SamplePGO */));
  758. }
  759. // Try to perform OpenMP specific optimizations on the module. This is a
  760. // (quick!) no-op if there are no OpenMP runtime calls present in the module.
  761. if (Level != OptimizationLevel::O0)
  762. MPM.addPass(OpenMPOptPass());
  763. if (AttributorRun & AttributorRunOption::MODULE)
  764. MPM.addPass(AttributorPass());
  765. // Lower type metadata and the type.test intrinsic in the ThinLTO
  766. // post link pipeline after ICP. This is to enable usage of the type
  767. // tests in ICP sequences.
  768. if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink)
  769. MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
  770. for (auto &C : PipelineEarlySimplificationEPCallbacks)
  771. C(MPM, Level);
  772. // Specialize functions with IPSCCP.
  773. if (EnableFunctionSpecialization && Level == OptimizationLevel::O3)
  774. MPM.addPass(FunctionSpecializationPass());
  775. // Interprocedural constant propagation now that basic cleanup has occurred
  776. // and prior to optimizing globals.
  777. // FIXME: This position in the pipeline hasn't been carefully considered in
  778. // years, it should be re-analyzed.
  779. MPM.addPass(IPSCCPPass());
  780. // Attach metadata to indirect call sites indicating the set of functions
  781. // they may target at run-time. This should follow IPSCCP.
  782. MPM.addPass(CalledValuePropagationPass());
  783. // Optimize globals to try and fold them into constants.
  784. MPM.addPass(GlobalOptPass());
  785. // Promote any localized globals to SSA registers.
  786. // FIXME: Should this instead by a run of SROA?
  787. // FIXME: We should probably run instcombine and simplifycfg afterward to
  788. // delete control flows that are dead once globals have been folded to
  789. // constants.
  790. MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
  791. // Remove any dead arguments exposed by cleanups and constant folding
  792. // globals.
  793. MPM.addPass(DeadArgumentEliminationPass());
  794. // Create a small function pass pipeline to cleanup after all the global
  795. // optimizations.
  796. FunctionPassManager GlobalCleanupPM;
  797. GlobalCleanupPM.addPass(InstCombinePass());
  798. invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
  799. GlobalCleanupPM.addPass(
  800. SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
  801. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM),
  802. PTO.EagerlyInvalidateAnalyses));
  803. // Add all the requested passes for instrumentation PGO, if requested.
  804. if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink &&
  805. (PGOOpt->Action == PGOOptions::IRInstr ||
  806. PGOOpt->Action == PGOOptions::IRUse)) {
  807. addPGOInstrPasses(MPM, Level,
  808. /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
  809. /* IsCS */ false, PGOOpt->ProfileFile,
  810. PGOOpt->ProfileRemappingFile);
  811. MPM.addPass(PGOIndirectCallPromotion(false, false));
  812. }
  813. if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink &&
  814. PGOOpt->CSAction == PGOOptions::CSIRInstr)
  815. MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
  816. // Synthesize function entry counts for non-PGO compilation.
  817. if (EnableSyntheticCounts && !PGOOpt)
  818. MPM.addPass(SyntheticCountsPropagation());
  819. if (EnableModuleInliner)
  820. MPM.addPass(buildModuleInlinerPipeline(Level, Phase));
  821. else
  822. MPM.addPass(buildInlinerPipeline(Level, Phase));
  823. if (EnableMemProfiler && Phase != ThinOrFullLTOPhase::ThinLTOPreLink) {
  824. MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
  825. MPM.addPass(ModuleMemProfilerPass());
  826. }
  827. return MPM;
  828. }
  829. /// TODO: Should LTO cause any differences to this set of passes?
  830. void PassBuilder::addVectorPasses(OptimizationLevel Level,
  831. FunctionPassManager &FPM, bool IsFullLTO) {
  832. FPM.addPass(LoopVectorizePass(
  833. LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
  834. if (IsFullLTO) {
  835. // The vectorizer may have significantly shortened a loop body; unroll
  836. // again. Unroll small loops to hide loop backedge latency and saturate any
  837. // parallel execution resources of an out-of-order processor. We also then
  838. // need to clean up redundancies and loop invariant code.
  839. // FIXME: It would be really good to use a loop-integrated instruction
  840. // combiner for cleanup here so that the unrolling and LICM can be pipelined
  841. // across the loop nests.
  842. // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
  843. if (EnableUnrollAndJam && PTO.LoopUnrolling)
  844. FPM.addPass(createFunctionToLoopPassAdaptor(
  845. LoopUnrollAndJamPass(Level.getSpeedupLevel())));
  846. FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
  847. Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
  848. PTO.ForgetAllSCEVInLoopUnroll)));
  849. FPM.addPass(WarnMissedTransformationsPass());
  850. }
  851. if (!IsFullLTO) {
  852. // Eliminate loads by forwarding stores from the previous iteration to loads
  853. // of the current iteration.
  854. FPM.addPass(LoopLoadEliminationPass());
  855. }
  856. // Cleanup after the loop optimization passes.
  857. FPM.addPass(InstCombinePass());
  858. if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) {
  859. ExtraVectorPassManager ExtraPasses;
  860. // At higher optimization levels, try to clean up any runtime overlap and
  861. // alignment checks inserted by the vectorizer. We want to track correlated
  862. // runtime checks for two inner loops in the same outer loop, fold any
  863. // common computations, hoist loop-invariant aspects out of any outer loop,
  864. // and unswitch the runtime checks if possible. Once hoisted, we may have
  865. // dead (or speculatable) control flows or more combining opportunities.
  866. ExtraPasses.addPass(EarlyCSEPass());
  867. ExtraPasses.addPass(CorrelatedValuePropagationPass());
  868. ExtraPasses.addPass(InstCombinePass());
  869. LoopPassManager LPM;
  870. LPM.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
  871. /*AllowSpeculation=*/true));
  872. LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
  873. OptimizationLevel::O3));
  874. ExtraPasses.addPass(
  875. RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
  876. ExtraPasses.addPass(
  877. createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/true,
  878. /*UseBlockFrequencyInfo=*/true));
  879. ExtraPasses.addPass(
  880. SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
  881. ExtraPasses.addPass(InstCombinePass());
  882. FPM.addPass(std::move(ExtraPasses));
  883. }
  884. // Now that we've formed fast to execute loop structures, we do further
  885. // optimizations. These are run afterward as they might block doing complex
  886. // analyses and transforms such as what are needed for loop vectorization.
  887. // Cleanup after loop vectorization, etc. Simplification passes like CVP and
  888. // GVN, loop transforms, and others have already run, so it's now better to
  889. // convert to more optimized IR using more aggressive simplify CFG options.
  890. // The extra sinking transform can create larger basic blocks, so do this
  891. // before SLP vectorization.
  892. FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions()
  893. .forwardSwitchCondToPhi(true)
  894. .convertSwitchRangeToICmp(true)
  895. .convertSwitchToLookupTable(true)
  896. .needCanonicalLoops(false)
  897. .hoistCommonInsts(true)
  898. .sinkCommonInsts(true)));
  899. if (IsFullLTO) {
  900. FPM.addPass(SCCPPass());
  901. FPM.addPass(InstCombinePass());
  902. FPM.addPass(BDCEPass());
  903. }
  904. // Optimize parallel scalar instruction chains into SIMD instructions.
  905. if (PTO.SLPVectorization) {
  906. FPM.addPass(SLPVectorizerPass());
  907. if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) {
  908. FPM.addPass(EarlyCSEPass());
  909. }
  910. }
  911. // Enhance/cleanup vector code.
  912. FPM.addPass(VectorCombinePass());
  913. if (!IsFullLTO) {
  914. FPM.addPass(InstCombinePass());
  915. // Unroll small loops to hide loop backedge latency and saturate any
  916. // parallel execution resources of an out-of-order processor. We also then
  917. // need to clean up redundancies and loop invariant code.
  918. // FIXME: It would be really good to use a loop-integrated instruction
  919. // combiner for cleanup here so that the unrolling and LICM can be pipelined
  920. // across the loop nests.
  921. // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
  922. if (EnableUnrollAndJam && PTO.LoopUnrolling) {
  923. FPM.addPass(createFunctionToLoopPassAdaptor(
  924. LoopUnrollAndJamPass(Level.getSpeedupLevel())));
  925. }
  926. FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
  927. Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
  928. PTO.ForgetAllSCEVInLoopUnroll)));
  929. FPM.addPass(WarnMissedTransformationsPass());
  930. FPM.addPass(InstCombinePass());
  931. FPM.addPass(
  932. RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
  933. FPM.addPass(createFunctionToLoopPassAdaptor(
  934. LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
  935. /*AllowSpeculation=*/true),
  936. /*UseMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true));
  937. }
  938. // Now that we've vectorized and unrolled loops, we may have more refined
  939. // alignment information, try to re-derive it here.
  940. FPM.addPass(AlignmentFromAssumptionsPass());
  941. if (IsFullLTO)
  942. FPM.addPass(InstCombinePass());
  943. }
  944. ModulePassManager
  945. PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
  946. bool LTOPreLink) {
  947. ModulePassManager MPM;
  948. // Optimize globals now that the module is fully simplified.
  949. MPM.addPass(GlobalOptPass());
  950. MPM.addPass(GlobalDCEPass());
  951. // Run partial inlining pass to partially inline functions that have
  952. // large bodies.
  953. if (RunPartialInlining)
  954. MPM.addPass(PartialInlinerPass());
  955. // Remove avail extern fns and globals definitions since we aren't compiling
  956. // an object file for later LTO. For LTO we want to preserve these so they
  957. // are eligible for inlining at link-time. Note if they are unreferenced they
  958. // will be removed by GlobalDCE later, so this only impacts referenced
  959. // available externally globals. Eventually they will be suppressed during
  960. // codegen, but eliminating here enables more opportunity for GlobalDCE as it
  961. // may make globals referenced by available external functions dead and saves
  962. // running remaining passes on the eliminated functions. These should be
  963. // preserved during prelinking for link-time inlining decisions.
  964. if (!LTOPreLink)
  965. MPM.addPass(EliminateAvailableExternallyPass());
  966. if (EnableOrderFileInstrumentation)
  967. MPM.addPass(InstrOrderFilePass());
  968. // Do RPO function attribute inference across the module to forward-propagate
  969. // attributes where applicable.
  970. // FIXME: Is this really an optimization rather than a canonicalization?
  971. MPM.addPass(ReversePostOrderFunctionAttrsPass());
  972. // Do a post inline PGO instrumentation and use pass. This is a context
  973. // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
  974. // cross-module inline has not been done yet. The context sensitive
  975. // instrumentation is after all the inlines are done.
  976. if (!LTOPreLink && PGOOpt) {
  977. if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
  978. addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true,
  979. /* IsCS */ true, PGOOpt->CSProfileGenFile,
  980. PGOOpt->ProfileRemappingFile);
  981. else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
  982. addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false,
  983. /* IsCS */ true, PGOOpt->ProfileFile,
  984. PGOOpt->ProfileRemappingFile);
  985. }
  986. // Re-require GloblasAA here prior to function passes. This is particularly
  987. // useful as the above will have inlined, DCE'ed, and function-attr
  988. // propagated everything. We should at this point have a reasonably minimal
  989. // and richly annotated call graph. By computing aliasing and mod/ref
  990. // information for all local globals here, the late loop passes and notably
  991. // the vectorizer will be able to use them to help recognize vectorizable
  992. // memory operations.
  993. MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
  994. FunctionPassManager OptimizePM;
  995. OptimizePM.addPass(Float2IntPass());
  996. OptimizePM.addPass(LowerConstantIntrinsicsPass());
  997. if (EnableMatrix) {
  998. OptimizePM.addPass(LowerMatrixIntrinsicsPass());
  999. OptimizePM.addPass(EarlyCSEPass());
  1000. }
  1001. // FIXME: We need to run some loop optimizations to re-rotate loops after
  1002. // simplifycfg and others undo their rotation.
  1003. // Optimize the loop execution. These passes operate on entire loop nests
  1004. // rather than on each loop in an inside-out manner, and so they are actually
  1005. // function passes.
  1006. for (auto &C : VectorizerStartEPCallbacks)
  1007. C(OptimizePM, Level);
  1008. LoopPassManager LPM;
  1009. // First rotate loops that may have been un-rotated by prior passes.
  1010. // Disable header duplication at -Oz.
  1011. LPM.addPass(LoopRotatePass(Level != OptimizationLevel::Oz, LTOPreLink));
  1012. // Some loops may have become dead by now. Try to delete them.
  1013. // FIXME: see discussion in https://reviews.llvm.org/D112851,
  1014. // this may need to be revisited once we run GVN before loop deletion
  1015. // in the simplification pipeline.
  1016. LPM.addPass(LoopDeletionPass());
  1017. OptimizePM.addPass(createFunctionToLoopPassAdaptor(
  1018. std::move(LPM), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/false));
  1019. // Distribute loops to allow partial vectorization. I.e. isolate dependences
  1020. // into separate loop that would otherwise inhibit vectorization. This is
  1021. // currently only performed for loops marked with the metadata
  1022. // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
  1023. OptimizePM.addPass(LoopDistributePass());
  1024. // Populates the VFABI attribute with the scalar-to-vector mappings
  1025. // from the TargetLibraryInfo.
  1026. OptimizePM.addPass(InjectTLIMappings());
  1027. addVectorPasses(Level, OptimizePM, /* IsFullLTO */ false);
  1028. // LoopSink pass sinks instructions hoisted by LICM, which serves as a
  1029. // canonicalization pass that enables other optimizations. As a result,
  1030. // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
  1031. // result too early.
  1032. OptimizePM.addPass(LoopSinkPass());
  1033. // And finally clean up LCSSA form before generating code.
  1034. OptimizePM.addPass(InstSimplifyPass());
  1035. // This hoists/decomposes div/rem ops. It should run after other sink/hoist
  1036. // passes to avoid re-sinking, but before SimplifyCFG because it can allow
  1037. // flattening of blocks.
  1038. OptimizePM.addPass(DivRemPairsPass());
  1039. // LoopSink (and other loop passes since the last simplifyCFG) might have
  1040. // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
  1041. OptimizePM.addPass(
  1042. SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
  1043. OptimizePM.addPass(CoroCleanupPass());
  1044. // Add the core optimizing pipeline.
  1045. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM),
  1046. PTO.EagerlyInvalidateAnalyses));
  1047. for (auto &C : OptimizerLastEPCallbacks)
  1048. C(MPM, Level);
  1049. // Split out cold code. Splitting is done late to avoid hiding context from
  1050. // other optimizations and inadvertently regressing performance. The tradeoff
  1051. // is that this has a higher code size cost than splitting early.
  1052. if (EnableHotColdSplit && !LTOPreLink)
  1053. MPM.addPass(HotColdSplittingPass());
  1054. // Search the code for similar regions of code. If enough similar regions can
  1055. // be found where extracting the regions into their own function will decrease
  1056. // the size of the program, we extract the regions, a deduplicate the
  1057. // structurally similar regions.
  1058. if (EnableIROutliner)
  1059. MPM.addPass(IROutlinerPass());
  1060. // Merge functions if requested.
  1061. if (PTO.MergeFunctions)
  1062. MPM.addPass(MergeFunctionsPass());
  1063. if (PTO.CallGraphProfile)
  1064. MPM.addPass(CGProfilePass());
  1065. // Now we need to do some global optimization transforms.
  1066. // FIXME: It would seem like these should come first in the optimization
  1067. // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
  1068. // ordering here.
  1069. MPM.addPass(GlobalDCEPass());
  1070. MPM.addPass(ConstantMergePass());
  1071. // TODO: Relative look table converter pass caused an issue when full lto is
  1072. // enabled. See https://reviews.llvm.org/D94355 for more details.
  1073. // Until the issue fixed, disable this pass during pre-linking phase.
  1074. if (!LTOPreLink)
  1075. MPM.addPass(RelLookupTableConverterPass());
  1076. return MPM;
  1077. }
  1078. ModulePassManager
  1079. PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
  1080. bool LTOPreLink) {
  1081. assert(Level != OptimizationLevel::O0 &&
  1082. "Must request optimizations for the default pipeline!");
  1083. ModulePassManager MPM;
  1084. // Convert @llvm.global.annotations to !annotation metadata.
  1085. MPM.addPass(Annotation2MetadataPass());
  1086. // Force any function attributes we want the rest of the pipeline to observe.
  1087. MPM.addPass(ForceFunctionAttrsPass());
  1088. // Apply module pipeline start EP callback.
  1089. for (auto &C : PipelineStartEPCallbacks)
  1090. C(MPM, Level);
  1091. if (PGOOpt && PGOOpt->DebugInfoForProfiling)
  1092. MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
  1093. // Add the core simplification pipeline.
  1094. MPM.addPass(buildModuleSimplificationPipeline(
  1095. Level, LTOPreLink ? ThinOrFullLTOPhase::FullLTOPreLink
  1096. : ThinOrFullLTOPhase::None));
  1097. // Now add the optimization pipeline.
  1098. MPM.addPass(buildModuleOptimizationPipeline(Level, LTOPreLink));
  1099. if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
  1100. PGOOpt->Action == PGOOptions::SampleUse)
  1101. MPM.addPass(PseudoProbeUpdatePass());
  1102. // Emit annotation remarks.
  1103. addAnnotationRemarksPass(MPM);
  1104. if (LTOPreLink)
  1105. addRequiredLTOPreLinkPasses(MPM);
  1106. return MPM;
  1107. }
  1108. ModulePassManager
  1109. PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level) {
  1110. assert(Level != OptimizationLevel::O0 &&
  1111. "Must request optimizations for the default pipeline!");
  1112. ModulePassManager MPM;
  1113. // Convert @llvm.global.annotations to !annotation metadata.
  1114. MPM.addPass(Annotation2MetadataPass());
  1115. // Force any function attributes we want the rest of the pipeline to observe.
  1116. MPM.addPass(ForceFunctionAttrsPass());
  1117. if (PGOOpt && PGOOpt->DebugInfoForProfiling)
  1118. MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
  1119. // Apply module pipeline start EP callback.
  1120. for (auto &C : PipelineStartEPCallbacks)
  1121. C(MPM, Level);
  1122. // If we are planning to perform ThinLTO later, we don't bloat the code with
  1123. // unrolling/vectorization/... now. Just simplify the module as much as we
  1124. // can.
  1125. MPM.addPass(buildModuleSimplificationPipeline(
  1126. Level, ThinOrFullLTOPhase::ThinLTOPreLink));
  1127. // Run partial inlining pass to partially inline functions that have
  1128. // large bodies.
  1129. // FIXME: It isn't clear whether this is really the right place to run this
  1130. // in ThinLTO. Because there is another canonicalization and simplification
  1131. // phase that will run after the thin link, running this here ends up with
  1132. // less information than will be available later and it may grow functions in
  1133. // ways that aren't beneficial.
  1134. if (RunPartialInlining)
  1135. MPM.addPass(PartialInlinerPass());
  1136. // Reduce the size of the IR as much as possible.
  1137. MPM.addPass(GlobalOptPass());
  1138. // Module simplification splits coroutines, but does not fully clean up
  1139. // coroutine intrinsics. To ensure ThinLTO optimization passes don't trip up
  1140. // on these, we schedule the cleanup here.
  1141. MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
  1142. if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
  1143. PGOOpt->Action == PGOOptions::SampleUse)
  1144. MPM.addPass(PseudoProbeUpdatePass());
  1145. // Handle OptimizerLastEPCallbacks added by clang on PreLink. Actual
  1146. // optimization is going to be done in PostLink stage, but clang can't
  1147. // add callbacks there in case of in-process ThinLTO called by linker.
  1148. for (auto &C : OptimizerLastEPCallbacks)
  1149. C(MPM, Level);
  1150. // Emit annotation remarks.
  1151. addAnnotationRemarksPass(MPM);
  1152. addRequiredLTOPreLinkPasses(MPM);
  1153. return MPM;
  1154. }
  1155. ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
  1156. OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) {
  1157. ModulePassManager MPM;
  1158. // Convert @llvm.global.annotations to !annotation metadata.
  1159. MPM.addPass(Annotation2MetadataPass());
  1160. if (ImportSummary) {
  1161. // These passes import type identifier resolutions for whole-program
  1162. // devirtualization and CFI. They must run early because other passes may
  1163. // disturb the specific instruction patterns that these passes look for,
  1164. // creating dependencies on resolutions that may not appear in the summary.
  1165. //
  1166. // For example, GVN may transform the pattern assume(type.test) appearing in
  1167. // two basic blocks into assume(phi(type.test, type.test)), which would
  1168. // transform a dependency on a WPD resolution into a dependency on a type
  1169. // identifier resolution for CFI.
  1170. //
  1171. // Also, WPD has access to more precise information than ICP and can
  1172. // devirtualize more effectively, so it should operate on the IR first.
  1173. //
  1174. // The WPD and LowerTypeTest passes need to run at -O0 to lower type
  1175. // metadata and intrinsics.
  1176. MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
  1177. MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
  1178. }
  1179. if (Level == OptimizationLevel::O0) {
  1180. // Run a second time to clean up any type tests left behind by WPD for use
  1181. // in ICP.
  1182. MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
  1183. // Drop available_externally and unreferenced globals. This is necessary
  1184. // with ThinLTO in order to avoid leaving undefined references to dead
  1185. // globals in the object file.
  1186. MPM.addPass(EliminateAvailableExternallyPass());
  1187. MPM.addPass(GlobalDCEPass());
  1188. return MPM;
  1189. }
  1190. // Force any function attributes we want the rest of the pipeline to observe.
  1191. MPM.addPass(ForceFunctionAttrsPass());
  1192. // Add the core simplification pipeline.
  1193. MPM.addPass(buildModuleSimplificationPipeline(
  1194. Level, ThinOrFullLTOPhase::ThinLTOPostLink));
  1195. // Now add the optimization pipeline.
  1196. MPM.addPass(buildModuleOptimizationPipeline(Level));
  1197. // Emit annotation remarks.
  1198. addAnnotationRemarksPass(MPM);
  1199. return MPM;
  1200. }
  1201. ModulePassManager
  1202. PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level) {
  1203. assert(Level != OptimizationLevel::O0 &&
  1204. "Must request optimizations for the default pipeline!");
  1205. // FIXME: We should use a customized pre-link pipeline!
  1206. return buildPerModuleDefaultPipeline(Level,
  1207. /* LTOPreLink */ true);
  1208. }
  1209. ModulePassManager
  1210. PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
  1211. ModuleSummaryIndex *ExportSummary) {
  1212. ModulePassManager MPM;
  1213. // Convert @llvm.global.annotations to !annotation metadata.
  1214. MPM.addPass(Annotation2MetadataPass());
  1215. // Create a function that performs CFI checks for cross-DSO calls with targets
  1216. // in the current module.
  1217. MPM.addPass(CrossDSOCFIPass());
  1218. if (Level == OptimizationLevel::O0) {
  1219. // The WPD and LowerTypeTest passes need to run at -O0 to lower type
  1220. // metadata and intrinsics.
  1221. MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
  1222. MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
  1223. // Run a second time to clean up any type tests left behind by WPD for use
  1224. // in ICP.
  1225. MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
  1226. // Emit annotation remarks.
  1227. addAnnotationRemarksPass(MPM);
  1228. return MPM;
  1229. }
  1230. if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
  1231. // Load sample profile before running the LTO optimization pipeline.
  1232. MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
  1233. PGOOpt->ProfileRemappingFile,
  1234. ThinOrFullLTOPhase::FullLTOPostLink));
  1235. // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
  1236. // RequireAnalysisPass for PSI before subsequent non-module passes.
  1237. MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
  1238. }
  1239. // Try to run OpenMP optimizations, quick no-op if no OpenMP metadata present.
  1240. MPM.addPass(OpenMPOptPass());
  1241. // Remove unused virtual tables to improve the quality of code generated by
  1242. // whole-program devirtualization and bitset lowering.
  1243. MPM.addPass(GlobalDCEPass());
  1244. // Force any function attributes we want the rest of the pipeline to observe.
  1245. MPM.addPass(ForceFunctionAttrsPass());
  1246. // Do basic inference of function attributes from known properties of system
  1247. // libraries and other oracles.
  1248. MPM.addPass(InferFunctionAttrsPass());
  1249. if (Level.getSpeedupLevel() > 1) {
  1250. FunctionPassManager EarlyFPM;
  1251. EarlyFPM.addPass(CallSiteSplittingPass());
  1252. MPM.addPass(createModuleToFunctionPassAdaptor(
  1253. std::move(EarlyFPM), PTO.EagerlyInvalidateAnalyses));
  1254. // Indirect call promotion. This should promote all the targets that are
  1255. // left by the earlier promotion pass that promotes intra-module targets.
  1256. // This two-step promotion is to save the compile time. For LTO, it should
  1257. // produce the same result as if we only do promotion here.
  1258. MPM.addPass(PGOIndirectCallPromotion(
  1259. true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
  1260. if (EnableFunctionSpecialization && Level == OptimizationLevel::O3)
  1261. MPM.addPass(FunctionSpecializationPass());
  1262. // Propagate constants at call sites into the functions they call. This
  1263. // opens opportunities for globalopt (and inlining) by substituting function
  1264. // pointers passed as arguments to direct uses of functions.
  1265. MPM.addPass(IPSCCPPass());
  1266. // Attach metadata to indirect call sites indicating the set of functions
  1267. // they may target at run-time. This should follow IPSCCP.
  1268. MPM.addPass(CalledValuePropagationPass());
  1269. }
  1270. // Now deduce any function attributes based in the current code.
  1271. MPM.addPass(
  1272. createModuleToPostOrderCGSCCPassAdaptor(PostOrderFunctionAttrsPass()));
  1273. // Do RPO function attribute inference across the module to forward-propagate
  1274. // attributes where applicable.
  1275. // FIXME: Is this really an optimization rather than a canonicalization?
  1276. MPM.addPass(ReversePostOrderFunctionAttrsPass());
  1277. // Use in-range annotations on GEP indices to split globals where beneficial.
  1278. MPM.addPass(GlobalSplitPass());
  1279. // Run whole program optimization of virtual call when the list of callees
  1280. // is fixed.
  1281. MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
  1282. // Stop here at -O1.
  1283. if (Level == OptimizationLevel::O1) {
  1284. // The LowerTypeTestsPass needs to run to lower type metadata and the
  1285. // type.test intrinsics. The pass does nothing if CFI is disabled.
  1286. MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
  1287. // Run a second time to clean up any type tests left behind by WPD for use
  1288. // in ICP (which is performed earlier than this in the regular LTO
  1289. // pipeline).
  1290. MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
  1291. // Emit annotation remarks.
  1292. addAnnotationRemarksPass(MPM);
  1293. return MPM;
  1294. }
  1295. // Optimize globals to try and fold them into constants.
  1296. MPM.addPass(GlobalOptPass());
  1297. // Promote any localized globals to SSA registers.
  1298. MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
  1299. // Linking modules together can lead to duplicate global constant, only
  1300. // keep one copy of each constant.
  1301. MPM.addPass(ConstantMergePass());
  1302. // Remove unused arguments from functions.
  1303. MPM.addPass(DeadArgumentEliminationPass());
  1304. // Reduce the code after globalopt and ipsccp. Both can open up significant
  1305. // simplification opportunities, and both can propagate functions through
  1306. // function pointers. When this happens, we often have to resolve varargs
  1307. // calls, etc, so let instcombine do this.
  1308. FunctionPassManager PeepholeFPM;
  1309. PeepholeFPM.addPass(InstCombinePass());
  1310. if (Level == OptimizationLevel::O3)
  1311. PeepholeFPM.addPass(AggressiveInstCombinePass());
  1312. invokePeepholeEPCallbacks(PeepholeFPM, Level);
  1313. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM),
  1314. PTO.EagerlyInvalidateAnalyses));
  1315. // Note: historically, the PruneEH pass was run first to deduce nounwind and
  1316. // generally clean up exception handling overhead. It isn't clear this is
  1317. // valuable as the inliner doesn't currently care whether it is inlining an
  1318. // invoke or a call.
  1319. // Run the inliner now.
  1320. MPM.addPass(ModuleInlinerWrapperPass(getInlineParamsFromOptLevel(Level)));
  1321. // Optimize globals again after we ran the inliner.
  1322. MPM.addPass(GlobalOptPass());
  1323. // Garbage collect dead functions.
  1324. MPM.addPass(GlobalDCEPass());
  1325. // If we didn't decide to inline a function, check to see if we can
  1326. // transform it to pass arguments by value instead of by reference.
  1327. MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(ArgumentPromotionPass()));
  1328. FunctionPassManager FPM;
  1329. // The IPO Passes may leave cruft around. Clean up after them.
  1330. FPM.addPass(InstCombinePass());
  1331. invokePeepholeEPCallbacks(FPM, Level);
  1332. FPM.addPass(JumpThreadingPass(/*InsertFreezeWhenUnfoldingSelect*/ true));
  1333. // Do a post inline PGO instrumentation and use pass. This is a context
  1334. // sensitive PGO pass.
  1335. if (PGOOpt) {
  1336. if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
  1337. addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true,
  1338. /* IsCS */ true, PGOOpt->CSProfileGenFile,
  1339. PGOOpt->ProfileRemappingFile);
  1340. else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
  1341. addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false,
  1342. /* IsCS */ true, PGOOpt->ProfileFile,
  1343. PGOOpt->ProfileRemappingFile);
  1344. }
  1345. // Break up allocas
  1346. FPM.addPass(SROAPass());
  1347. // LTO provides additional opportunities for tailcall elimination due to
  1348. // link-time inlining, and visibility of nocapture attribute.
  1349. FPM.addPass(TailCallElimPass());
  1350. // Run a few AA driver optimizations here and now to cleanup the code.
  1351. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),
  1352. PTO.EagerlyInvalidateAnalyses));
  1353. MPM.addPass(
  1354. createModuleToPostOrderCGSCCPassAdaptor(PostOrderFunctionAttrsPass()));
  1355. // Require the GlobalsAA analysis for the module so we can query it within
  1356. // MainFPM.
  1357. MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
  1358. // Invalidate AAManager so it can be recreated and pick up the newly available
  1359. // GlobalsAA.
  1360. MPM.addPass(
  1361. createModuleToFunctionPassAdaptor(InvalidateAnalysisPass<AAManager>()));
  1362. FunctionPassManager MainFPM;
  1363. MainFPM.addPass(createFunctionToLoopPassAdaptor(
  1364. LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
  1365. /*AllowSpeculation=*/true),
  1366. /*USeMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true));
  1367. if (RunNewGVN)
  1368. MainFPM.addPass(NewGVNPass());
  1369. else
  1370. MainFPM.addPass(GVNPass());
  1371. // Remove dead memcpy()'s.
  1372. MainFPM.addPass(MemCpyOptPass());
  1373. // Nuke dead stores.
  1374. MainFPM.addPass(DSEPass());
  1375. MainFPM.addPass(MergedLoadStoreMotionPass());
  1376. if (EnableConstraintElimination)
  1377. MainFPM.addPass(ConstraintEliminationPass());
  1378. LoopPassManager LPM;
  1379. if (EnableLoopFlatten && Level.getSpeedupLevel() > 1)
  1380. LPM.addPass(LoopFlattenPass());
  1381. LPM.addPass(IndVarSimplifyPass());
  1382. LPM.addPass(LoopDeletionPass());
  1383. // FIXME: Add loop interchange.
  1384. // Unroll small loops and perform peeling.
  1385. LPM.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
  1386. /* OnlyWhenForced= */ !PTO.LoopUnrolling,
  1387. PTO.ForgetAllSCEVInLoopUnroll));
  1388. // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA.
  1389. // *All* loop passes must preserve it, in order to be able to use it.
  1390. MainFPM.addPass(createFunctionToLoopPassAdaptor(
  1391. std::move(LPM), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/true));
  1392. MainFPM.addPass(LoopDistributePass());
  1393. addVectorPasses(Level, MainFPM, /* IsFullLTO */ true);
  1394. // Run the OpenMPOpt CGSCC pass again late.
  1395. MPM.addPass(
  1396. createModuleToPostOrderCGSCCPassAdaptor(OpenMPOptCGSCCPass()));
  1397. invokePeepholeEPCallbacks(MainFPM, Level);
  1398. MainFPM.addPass(JumpThreadingPass(/*InsertFreezeWhenUnfoldingSelect*/ true));
  1399. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM),
  1400. PTO.EagerlyInvalidateAnalyses));
  1401. // Lower type metadata and the type.test intrinsic. This pass supports
  1402. // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
  1403. // to be run at link time if CFI is enabled. This pass does nothing if
  1404. // CFI is disabled.
  1405. MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
  1406. // Run a second time to clean up any type tests left behind by WPD for use
  1407. // in ICP (which is performed earlier than this in the regular LTO pipeline).
  1408. MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
  1409. // Enable splitting late in the FullLTO post-link pipeline. This is done in
  1410. // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
  1411. if (EnableHotColdSplit)
  1412. MPM.addPass(HotColdSplittingPass());
  1413. // Add late LTO optimization passes.
  1414. // Delete basic blocks, which optimization passes may have killed.
  1415. MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass(
  1416. SimplifyCFGOptions().convertSwitchRangeToICmp(true).hoistCommonInsts(
  1417. true))));
  1418. // Drop bodies of available eternally objects to improve GlobalDCE.
  1419. MPM.addPass(EliminateAvailableExternallyPass());
  1420. // Now that we have optimized the program, discard unreachable functions.
  1421. MPM.addPass(GlobalDCEPass());
  1422. if (PTO.MergeFunctions)
  1423. MPM.addPass(MergeFunctionsPass());
  1424. // Emit annotation remarks.
  1425. addAnnotationRemarksPass(MPM);
  1426. return MPM;
  1427. }
  1428. ModulePassManager PassBuilder::buildO0DefaultPipeline(OptimizationLevel Level,
  1429. bool LTOPreLink) {
  1430. assert(Level == OptimizationLevel::O0 &&
  1431. "buildO0DefaultPipeline should only be used with O0");
  1432. ModulePassManager MPM;
  1433. // Perform pseudo probe instrumentation in O0 mode. This is for the
  1434. // consistency between different build modes. For example, a LTO build can be
  1435. // mixed with an O0 prelink and an O2 postlink. Loading a sample profile in
  1436. // the postlink will require pseudo probe instrumentation in the prelink.
  1437. if (PGOOpt && PGOOpt->PseudoProbeForProfiling)
  1438. MPM.addPass(SampleProfileProbePass(TM));
  1439. if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
  1440. PGOOpt->Action == PGOOptions::IRUse))
  1441. addPGOInstrPassesForO0(
  1442. MPM,
  1443. /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
  1444. /* IsCS */ false, PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
  1445. for (auto &C : PipelineStartEPCallbacks)
  1446. C(MPM, Level);
  1447. if (PGOOpt && PGOOpt->DebugInfoForProfiling)
  1448. MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
  1449. for (auto &C : PipelineEarlySimplificationEPCallbacks)
  1450. C(MPM, Level);
  1451. // Build a minimal pipeline based on the semantics required by LLVM,
  1452. // which is just that always inlining occurs. Further, disable generating
  1453. // lifetime intrinsics to avoid enabling further optimizations during
  1454. // code generation.
  1455. MPM.addPass(AlwaysInlinerPass(
  1456. /*InsertLifetimeIntrinsics=*/false));
  1457. if (PTO.MergeFunctions)
  1458. MPM.addPass(MergeFunctionsPass());
  1459. if (EnableMatrix)
  1460. MPM.addPass(
  1461. createModuleToFunctionPassAdaptor(LowerMatrixIntrinsicsPass(true)));
  1462. if (!CGSCCOptimizerLateEPCallbacks.empty()) {
  1463. CGSCCPassManager CGPM;
  1464. for (auto &C : CGSCCOptimizerLateEPCallbacks)
  1465. C(CGPM, Level);
  1466. if (!CGPM.isEmpty())
  1467. MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
  1468. }
  1469. if (!LateLoopOptimizationsEPCallbacks.empty()) {
  1470. LoopPassManager LPM;
  1471. for (auto &C : LateLoopOptimizationsEPCallbacks)
  1472. C(LPM, Level);
  1473. if (!LPM.isEmpty()) {
  1474. MPM.addPass(createModuleToFunctionPassAdaptor(
  1475. createFunctionToLoopPassAdaptor(std::move(LPM))));
  1476. }
  1477. }
  1478. if (!LoopOptimizerEndEPCallbacks.empty()) {
  1479. LoopPassManager LPM;
  1480. for (auto &C : LoopOptimizerEndEPCallbacks)
  1481. C(LPM, Level);
  1482. if (!LPM.isEmpty()) {
  1483. MPM.addPass(createModuleToFunctionPassAdaptor(
  1484. createFunctionToLoopPassAdaptor(std::move(LPM))));
  1485. }
  1486. }
  1487. if (!ScalarOptimizerLateEPCallbacks.empty()) {
  1488. FunctionPassManager FPM;
  1489. for (auto &C : ScalarOptimizerLateEPCallbacks)
  1490. C(FPM, Level);
  1491. if (!FPM.isEmpty())
  1492. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  1493. }
  1494. if (!VectorizerStartEPCallbacks.empty()) {
  1495. FunctionPassManager FPM;
  1496. for (auto &C : VectorizerStartEPCallbacks)
  1497. C(FPM, Level);
  1498. if (!FPM.isEmpty())
  1499. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  1500. }
  1501. MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
  1502. CGSCCPassManager CGPM;
  1503. CGPM.addPass(CoroSplitPass());
  1504. MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
  1505. MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
  1506. for (auto &C : OptimizerLastEPCallbacks)
  1507. C(MPM, Level);
  1508. if (LTOPreLink)
  1509. addRequiredLTOPreLinkPasses(MPM);
  1510. MPM.addPass(createModuleToFunctionPassAdaptor(AnnotationRemarksPass()));
  1511. return MPM;
  1512. }
  1513. AAManager PassBuilder::buildDefaultAAPipeline() {
  1514. AAManager AA;
  1515. // The order in which these are registered determines their priority when
  1516. // being queried.
  1517. // First we register the basic alias analysis that provides the majority of
  1518. // per-function local AA logic. This is a stateless, on-demand local set of
  1519. // AA techniques.
  1520. AA.registerFunctionAnalysis<BasicAA>();
  1521. // Next we query fast, specialized alias analyses that wrap IR-embedded
  1522. // information about aliasing.
  1523. AA.registerFunctionAnalysis<ScopedNoAliasAA>();
  1524. AA.registerFunctionAnalysis<TypeBasedAA>();
  1525. // Add support for querying global aliasing information when available.
  1526. // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
  1527. // analysis, all that the `AAManager` can do is query for any *cached*
  1528. // results from `GlobalsAA` through a readonly proxy.
  1529. AA.registerModuleAnalysis<GlobalsAA>();
  1530. // Add target-specific alias analyses.
  1531. if (TM)
  1532. TM->registerDefaultAliasAnalyses(AA);
  1533. return AA;
  1534. }