PassBuilder.cpp 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834
  1. //===- Parsing and selection 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/Passes/PassBuilder.h"
  17. #include "llvm/ADT/StringSwitch.h"
  18. #include "llvm/Analysis/AliasAnalysisEvaluator.h"
  19. #include "llvm/Analysis/AliasSetTracker.h"
  20. #include "llvm/Analysis/AssumptionCache.h"
  21. #include "llvm/Analysis/BasicAliasAnalysis.h"
  22. #include "llvm/Analysis/BlockFrequencyInfo.h"
  23. #include "llvm/Analysis/BranchProbabilityInfo.h"
  24. #include "llvm/Analysis/CFGPrinter.h"
  25. #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
  26. #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
  27. #include "llvm/Analysis/CGSCCPassManager.h"
  28. #include "llvm/Analysis/CallGraph.h"
  29. #include "llvm/Analysis/CostModel.h"
  30. #include "llvm/Analysis/CycleAnalysis.h"
  31. #include "llvm/Analysis/DDG.h"
  32. #include "llvm/Analysis/DDGPrinter.h"
  33. #include "llvm/Analysis/Delinearization.h"
  34. #include "llvm/Analysis/DemandedBits.h"
  35. #include "llvm/Analysis/DependenceAnalysis.h"
  36. #include "llvm/Analysis/DivergenceAnalysis.h"
  37. #include "llvm/Analysis/DomPrinter.h"
  38. #include "llvm/Analysis/DominanceFrontier.h"
  39. #include "llvm/Analysis/FunctionPropertiesAnalysis.h"
  40. #include "llvm/Analysis/GlobalsModRef.h"
  41. #include "llvm/Analysis/IRSimilarityIdentifier.h"
  42. #include "llvm/Analysis/IVUsers.h"
  43. #include "llvm/Analysis/InlineAdvisor.h"
  44. #include "llvm/Analysis/InlineSizeEstimatorAnalysis.h"
  45. #include "llvm/Analysis/InstCount.h"
  46. #include "llvm/Analysis/LazyCallGraph.h"
  47. #include "llvm/Analysis/LazyValueInfo.h"
  48. #include "llvm/Analysis/Lint.h"
  49. #include "llvm/Analysis/LoopAccessAnalysis.h"
  50. #include "llvm/Analysis/LoopCacheAnalysis.h"
  51. #include "llvm/Analysis/LoopInfo.h"
  52. #include "llvm/Analysis/LoopNestAnalysis.h"
  53. #include "llvm/Analysis/MemDerefPrinter.h"
  54. #include "llvm/Analysis/MemoryDependenceAnalysis.h"
  55. #include "llvm/Analysis/MemorySSA.h"
  56. #include "llvm/Analysis/ModuleDebugInfoPrinter.h"
  57. #include "llvm/Analysis/ModuleSummaryAnalysis.h"
  58. #include "llvm/Analysis/MustExecute.h"
  59. #include "llvm/Analysis/ObjCARCAliasAnalysis.h"
  60. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  61. #include "llvm/Analysis/PhiValues.h"
  62. #include "llvm/Analysis/PostDominators.h"
  63. #include "llvm/Analysis/ProfileSummaryInfo.h"
  64. #include "llvm/Analysis/RegionInfo.h"
  65. #include "llvm/Analysis/ScalarEvolution.h"
  66. #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
  67. #include "llvm/Analysis/ScopedNoAliasAA.h"
  68. #include "llvm/Analysis/StackLifetime.h"
  69. #include "llvm/Analysis/StackSafetyAnalysis.h"
  70. #include "llvm/Analysis/TargetLibraryInfo.h"
  71. #include "llvm/Analysis/TargetTransformInfo.h"
  72. #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
  73. #include "llvm/IR/Dominators.h"
  74. #include "llvm/IR/IRPrintingPasses.h"
  75. #include "llvm/IR/PassManager.h"
  76. #include "llvm/IR/PrintPasses.h"
  77. #include "llvm/IR/SafepointIRVerifier.h"
  78. #include "llvm/IR/Verifier.h"
  79. #include "llvm/Support/CommandLine.h"
  80. #include "llvm/Support/Debug.h"
  81. #include "llvm/Support/ErrorHandling.h"
  82. #include "llvm/Support/FormatVariadic.h"
  83. #include "llvm/Support/Regex.h"
  84. #include "llvm/Target/TargetMachine.h"
  85. #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
  86. #include "llvm/Transforms/Coroutines/CoroCleanup.h"
  87. #include "llvm/Transforms/Coroutines/CoroEarly.h"
  88. #include "llvm/Transforms/Coroutines/CoroElide.h"
  89. #include "llvm/Transforms/Coroutines/CoroSplit.h"
  90. #include "llvm/Transforms/IPO/AlwaysInliner.h"
  91. #include "llvm/Transforms/IPO/Annotation2Metadata.h"
  92. #include "llvm/Transforms/IPO/ArgumentPromotion.h"
  93. #include "llvm/Transforms/IPO/Attributor.h"
  94. #include "llvm/Transforms/IPO/BlockExtractor.h"
  95. #include "llvm/Transforms/IPO/CalledValuePropagation.h"
  96. #include "llvm/Transforms/IPO/ConstantMerge.h"
  97. #include "llvm/Transforms/IPO/CrossDSOCFI.h"
  98. #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
  99. #include "llvm/Transforms/IPO/ElimAvailExtern.h"
  100. #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
  101. #include "llvm/Transforms/IPO/FunctionAttrs.h"
  102. #include "llvm/Transforms/IPO/FunctionImport.h"
  103. #include "llvm/Transforms/IPO/GlobalDCE.h"
  104. #include "llvm/Transforms/IPO/GlobalOpt.h"
  105. #include "llvm/Transforms/IPO/GlobalSplit.h"
  106. #include "llvm/Transforms/IPO/HotColdSplitting.h"
  107. #include "llvm/Transforms/IPO/IROutliner.h"
  108. #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
  109. #include "llvm/Transforms/IPO/Inliner.h"
  110. #include "llvm/Transforms/IPO/Internalize.h"
  111. #include "llvm/Transforms/IPO/LoopExtractor.h"
  112. #include "llvm/Transforms/IPO/LowerTypeTests.h"
  113. #include "llvm/Transforms/IPO/MergeFunctions.h"
  114. #include "llvm/Transforms/IPO/ModuleInliner.h"
  115. #include "llvm/Transforms/IPO/OpenMPOpt.h"
  116. #include "llvm/Transforms/IPO/PartialInlining.h"
  117. #include "llvm/Transforms/IPO/SCCP.h"
  118. #include "llvm/Transforms/IPO/SampleProfile.h"
  119. #include "llvm/Transforms/IPO/SampleProfileProbe.h"
  120. #include "llvm/Transforms/IPO/StripDeadPrototypes.h"
  121. #include "llvm/Transforms/IPO/StripSymbols.h"
  122. #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
  123. #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
  124. #include "llvm/Transforms/InstCombine/InstCombine.h"
  125. #include "llvm/Transforms/Instrumentation.h"
  126. #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
  127. #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
  128. #include "llvm/Transforms/Instrumentation/CGProfile.h"
  129. #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
  130. #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
  131. #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
  132. #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
  133. #include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
  134. #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
  135. #include "llvm/Transforms/Instrumentation/MemProfiler.h"
  136. #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
  137. #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
  138. #include "llvm/Transforms/Instrumentation/PoisonChecking.h"
  139. #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
  140. #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
  141. #include "llvm/Transforms/ObjCARC.h"
  142. #include "llvm/Transforms/Scalar/ADCE.h"
  143. #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
  144. #include "llvm/Transforms/Scalar/AnnotationRemarks.h"
  145. #include "llvm/Transforms/Scalar/BDCE.h"
  146. #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
  147. #include "llvm/Transforms/Scalar/ConstantHoisting.h"
  148. #include "llvm/Transforms/Scalar/ConstraintElimination.h"
  149. #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
  150. #include "llvm/Transforms/Scalar/DCE.h"
  151. #include "llvm/Transforms/Scalar/DFAJumpThreading.h"
  152. #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
  153. #include "llvm/Transforms/Scalar/DivRemPairs.h"
  154. #include "llvm/Transforms/Scalar/EarlyCSE.h"
  155. #include "llvm/Transforms/Scalar/FlattenCFG.h"
  156. #include "llvm/Transforms/Scalar/Float2Int.h"
  157. #include "llvm/Transforms/Scalar/GVN.h"
  158. #include "llvm/Transforms/Scalar/GuardWidening.h"
  159. #include "llvm/Transforms/Scalar/IVUsersPrinter.h"
  160. #include "llvm/Transforms/Scalar/IndVarSimplify.h"
  161. #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
  162. #include "llvm/Transforms/Scalar/InferAddressSpaces.h"
  163. #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
  164. #include "llvm/Transforms/Scalar/JumpThreading.h"
  165. #include "llvm/Transforms/Scalar/LICM.h"
  166. #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
  167. #include "llvm/Transforms/Scalar/LoopBoundSplit.h"
  168. #include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
  169. #include "llvm/Transforms/Scalar/LoopDeletion.h"
  170. #include "llvm/Transforms/Scalar/LoopDistribute.h"
  171. #include "llvm/Transforms/Scalar/LoopFlatten.h"
  172. #include "llvm/Transforms/Scalar/LoopFuse.h"
  173. #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
  174. #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
  175. #include "llvm/Transforms/Scalar/LoopInterchange.h"
  176. #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
  177. #include "llvm/Transforms/Scalar/LoopPassManager.h"
  178. #include "llvm/Transforms/Scalar/LoopPredication.h"
  179. #include "llvm/Transforms/Scalar/LoopReroll.h"
  180. #include "llvm/Transforms/Scalar/LoopRotation.h"
  181. #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
  182. #include "llvm/Transforms/Scalar/LoopSink.h"
  183. #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
  184. #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
  185. #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
  186. #include "llvm/Transforms/Scalar/LoopVersioningLICM.h"
  187. #include "llvm/Transforms/Scalar/LowerAtomic.h"
  188. #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h"
  189. #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
  190. #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
  191. #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
  192. #include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
  193. #include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
  194. #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
  195. #include "llvm/Transforms/Scalar/MergeICmps.h"
  196. #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
  197. #include "llvm/Transforms/Scalar/NaryReassociate.h"
  198. #include "llvm/Transforms/Scalar/NewGVN.h"
  199. #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
  200. #include "llvm/Transforms/Scalar/Reassociate.h"
  201. #include "llvm/Transforms/Scalar/Reg2Mem.h"
  202. #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
  203. #include "llvm/Transforms/Scalar/SCCP.h"
  204. #include "llvm/Transforms/Scalar/SROA.h"
  205. #include "llvm/Transforms/Scalar/ScalarizeMaskedMemIntrin.h"
  206. #include "llvm/Transforms/Scalar/Scalarizer.h"
  207. #include "llvm/Transforms/Scalar/SeparateConstOffsetFromGEP.h"
  208. #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
  209. #include "llvm/Transforms/Scalar/SimplifyCFG.h"
  210. #include "llvm/Transforms/Scalar/Sink.h"
  211. #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
  212. #include "llvm/Transforms/Scalar/StraightLineStrengthReduce.h"
  213. #include "llvm/Transforms/Scalar/StructurizeCFG.h"
  214. #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
  215. #include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
  216. #include "llvm/Transforms/Utils/AddDiscriminators.h"
  217. #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
  218. #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
  219. #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
  220. #include "llvm/Transforms/Utils/CanonicalizeFreezeInLoops.h"
  221. #include "llvm/Transforms/Utils/Debugify.h"
  222. #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
  223. #include "llvm/Transforms/Utils/FixIrreducible.h"
  224. #include "llvm/Transforms/Utils/HelloWorld.h"
  225. #include "llvm/Transforms/Utils/InjectTLIMappings.h"
  226. #include "llvm/Transforms/Utils/InstructionNamer.h"
  227. #include "llvm/Transforms/Utils/LCSSA.h"
  228. #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
  229. #include "llvm/Transforms/Utils/LoopSimplify.h"
  230. #include "llvm/Transforms/Utils/LoopVersioning.h"
  231. #include "llvm/Transforms/Utils/LowerInvoke.h"
  232. #include "llvm/Transforms/Utils/LowerSwitch.h"
  233. #include "llvm/Transforms/Utils/Mem2Reg.h"
  234. #include "llvm/Transforms/Utils/MetaRenamer.h"
  235. #include "llvm/Transforms/Utils/NameAnonGlobals.h"
  236. #include "llvm/Transforms/Utils/RelLookupTableConverter.h"
  237. #include "llvm/Transforms/Utils/StripGCRelocates.h"
  238. #include "llvm/Transforms/Utils/StripNonLineTableDebugInfo.h"
  239. #include "llvm/Transforms/Utils/SymbolRewriter.h"
  240. #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
  241. #include "llvm/Transforms/Utils/UnifyLoopExits.h"
  242. #include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
  243. #include "llvm/Transforms/Vectorize/LoopVectorize.h"
  244. #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
  245. #include "llvm/Transforms/Vectorize/VectorCombine.h"
  246. using namespace llvm;
  247. static const Regex DefaultAliasRegex(
  248. "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
  249. namespace llvm {
  250. cl::opt<bool> PrintPipelinePasses(
  251. "print-pipeline-passes",
  252. cl::desc("Print a '-passes' compatible string describing the pipeline "
  253. "(best-effort only)."));
  254. } // namespace llvm
  255. namespace {
  256. // The following passes/analyses have custom names, otherwise their name will
  257. // include `(anonymous namespace)`. These are special since they are only for
  258. // testing purposes and don't live in a header file.
  259. /// No-op module pass which does nothing.
  260. struct NoOpModulePass : PassInfoMixin<NoOpModulePass> {
  261. PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
  262. return PreservedAnalyses::all();
  263. }
  264. static StringRef name() { return "NoOpModulePass"; }
  265. };
  266. /// No-op module analysis.
  267. class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
  268. friend AnalysisInfoMixin<NoOpModuleAnalysis>;
  269. static AnalysisKey Key;
  270. public:
  271. struct Result {};
  272. Result run(Module &, ModuleAnalysisManager &) { return Result(); }
  273. static StringRef name() { return "NoOpModuleAnalysis"; }
  274. };
  275. /// No-op CGSCC pass which does nothing.
  276. struct NoOpCGSCCPass : PassInfoMixin<NoOpCGSCCPass> {
  277. PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
  278. LazyCallGraph &, CGSCCUpdateResult &UR) {
  279. return PreservedAnalyses::all();
  280. }
  281. static StringRef name() { return "NoOpCGSCCPass"; }
  282. };
  283. /// No-op CGSCC analysis.
  284. class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
  285. friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
  286. static AnalysisKey Key;
  287. public:
  288. struct Result {};
  289. Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
  290. return Result();
  291. }
  292. static StringRef name() { return "NoOpCGSCCAnalysis"; }
  293. };
  294. /// No-op function pass which does nothing.
  295. struct NoOpFunctionPass : PassInfoMixin<NoOpFunctionPass> {
  296. PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
  297. return PreservedAnalyses::all();
  298. }
  299. static StringRef name() { return "NoOpFunctionPass"; }
  300. };
  301. /// No-op function analysis.
  302. class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
  303. friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
  304. static AnalysisKey Key;
  305. public:
  306. struct Result {};
  307. Result run(Function &, FunctionAnalysisManager &) { return Result(); }
  308. static StringRef name() { return "NoOpFunctionAnalysis"; }
  309. };
  310. /// No-op loop nest pass which does nothing.
  311. struct NoOpLoopNestPass : PassInfoMixin<NoOpLoopNestPass> {
  312. PreservedAnalyses run(LoopNest &L, LoopAnalysisManager &,
  313. LoopStandardAnalysisResults &, LPMUpdater &) {
  314. return PreservedAnalyses::all();
  315. }
  316. static StringRef name() { return "NoOpLoopNestPass"; }
  317. };
  318. /// No-op loop pass which does nothing.
  319. struct NoOpLoopPass : PassInfoMixin<NoOpLoopPass> {
  320. PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
  321. LoopStandardAnalysisResults &, LPMUpdater &) {
  322. return PreservedAnalyses::all();
  323. }
  324. static StringRef name() { return "NoOpLoopPass"; }
  325. };
  326. /// No-op loop analysis.
  327. class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
  328. friend AnalysisInfoMixin<NoOpLoopAnalysis>;
  329. static AnalysisKey Key;
  330. public:
  331. struct Result {};
  332. Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
  333. return Result();
  334. }
  335. static StringRef name() { return "NoOpLoopAnalysis"; }
  336. };
  337. AnalysisKey NoOpModuleAnalysis::Key;
  338. AnalysisKey NoOpCGSCCAnalysis::Key;
  339. AnalysisKey NoOpFunctionAnalysis::Key;
  340. AnalysisKey NoOpLoopAnalysis::Key;
  341. /// Whether or not we should populate a PassInstrumentationCallbacks's class to
  342. /// pass name map.
  343. ///
  344. /// This is for optimization purposes so we don't populate it if we never use
  345. /// it. This should be updated if new pass instrumentation wants to use the map.
  346. /// We currently only use this for --print-before/after.
  347. bool shouldPopulateClassToPassNames() {
  348. return PrintPipelinePasses || !printBeforePasses().empty() ||
  349. !printAfterPasses().empty();
  350. }
  351. } // namespace
  352. PassBuilder::PassBuilder(TargetMachine *TM, PipelineTuningOptions PTO,
  353. Optional<PGOOptions> PGOOpt,
  354. PassInstrumentationCallbacks *PIC)
  355. : TM(TM), PTO(PTO), PGOOpt(PGOOpt), PIC(PIC) {
  356. if (TM)
  357. TM->registerPassBuilderCallbacks(*this);
  358. if (PIC && shouldPopulateClassToPassNames()) {
  359. #define MODULE_PASS(NAME, CREATE_PASS) \
  360. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  361. #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  362. PIC->addClassToPassName(CLASS, NAME);
  363. #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
  364. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  365. #define FUNCTION_PASS(NAME, CREATE_PASS) \
  366. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  367. #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  368. PIC->addClassToPassName(CLASS, NAME);
  369. #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
  370. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  371. #define LOOPNEST_PASS(NAME, CREATE_PASS) \
  372. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  373. #define LOOP_PASS(NAME, CREATE_PASS) \
  374. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  375. #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  376. PIC->addClassToPassName(CLASS, NAME);
  377. #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
  378. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  379. #define CGSCC_PASS(NAME, CREATE_PASS) \
  380. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  381. #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  382. PIC->addClassToPassName(CLASS, NAME);
  383. #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
  384. PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
  385. #include "PassRegistry.def"
  386. }
  387. }
  388. void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
  389. #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
  390. MAM.registerPass([&] { return CREATE_PASS; });
  391. #include "PassRegistry.def"
  392. for (auto &C : ModuleAnalysisRegistrationCallbacks)
  393. C(MAM);
  394. }
  395. void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
  396. #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
  397. CGAM.registerPass([&] { return CREATE_PASS; });
  398. #include "PassRegistry.def"
  399. for (auto &C : CGSCCAnalysisRegistrationCallbacks)
  400. C(CGAM);
  401. }
  402. void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
  403. // We almost always want the default alias analysis pipeline.
  404. // If a user wants a different one, they can register their own before calling
  405. // registerFunctionAnalyses().
  406. FAM.registerPass([&] { return buildDefaultAAPipeline(); });
  407. #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
  408. FAM.registerPass([&] { return CREATE_PASS; });
  409. #include "PassRegistry.def"
  410. for (auto &C : FunctionAnalysisRegistrationCallbacks)
  411. C(FAM);
  412. }
  413. void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
  414. #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
  415. LAM.registerPass([&] { return CREATE_PASS; });
  416. #include "PassRegistry.def"
  417. for (auto &C : LoopAnalysisRegistrationCallbacks)
  418. C(LAM);
  419. }
  420. static Optional<int> parseRepeatPassName(StringRef Name) {
  421. if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
  422. return None;
  423. int Count;
  424. if (Name.getAsInteger(0, Count) || Count <= 0)
  425. return None;
  426. return Count;
  427. }
  428. static Optional<int> parseDevirtPassName(StringRef Name) {
  429. if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
  430. return None;
  431. int Count;
  432. if (Name.getAsInteger(0, Count) || Count < 0)
  433. return None;
  434. return Count;
  435. }
  436. static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
  437. if (!Name.consume_front(PassName))
  438. return false;
  439. // normal pass name w/o parameters == default parameters
  440. if (Name.empty())
  441. return true;
  442. return Name.startswith("<") && Name.endswith(">");
  443. }
  444. namespace {
  445. /// This performs customized parsing of pass name with parameters.
  446. ///
  447. /// We do not need parametrization of passes in textual pipeline very often,
  448. /// yet on a rare occasion ability to specify parameters right there can be
  449. /// useful.
  450. ///
  451. /// \p Name - parameterized specification of a pass from a textual pipeline
  452. /// is a string in a form of :
  453. /// PassName '<' parameter-list '>'
  454. ///
  455. /// Parameter list is being parsed by the parser callable argument, \p Parser,
  456. /// It takes a string-ref of parameters and returns either StringError or a
  457. /// parameter list in a form of a custom parameters type, all wrapped into
  458. /// Expected<> template class.
  459. ///
  460. template <typename ParametersParseCallableT>
  461. auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
  462. StringRef PassName) -> decltype(Parser(StringRef{})) {
  463. using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
  464. StringRef Params = Name;
  465. if (!Params.consume_front(PassName)) {
  466. assert(false &&
  467. "unable to strip pass name from parametrized pass specification");
  468. }
  469. if (!Params.empty() &&
  470. (!Params.consume_front("<") || !Params.consume_back(">"))) {
  471. assert(false && "invalid format for parametrized pass name");
  472. }
  473. Expected<ParametersT> Result = Parser(Params);
  474. assert((Result || Result.template errorIsA<StringError>()) &&
  475. "Pass parameter parser can only return StringErrors.");
  476. return Result;
  477. }
  478. /// Parser of parameters for LoopUnroll pass.
  479. Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
  480. LoopUnrollOptions UnrollOpts;
  481. while (!Params.empty()) {
  482. StringRef ParamName;
  483. std::tie(ParamName, Params) = Params.split(';');
  484. int OptLevel = StringSwitch<int>(ParamName)
  485. .Case("O0", 0)
  486. .Case("O1", 1)
  487. .Case("O2", 2)
  488. .Case("O3", 3)
  489. .Default(-1);
  490. if (OptLevel >= 0) {
  491. UnrollOpts.setOptLevel(OptLevel);
  492. continue;
  493. }
  494. if (ParamName.consume_front("full-unroll-max=")) {
  495. int Count;
  496. if (ParamName.getAsInteger(0, Count))
  497. return make_error<StringError>(
  498. formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
  499. inconvertibleErrorCode());
  500. UnrollOpts.setFullUnrollMaxCount(Count);
  501. continue;
  502. }
  503. bool Enable = !ParamName.consume_front("no-");
  504. if (ParamName == "partial") {
  505. UnrollOpts.setPartial(Enable);
  506. } else if (ParamName == "peeling") {
  507. UnrollOpts.setPeeling(Enable);
  508. } else if (ParamName == "profile-peeling") {
  509. UnrollOpts.setProfileBasedPeeling(Enable);
  510. } else if (ParamName == "runtime") {
  511. UnrollOpts.setRuntime(Enable);
  512. } else if (ParamName == "upperbound") {
  513. UnrollOpts.setUpperBound(Enable);
  514. } else {
  515. return make_error<StringError>(
  516. formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
  517. inconvertibleErrorCode());
  518. }
  519. }
  520. return UnrollOpts;
  521. }
  522. Expected<bool> parseSinglePassOption(StringRef Params, StringRef OptionName,
  523. StringRef PassName) {
  524. bool Result = false;
  525. while (!Params.empty()) {
  526. StringRef ParamName;
  527. std::tie(ParamName, Params) = Params.split(';');
  528. if (ParamName == OptionName) {
  529. Result = true;
  530. } else {
  531. return make_error<StringError>(
  532. formatv("invalid {1} pass parameter '{0}' ", ParamName, PassName)
  533. .str(),
  534. inconvertibleErrorCode());
  535. }
  536. }
  537. return Result;
  538. }
  539. Expected<bool> parseInlinerPassOptions(StringRef Params) {
  540. return parseSinglePassOption(Params, "only-mandatory", "InlinerPass");
  541. }
  542. Expected<bool> parseEarlyCSEPassOptions(StringRef Params) {
  543. return parseSinglePassOption(Params, "memssa", "EarlyCSE");
  544. }
  545. Expected<bool> parseEntryExitInstrumenterPassOptions(StringRef Params) {
  546. return parseSinglePassOption(Params, "post-inline", "EntryExitInstrumenter");
  547. }
  548. Expected<bool> parseLoopExtractorPassOptions(StringRef Params) {
  549. return parseSinglePassOption(Params, "single", "LoopExtractor");
  550. }
  551. Expected<bool> parseLowerMatrixIntrinsicsPassOptions(StringRef Params) {
  552. return parseSinglePassOption(Params, "minimal", "LowerMatrixIntrinsics");
  553. }
  554. Expected<AddressSanitizerOptions> parseASanPassOptions(StringRef Params) {
  555. AddressSanitizerOptions Result;
  556. while (!Params.empty()) {
  557. StringRef ParamName;
  558. std::tie(ParamName, Params) = Params.split(';');
  559. if (ParamName == "kernel") {
  560. Result.CompileKernel = true;
  561. } else {
  562. return make_error<StringError>(
  563. formatv("invalid AddressSanitizer pass parameter '{0}' ", ParamName)
  564. .str(),
  565. inconvertibleErrorCode());
  566. }
  567. }
  568. return Result;
  569. }
  570. Expected<HWAddressSanitizerOptions> parseHWASanPassOptions(StringRef Params) {
  571. HWAddressSanitizerOptions Result;
  572. while (!Params.empty()) {
  573. StringRef ParamName;
  574. std::tie(ParamName, Params) = Params.split(';');
  575. if (ParamName == "recover") {
  576. Result.Recover = true;
  577. } else if (ParamName == "kernel") {
  578. Result.CompileKernel = true;
  579. } else {
  580. return make_error<StringError>(
  581. formatv("invalid HWAddressSanitizer pass parameter '{0}' ", ParamName)
  582. .str(),
  583. inconvertibleErrorCode());
  584. }
  585. }
  586. return Result;
  587. }
  588. Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
  589. MemorySanitizerOptions Result;
  590. while (!Params.empty()) {
  591. StringRef ParamName;
  592. std::tie(ParamName, Params) = Params.split(';');
  593. if (ParamName == "recover") {
  594. Result.Recover = true;
  595. } else if (ParamName == "kernel") {
  596. Result.Kernel = true;
  597. } else if (ParamName.consume_front("track-origins=")) {
  598. if (ParamName.getAsInteger(0, Result.TrackOrigins))
  599. return make_error<StringError>(
  600. formatv("invalid argument to MemorySanitizer pass track-origins "
  601. "parameter: '{0}' ",
  602. ParamName)
  603. .str(),
  604. inconvertibleErrorCode());
  605. } else if (ParamName == "eager-checks") {
  606. Result.EagerChecks = true;
  607. } else {
  608. return make_error<StringError>(
  609. formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
  610. .str(),
  611. inconvertibleErrorCode());
  612. }
  613. }
  614. return Result;
  615. }
  616. /// Parser of parameters for SimplifyCFG pass.
  617. Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
  618. SimplifyCFGOptions Result;
  619. while (!Params.empty()) {
  620. StringRef ParamName;
  621. std::tie(ParamName, Params) = Params.split(';');
  622. bool Enable = !ParamName.consume_front("no-");
  623. if (ParamName == "forward-switch-cond") {
  624. Result.forwardSwitchCondToPhi(Enable);
  625. } else if (ParamName == "switch-range-to-icmp") {
  626. Result.convertSwitchRangeToICmp(Enable);
  627. } else if (ParamName == "switch-to-lookup") {
  628. Result.convertSwitchToLookupTable(Enable);
  629. } else if (ParamName == "keep-loops") {
  630. Result.needCanonicalLoops(Enable);
  631. } else if (ParamName == "hoist-common-insts") {
  632. Result.hoistCommonInsts(Enable);
  633. } else if (ParamName == "sink-common-insts") {
  634. Result.sinkCommonInsts(Enable);
  635. } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
  636. APInt BonusInstThreshold;
  637. if (ParamName.getAsInteger(0, BonusInstThreshold))
  638. return make_error<StringError>(
  639. formatv("invalid argument to SimplifyCFG pass bonus-threshold "
  640. "parameter: '{0}' ",
  641. ParamName).str(),
  642. inconvertibleErrorCode());
  643. Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
  644. } else {
  645. return make_error<StringError>(
  646. formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
  647. inconvertibleErrorCode());
  648. }
  649. }
  650. return Result;
  651. }
  652. /// Parser of parameters for LoopVectorize pass.
  653. Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
  654. LoopVectorizeOptions Opts;
  655. while (!Params.empty()) {
  656. StringRef ParamName;
  657. std::tie(ParamName, Params) = Params.split(';');
  658. bool Enable = !ParamName.consume_front("no-");
  659. if (ParamName == "interleave-forced-only") {
  660. Opts.setInterleaveOnlyWhenForced(Enable);
  661. } else if (ParamName == "vectorize-forced-only") {
  662. Opts.setVectorizeOnlyWhenForced(Enable);
  663. } else {
  664. return make_error<StringError>(
  665. formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
  666. inconvertibleErrorCode());
  667. }
  668. }
  669. return Opts;
  670. }
  671. Expected<std::pair<bool, bool>> parseLoopUnswitchOptions(StringRef Params) {
  672. std::pair<bool, bool> Result = {false, true};
  673. while (!Params.empty()) {
  674. StringRef ParamName;
  675. std::tie(ParamName, Params) = Params.split(';');
  676. bool Enable = !ParamName.consume_front("no-");
  677. if (ParamName == "nontrivial") {
  678. Result.first = Enable;
  679. } else if (ParamName == "trivial") {
  680. Result.second = Enable;
  681. } else {
  682. return make_error<StringError>(
  683. formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
  684. .str(),
  685. inconvertibleErrorCode());
  686. }
  687. }
  688. return Result;
  689. }
  690. Expected<bool> parseMergedLoadStoreMotionOptions(StringRef Params) {
  691. bool Result = false;
  692. while (!Params.empty()) {
  693. StringRef ParamName;
  694. std::tie(ParamName, Params) = Params.split(';');
  695. bool Enable = !ParamName.consume_front("no-");
  696. if (ParamName == "split-footer-bb") {
  697. Result = Enable;
  698. } else {
  699. return make_error<StringError>(
  700. formatv("invalid MergedLoadStoreMotion pass parameter '{0}' ",
  701. ParamName)
  702. .str(),
  703. inconvertibleErrorCode());
  704. }
  705. }
  706. return Result;
  707. }
  708. Expected<GVNOptions> parseGVNOptions(StringRef Params) {
  709. GVNOptions Result;
  710. while (!Params.empty()) {
  711. StringRef ParamName;
  712. std::tie(ParamName, Params) = Params.split(';');
  713. bool Enable = !ParamName.consume_front("no-");
  714. if (ParamName == "pre") {
  715. Result.setPRE(Enable);
  716. } else if (ParamName == "load-pre") {
  717. Result.setLoadPRE(Enable);
  718. } else if (ParamName == "split-backedge-load-pre") {
  719. Result.setLoadPRESplitBackedge(Enable);
  720. } else if (ParamName == "memdep") {
  721. Result.setMemDep(Enable);
  722. } else {
  723. return make_error<StringError>(
  724. formatv("invalid GVN pass parameter '{0}' ", ParamName).str(),
  725. inconvertibleErrorCode());
  726. }
  727. }
  728. return Result;
  729. }
  730. Expected<StackLifetime::LivenessType>
  731. parseStackLifetimeOptions(StringRef Params) {
  732. StackLifetime::LivenessType Result = StackLifetime::LivenessType::May;
  733. while (!Params.empty()) {
  734. StringRef ParamName;
  735. std::tie(ParamName, Params) = Params.split(';');
  736. if (ParamName == "may") {
  737. Result = StackLifetime::LivenessType::May;
  738. } else if (ParamName == "must") {
  739. Result = StackLifetime::LivenessType::Must;
  740. } else {
  741. return make_error<StringError>(
  742. formatv("invalid StackLifetime parameter '{0}' ", ParamName).str(),
  743. inconvertibleErrorCode());
  744. }
  745. }
  746. return Result;
  747. }
  748. } // namespace
  749. /// Tests whether a pass name starts with a valid prefix for a default pipeline
  750. /// alias.
  751. static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
  752. return Name.startswith("default") || Name.startswith("thinlto") ||
  753. Name.startswith("lto");
  754. }
  755. /// Tests whether registered callbacks will accept a given pass name.
  756. ///
  757. /// When parsing a pipeline text, the type of the outermost pipeline may be
  758. /// omitted, in which case the type is automatically determined from the first
  759. /// pass name in the text. This may be a name that is handled through one of the
  760. /// callbacks. We check this through the oridinary parsing callbacks by setting
  761. /// up a dummy PassManager in order to not force the client to also handle this
  762. /// type of query.
  763. template <typename PassManagerT, typename CallbacksT>
  764. static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
  765. if (!Callbacks.empty()) {
  766. PassManagerT DummyPM;
  767. for (auto &CB : Callbacks)
  768. if (CB(Name, DummyPM, {}))
  769. return true;
  770. }
  771. return false;
  772. }
  773. template <typename CallbacksT>
  774. static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
  775. // Manually handle aliases for pre-configured pipeline fragments.
  776. if (startsWithDefaultPipelineAliasPrefix(Name))
  777. return DefaultAliasRegex.match(Name);
  778. // Explicitly handle pass manager names.
  779. if (Name == "module")
  780. return true;
  781. if (Name == "cgscc")
  782. return true;
  783. if (Name == "function" || Name == "function<eager-inv>")
  784. return true;
  785. // Explicitly handle custom-parsed pass names.
  786. if (parseRepeatPassName(Name))
  787. return true;
  788. #define MODULE_PASS(NAME, CREATE_PASS) \
  789. if (Name == NAME) \
  790. return true;
  791. #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  792. if (checkParametrizedPassName(Name, NAME)) \
  793. return true;
  794. #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
  795. if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
  796. return true;
  797. #include "PassRegistry.def"
  798. return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
  799. }
  800. template <typename CallbacksT>
  801. static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
  802. // Explicitly handle pass manager names.
  803. if (Name == "cgscc")
  804. return true;
  805. if (Name == "function" || Name == "function<eager-inv>")
  806. return true;
  807. // Explicitly handle custom-parsed pass names.
  808. if (parseRepeatPassName(Name))
  809. return true;
  810. if (parseDevirtPassName(Name))
  811. return true;
  812. #define CGSCC_PASS(NAME, CREATE_PASS) \
  813. if (Name == NAME) \
  814. return true;
  815. #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  816. if (checkParametrizedPassName(Name, NAME)) \
  817. return true;
  818. #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
  819. if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
  820. return true;
  821. #include "PassRegistry.def"
  822. return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
  823. }
  824. template <typename CallbacksT>
  825. static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
  826. // Explicitly handle pass manager names.
  827. if (Name == "function" || Name == "function<eager-inv>")
  828. return true;
  829. if (Name == "loop" || Name == "loop-mssa")
  830. return true;
  831. // Explicitly handle custom-parsed pass names.
  832. if (parseRepeatPassName(Name))
  833. return true;
  834. #define FUNCTION_PASS(NAME, CREATE_PASS) \
  835. if (Name == NAME) \
  836. return true;
  837. #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  838. if (checkParametrizedPassName(Name, NAME)) \
  839. return true;
  840. #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
  841. if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
  842. return true;
  843. #include "PassRegistry.def"
  844. return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
  845. }
  846. template <typename CallbacksT>
  847. static bool isLoopNestPassName(StringRef Name, CallbacksT &Callbacks,
  848. bool &UseMemorySSA) {
  849. UseMemorySSA = false;
  850. // Explicitly handle custom-parsed pass names.
  851. if (parseRepeatPassName(Name))
  852. return true;
  853. if (Name == "lnicm") {
  854. UseMemorySSA = true;
  855. return true;
  856. }
  857. #define LOOPNEST_PASS(NAME, CREATE_PASS) \
  858. if (Name == NAME) \
  859. return true;
  860. #include "PassRegistry.def"
  861. return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
  862. }
  863. template <typename CallbacksT>
  864. static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks,
  865. bool &UseMemorySSA) {
  866. UseMemorySSA = false;
  867. // Explicitly handle custom-parsed pass names.
  868. if (parseRepeatPassName(Name))
  869. return true;
  870. if (Name == "licm") {
  871. UseMemorySSA = true;
  872. return true;
  873. }
  874. #define LOOP_PASS(NAME, CREATE_PASS) \
  875. if (Name == NAME) \
  876. return true;
  877. #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  878. if (checkParametrizedPassName(Name, NAME)) \
  879. return true;
  880. #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
  881. if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
  882. return true;
  883. #include "PassRegistry.def"
  884. return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
  885. }
  886. Optional<std::vector<PassBuilder::PipelineElement>>
  887. PassBuilder::parsePipelineText(StringRef Text) {
  888. std::vector<PipelineElement> ResultPipeline;
  889. SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
  890. &ResultPipeline};
  891. for (;;) {
  892. std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
  893. size_t Pos = Text.find_first_of(",()");
  894. Pipeline.push_back({Text.substr(0, Pos), {}});
  895. // If we have a single terminating name, we're done.
  896. if (Pos == Text.npos)
  897. break;
  898. char Sep = Text[Pos];
  899. Text = Text.substr(Pos + 1);
  900. if (Sep == ',')
  901. // Just a name ending in a comma, continue.
  902. continue;
  903. if (Sep == '(') {
  904. // Push the inner pipeline onto the stack to continue processing.
  905. PipelineStack.push_back(&Pipeline.back().InnerPipeline);
  906. continue;
  907. }
  908. assert(Sep == ')' && "Bogus separator!");
  909. // When handling the close parenthesis, we greedily consume them to avoid
  910. // empty strings in the pipeline.
  911. do {
  912. // If we try to pop the outer pipeline we have unbalanced parentheses.
  913. if (PipelineStack.size() == 1)
  914. return None;
  915. PipelineStack.pop_back();
  916. } while (Text.consume_front(")"));
  917. // Check if we've finished parsing.
  918. if (Text.empty())
  919. break;
  920. // Otherwise, the end of an inner pipeline always has to be followed by
  921. // a comma, and then we can continue.
  922. if (!Text.consume_front(","))
  923. return None;
  924. }
  925. if (PipelineStack.size() > 1)
  926. // Unbalanced paretheses.
  927. return None;
  928. assert(PipelineStack.back() == &ResultPipeline &&
  929. "Wrong pipeline at the bottom of the stack!");
  930. return {std::move(ResultPipeline)};
  931. }
  932. Error PassBuilder::parseModulePass(ModulePassManager &MPM,
  933. const PipelineElement &E) {
  934. auto &Name = E.Name;
  935. auto &InnerPipeline = E.InnerPipeline;
  936. // First handle complex passes like the pass managers which carry pipelines.
  937. if (!InnerPipeline.empty()) {
  938. if (Name == "module") {
  939. ModulePassManager NestedMPM;
  940. if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline))
  941. return Err;
  942. MPM.addPass(std::move(NestedMPM));
  943. return Error::success();
  944. }
  945. if (Name == "cgscc") {
  946. CGSCCPassManager CGPM;
  947. if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline))
  948. return Err;
  949. MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
  950. return Error::success();
  951. }
  952. if (Name == "function" || Name == "function<eager-inv>") {
  953. FunctionPassManager FPM;
  954. if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline))
  955. return Err;
  956. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),
  957. Name != "function"));
  958. return Error::success();
  959. }
  960. if (auto Count = parseRepeatPassName(Name)) {
  961. ModulePassManager NestedMPM;
  962. if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline))
  963. return Err;
  964. MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
  965. return Error::success();
  966. }
  967. for (auto &C : ModulePipelineParsingCallbacks)
  968. if (C(Name, MPM, InnerPipeline))
  969. return Error::success();
  970. // Normal passes can't have pipelines.
  971. return make_error<StringError>(
  972. formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
  973. inconvertibleErrorCode());
  974. ;
  975. }
  976. // Manually handle aliases for pre-configured pipeline fragments.
  977. if (startsWithDefaultPipelineAliasPrefix(Name)) {
  978. SmallVector<StringRef, 3> Matches;
  979. if (!DefaultAliasRegex.match(Name, &Matches))
  980. return make_error<StringError>(
  981. formatv("unknown default pipeline alias '{0}'", Name).str(),
  982. inconvertibleErrorCode());
  983. assert(Matches.size() == 3 && "Must capture two matched strings!");
  984. OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
  985. .Case("O0", OptimizationLevel::O0)
  986. .Case("O1", OptimizationLevel::O1)
  987. .Case("O2", OptimizationLevel::O2)
  988. .Case("O3", OptimizationLevel::O3)
  989. .Case("Os", OptimizationLevel::Os)
  990. .Case("Oz", OptimizationLevel::Oz);
  991. if (L == OptimizationLevel::O0 && Matches[1] != "thinlto" &&
  992. Matches[1] != "lto") {
  993. MPM.addPass(buildO0DefaultPipeline(L, Matches[1] == "thinlto-pre-link" ||
  994. Matches[1] == "lto-pre-link"));
  995. return Error::success();
  996. }
  997. // This is consistent with old pass manager invoked via opt, but
  998. // inconsistent with clang. Clang doesn't enable loop vectorization
  999. // but does enable slp vectorization at Oz.
  1000. PTO.LoopVectorization =
  1001. L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz;
  1002. PTO.SLPVectorization =
  1003. L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz;
  1004. if (Matches[1] == "default") {
  1005. MPM.addPass(buildPerModuleDefaultPipeline(L));
  1006. } else if (Matches[1] == "thinlto-pre-link") {
  1007. MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L));
  1008. } else if (Matches[1] == "thinlto") {
  1009. MPM.addPass(buildThinLTODefaultPipeline(L, nullptr));
  1010. } else if (Matches[1] == "lto-pre-link") {
  1011. MPM.addPass(buildLTOPreLinkDefaultPipeline(L));
  1012. } else {
  1013. assert(Matches[1] == "lto" && "Not one of the matched options!");
  1014. MPM.addPass(buildLTODefaultPipeline(L, nullptr));
  1015. }
  1016. return Error::success();
  1017. }
  1018. // Finally expand the basic registered passes from the .inc file.
  1019. #define MODULE_PASS(NAME, CREATE_PASS) \
  1020. if (Name == NAME) { \
  1021. MPM.addPass(CREATE_PASS); \
  1022. return Error::success(); \
  1023. }
  1024. #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1025. if (checkParametrizedPassName(Name, NAME)) { \
  1026. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1027. if (!Params) \
  1028. return Params.takeError(); \
  1029. MPM.addPass(CREATE_PASS(Params.get())); \
  1030. return Error::success(); \
  1031. }
  1032. #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
  1033. if (Name == "require<" NAME ">") { \
  1034. MPM.addPass( \
  1035. RequireAnalysisPass< \
  1036. std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
  1037. return Error::success(); \
  1038. } \
  1039. if (Name == "invalidate<" NAME ">") { \
  1040. MPM.addPass(InvalidateAnalysisPass< \
  1041. std::remove_reference<decltype(CREATE_PASS)>::type>()); \
  1042. return Error::success(); \
  1043. }
  1044. #define CGSCC_PASS(NAME, CREATE_PASS) \
  1045. if (Name == NAME) { \
  1046. MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(CREATE_PASS)); \
  1047. return Error::success(); \
  1048. }
  1049. #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1050. if (checkParametrizedPassName(Name, NAME)) { \
  1051. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1052. if (!Params) \
  1053. return Params.takeError(); \
  1054. MPM.addPass( \
  1055. createModuleToPostOrderCGSCCPassAdaptor(CREATE_PASS(Params.get()))); \
  1056. return Error::success(); \
  1057. }
  1058. #define FUNCTION_PASS(NAME, CREATE_PASS) \
  1059. if (Name == NAME) { \
  1060. MPM.addPass(createModuleToFunctionPassAdaptor(CREATE_PASS)); \
  1061. return Error::success(); \
  1062. }
  1063. #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1064. if (checkParametrizedPassName(Name, NAME)) { \
  1065. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1066. if (!Params) \
  1067. return Params.takeError(); \
  1068. MPM.addPass(createModuleToFunctionPassAdaptor(CREATE_PASS(Params.get()))); \
  1069. return Error::success(); \
  1070. }
  1071. #define LOOPNEST_PASS(NAME, CREATE_PASS) \
  1072. if (Name == NAME) { \
  1073. MPM.addPass(createModuleToFunctionPassAdaptor( \
  1074. createFunctionToLoopPassAdaptor(CREATE_PASS, false, false))); \
  1075. return Error::success(); \
  1076. }
  1077. #define LOOP_PASS(NAME, CREATE_PASS) \
  1078. if (Name == NAME) { \
  1079. MPM.addPass(createModuleToFunctionPassAdaptor( \
  1080. createFunctionToLoopPassAdaptor(CREATE_PASS, false, false))); \
  1081. return Error::success(); \
  1082. }
  1083. #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1084. if (checkParametrizedPassName(Name, NAME)) { \
  1085. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1086. if (!Params) \
  1087. return Params.takeError(); \
  1088. MPM.addPass( \
  1089. createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor( \
  1090. CREATE_PASS(Params.get()), false, false))); \
  1091. return Error::success(); \
  1092. }
  1093. #include "PassRegistry.def"
  1094. for (auto &C : ModulePipelineParsingCallbacks)
  1095. if (C(Name, MPM, InnerPipeline))
  1096. return Error::success();
  1097. return make_error<StringError>(
  1098. formatv("unknown module pass '{0}'", Name).str(),
  1099. inconvertibleErrorCode());
  1100. }
  1101. Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
  1102. const PipelineElement &E) {
  1103. auto &Name = E.Name;
  1104. auto &InnerPipeline = E.InnerPipeline;
  1105. // First handle complex passes like the pass managers which carry pipelines.
  1106. if (!InnerPipeline.empty()) {
  1107. if (Name == "cgscc") {
  1108. CGSCCPassManager NestedCGPM;
  1109. if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
  1110. return Err;
  1111. // Add the nested pass manager with the appropriate adaptor.
  1112. CGPM.addPass(std::move(NestedCGPM));
  1113. return Error::success();
  1114. }
  1115. if (Name == "function" || Name == "function<eager-inv>") {
  1116. FunctionPassManager FPM;
  1117. if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline))
  1118. return Err;
  1119. // Add the nested pass manager with the appropriate adaptor.
  1120. CGPM.addPass(
  1121. createCGSCCToFunctionPassAdaptor(std::move(FPM), Name != "function"));
  1122. return Error::success();
  1123. }
  1124. if (auto Count = parseRepeatPassName(Name)) {
  1125. CGSCCPassManager NestedCGPM;
  1126. if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
  1127. return Err;
  1128. CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
  1129. return Error::success();
  1130. }
  1131. if (auto MaxRepetitions = parseDevirtPassName(Name)) {
  1132. CGSCCPassManager NestedCGPM;
  1133. if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
  1134. return Err;
  1135. CGPM.addPass(
  1136. createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
  1137. return Error::success();
  1138. }
  1139. for (auto &C : CGSCCPipelineParsingCallbacks)
  1140. if (C(Name, CGPM, InnerPipeline))
  1141. return Error::success();
  1142. // Normal passes can't have pipelines.
  1143. return make_error<StringError>(
  1144. formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
  1145. inconvertibleErrorCode());
  1146. }
  1147. // Now expand the basic registered passes from the .inc file.
  1148. #define CGSCC_PASS(NAME, CREATE_PASS) \
  1149. if (Name == NAME) { \
  1150. CGPM.addPass(CREATE_PASS); \
  1151. return Error::success(); \
  1152. }
  1153. #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1154. if (checkParametrizedPassName(Name, NAME)) { \
  1155. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1156. if (!Params) \
  1157. return Params.takeError(); \
  1158. CGPM.addPass(CREATE_PASS(Params.get())); \
  1159. return Error::success(); \
  1160. }
  1161. #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
  1162. if (Name == "require<" NAME ">") { \
  1163. CGPM.addPass(RequireAnalysisPass< \
  1164. std::remove_reference<decltype(CREATE_PASS)>::type, \
  1165. LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
  1166. CGSCCUpdateResult &>()); \
  1167. return Error::success(); \
  1168. } \
  1169. if (Name == "invalidate<" NAME ">") { \
  1170. CGPM.addPass(InvalidateAnalysisPass< \
  1171. std::remove_reference<decltype(CREATE_PASS)>::type>()); \
  1172. return Error::success(); \
  1173. }
  1174. #define FUNCTION_PASS(NAME, CREATE_PASS) \
  1175. if (Name == NAME) { \
  1176. CGPM.addPass(createCGSCCToFunctionPassAdaptor(CREATE_PASS)); \
  1177. return Error::success(); \
  1178. }
  1179. #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1180. if (checkParametrizedPassName(Name, NAME)) { \
  1181. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1182. if (!Params) \
  1183. return Params.takeError(); \
  1184. CGPM.addPass(createCGSCCToFunctionPassAdaptor(CREATE_PASS(Params.get()))); \
  1185. return Error::success(); \
  1186. }
  1187. #define LOOPNEST_PASS(NAME, CREATE_PASS) \
  1188. if (Name == NAME) { \
  1189. CGPM.addPass(createCGSCCToFunctionPassAdaptor( \
  1190. createFunctionToLoopPassAdaptor(CREATE_PASS, false, false))); \
  1191. return Error::success(); \
  1192. }
  1193. #define LOOP_PASS(NAME, CREATE_PASS) \
  1194. if (Name == NAME) { \
  1195. CGPM.addPass(createCGSCCToFunctionPassAdaptor( \
  1196. createFunctionToLoopPassAdaptor(CREATE_PASS, false, false))); \
  1197. return Error::success(); \
  1198. }
  1199. #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1200. if (checkParametrizedPassName(Name, NAME)) { \
  1201. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1202. if (!Params) \
  1203. return Params.takeError(); \
  1204. CGPM.addPass( \
  1205. createCGSCCToFunctionPassAdaptor(createFunctionToLoopPassAdaptor( \
  1206. CREATE_PASS(Params.get()), false, false))); \
  1207. return Error::success(); \
  1208. }
  1209. #include "PassRegistry.def"
  1210. for (auto &C : CGSCCPipelineParsingCallbacks)
  1211. if (C(Name, CGPM, InnerPipeline))
  1212. return Error::success();
  1213. return make_error<StringError>(
  1214. formatv("unknown cgscc pass '{0}'", Name).str(),
  1215. inconvertibleErrorCode());
  1216. }
  1217. Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
  1218. const PipelineElement &E) {
  1219. auto &Name = E.Name;
  1220. auto &InnerPipeline = E.InnerPipeline;
  1221. // First handle complex passes like the pass managers which carry pipelines.
  1222. if (!InnerPipeline.empty()) {
  1223. if (Name == "function") {
  1224. FunctionPassManager NestedFPM;
  1225. if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline))
  1226. return Err;
  1227. // Add the nested pass manager with the appropriate adaptor.
  1228. FPM.addPass(std::move(NestedFPM));
  1229. return Error::success();
  1230. }
  1231. if (Name == "loop" || Name == "loop-mssa") {
  1232. LoopPassManager LPM;
  1233. if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline))
  1234. return Err;
  1235. // Add the nested pass manager with the appropriate adaptor.
  1236. bool UseMemorySSA = (Name == "loop-mssa");
  1237. bool UseBFI = llvm::any_of(
  1238. InnerPipeline, [](auto Pipeline) { return Pipeline.Name == "licm"; });
  1239. bool UseBPI = llvm::any_of(InnerPipeline, [](auto Pipeline) {
  1240. return Pipeline.Name == "loop-predication";
  1241. });
  1242. FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM), UseMemorySSA,
  1243. UseBFI, UseBPI));
  1244. return Error::success();
  1245. }
  1246. if (auto Count = parseRepeatPassName(Name)) {
  1247. FunctionPassManager NestedFPM;
  1248. if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline))
  1249. return Err;
  1250. FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
  1251. return Error::success();
  1252. }
  1253. for (auto &C : FunctionPipelineParsingCallbacks)
  1254. if (C(Name, FPM, InnerPipeline))
  1255. return Error::success();
  1256. // Normal passes can't have pipelines.
  1257. return make_error<StringError>(
  1258. formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
  1259. inconvertibleErrorCode());
  1260. }
  1261. // Now expand the basic registered passes from the .inc file.
  1262. #define FUNCTION_PASS(NAME, CREATE_PASS) \
  1263. if (Name == NAME) { \
  1264. FPM.addPass(CREATE_PASS); \
  1265. return Error::success(); \
  1266. }
  1267. #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1268. if (checkParametrizedPassName(Name, NAME)) { \
  1269. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1270. if (!Params) \
  1271. return Params.takeError(); \
  1272. FPM.addPass(CREATE_PASS(Params.get())); \
  1273. return Error::success(); \
  1274. }
  1275. #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
  1276. if (Name == "require<" NAME ">") { \
  1277. FPM.addPass( \
  1278. RequireAnalysisPass< \
  1279. std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
  1280. return Error::success(); \
  1281. } \
  1282. if (Name == "invalidate<" NAME ">") { \
  1283. FPM.addPass(InvalidateAnalysisPass< \
  1284. std::remove_reference<decltype(CREATE_PASS)>::type>()); \
  1285. return Error::success(); \
  1286. }
  1287. // FIXME: UseMemorySSA is set to false. Maybe we could do things like:
  1288. // bool UseMemorySSA = !("canon-freeze" || "loop-predication" ||
  1289. // "guard-widening");
  1290. // The risk is that it may become obsolete if we're not careful.
  1291. #define LOOPNEST_PASS(NAME, CREATE_PASS) \
  1292. if (Name == NAME) { \
  1293. FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)); \
  1294. return Error::success(); \
  1295. }
  1296. #define LOOP_PASS(NAME, CREATE_PASS) \
  1297. if (Name == NAME) { \
  1298. FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)); \
  1299. return Error::success(); \
  1300. }
  1301. #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1302. if (checkParametrizedPassName(Name, NAME)) { \
  1303. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1304. if (!Params) \
  1305. return Params.takeError(); \
  1306. FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS(Params.get()), \
  1307. false, false)); \
  1308. return Error::success(); \
  1309. }
  1310. #include "PassRegistry.def"
  1311. for (auto &C : FunctionPipelineParsingCallbacks)
  1312. if (C(Name, FPM, InnerPipeline))
  1313. return Error::success();
  1314. return make_error<StringError>(
  1315. formatv("unknown function pass '{0}'", Name).str(),
  1316. inconvertibleErrorCode());
  1317. }
  1318. Error PassBuilder::parseLoopPass(LoopPassManager &LPM,
  1319. const PipelineElement &E) {
  1320. StringRef Name = E.Name;
  1321. auto &InnerPipeline = E.InnerPipeline;
  1322. // First handle complex passes like the pass managers which carry pipelines.
  1323. if (!InnerPipeline.empty()) {
  1324. if (Name == "loop") {
  1325. LoopPassManager NestedLPM;
  1326. if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline))
  1327. return Err;
  1328. // Add the nested pass manager with the appropriate adaptor.
  1329. LPM.addPass(std::move(NestedLPM));
  1330. return Error::success();
  1331. }
  1332. if (auto Count = parseRepeatPassName(Name)) {
  1333. LoopPassManager NestedLPM;
  1334. if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline))
  1335. return Err;
  1336. LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
  1337. return Error::success();
  1338. }
  1339. for (auto &C : LoopPipelineParsingCallbacks)
  1340. if (C(Name, LPM, InnerPipeline))
  1341. return Error::success();
  1342. // Normal passes can't have pipelines.
  1343. return make_error<StringError>(
  1344. formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
  1345. inconvertibleErrorCode());
  1346. }
  1347. // Now expand the basic registered passes from the .inc file.
  1348. #define LOOPNEST_PASS(NAME, CREATE_PASS) \
  1349. if (Name == NAME) { \
  1350. LPM.addPass(CREATE_PASS); \
  1351. return Error::success(); \
  1352. }
  1353. #define LOOP_PASS(NAME, CREATE_PASS) \
  1354. if (Name == NAME) { \
  1355. LPM.addPass(CREATE_PASS); \
  1356. return Error::success(); \
  1357. }
  1358. #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1359. if (checkParametrizedPassName(Name, NAME)) { \
  1360. auto Params = parsePassParameters(PARSER, Name, NAME); \
  1361. if (!Params) \
  1362. return Params.takeError(); \
  1363. LPM.addPass(CREATE_PASS(Params.get())); \
  1364. return Error::success(); \
  1365. }
  1366. #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
  1367. if (Name == "require<" NAME ">") { \
  1368. LPM.addPass(RequireAnalysisPass< \
  1369. std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
  1370. LoopAnalysisManager, LoopStandardAnalysisResults &, \
  1371. LPMUpdater &>()); \
  1372. return Error::success(); \
  1373. } \
  1374. if (Name == "invalidate<" NAME ">") { \
  1375. LPM.addPass(InvalidateAnalysisPass< \
  1376. std::remove_reference<decltype(CREATE_PASS)>::type>()); \
  1377. return Error::success(); \
  1378. }
  1379. #include "PassRegistry.def"
  1380. for (auto &C : LoopPipelineParsingCallbacks)
  1381. if (C(Name, LPM, InnerPipeline))
  1382. return Error::success();
  1383. return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
  1384. inconvertibleErrorCode());
  1385. }
  1386. bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
  1387. #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
  1388. if (Name == NAME) { \
  1389. AA.registerModuleAnalysis< \
  1390. std::remove_reference<decltype(CREATE_PASS)>::type>(); \
  1391. return true; \
  1392. }
  1393. #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
  1394. if (Name == NAME) { \
  1395. AA.registerFunctionAnalysis< \
  1396. std::remove_reference<decltype(CREATE_PASS)>::type>(); \
  1397. return true; \
  1398. }
  1399. #include "PassRegistry.def"
  1400. for (auto &C : AAParsingCallbacks)
  1401. if (C(Name, AA))
  1402. return true;
  1403. return false;
  1404. }
  1405. Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
  1406. ArrayRef<PipelineElement> Pipeline) {
  1407. for (const auto &Element : Pipeline) {
  1408. if (auto Err = parseLoopPass(LPM, Element))
  1409. return Err;
  1410. }
  1411. return Error::success();
  1412. }
  1413. Error PassBuilder::parseFunctionPassPipeline(
  1414. FunctionPassManager &FPM, ArrayRef<PipelineElement> Pipeline) {
  1415. for (const auto &Element : Pipeline) {
  1416. if (auto Err = parseFunctionPass(FPM, Element))
  1417. return Err;
  1418. }
  1419. return Error::success();
  1420. }
  1421. Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
  1422. ArrayRef<PipelineElement> Pipeline) {
  1423. for (const auto &Element : Pipeline) {
  1424. if (auto Err = parseCGSCCPass(CGPM, Element))
  1425. return Err;
  1426. }
  1427. return Error::success();
  1428. }
  1429. void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
  1430. FunctionAnalysisManager &FAM,
  1431. CGSCCAnalysisManager &CGAM,
  1432. ModuleAnalysisManager &MAM) {
  1433. MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
  1434. MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
  1435. CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
  1436. FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
  1437. FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
  1438. FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
  1439. LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
  1440. }
  1441. Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
  1442. ArrayRef<PipelineElement> Pipeline) {
  1443. for (const auto &Element : Pipeline) {
  1444. if (auto Err = parseModulePass(MPM, Element))
  1445. return Err;
  1446. }
  1447. return Error::success();
  1448. }
  1449. // Primary pass pipeline description parsing routine for a \c ModulePassManager
  1450. // FIXME: Should this routine accept a TargetMachine or require the caller to
  1451. // pre-populate the analysis managers with target-specific stuff?
  1452. Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
  1453. StringRef PipelineText) {
  1454. auto Pipeline = parsePipelineText(PipelineText);
  1455. if (!Pipeline || Pipeline->empty())
  1456. return make_error<StringError>(
  1457. formatv("invalid pipeline '{0}'", PipelineText).str(),
  1458. inconvertibleErrorCode());
  1459. // If the first name isn't at the module layer, wrap the pipeline up
  1460. // automatically.
  1461. StringRef FirstName = Pipeline->front().Name;
  1462. if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
  1463. bool UseMemorySSA;
  1464. if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
  1465. Pipeline = {{"cgscc", std::move(*Pipeline)}};
  1466. } else if (isFunctionPassName(FirstName,
  1467. FunctionPipelineParsingCallbacks)) {
  1468. Pipeline = {{"function", std::move(*Pipeline)}};
  1469. } else if (isLoopNestPassName(FirstName, LoopPipelineParsingCallbacks,
  1470. UseMemorySSA)) {
  1471. Pipeline = {{"function", {{UseMemorySSA ? "loop-mssa" : "loop",
  1472. std::move(*Pipeline)}}}};
  1473. } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks,
  1474. UseMemorySSA)) {
  1475. Pipeline = {{"function", {{UseMemorySSA ? "loop-mssa" : "loop",
  1476. std::move(*Pipeline)}}}};
  1477. } else {
  1478. for (auto &C : TopLevelPipelineParsingCallbacks)
  1479. if (C(MPM, *Pipeline))
  1480. return Error::success();
  1481. // Unknown pass or pipeline name!
  1482. auto &InnerPipeline = Pipeline->front().InnerPipeline;
  1483. return make_error<StringError>(
  1484. formatv("unknown {0} name '{1}'",
  1485. (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
  1486. .str(),
  1487. inconvertibleErrorCode());
  1488. }
  1489. }
  1490. if (auto Err = parseModulePassPipeline(MPM, *Pipeline))
  1491. return Err;
  1492. return Error::success();
  1493. }
  1494. // Primary pass pipeline description parsing routine for a \c CGSCCPassManager
  1495. Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
  1496. StringRef PipelineText) {
  1497. auto Pipeline = parsePipelineText(PipelineText);
  1498. if (!Pipeline || Pipeline->empty())
  1499. return make_error<StringError>(
  1500. formatv("invalid pipeline '{0}'", PipelineText).str(),
  1501. inconvertibleErrorCode());
  1502. StringRef FirstName = Pipeline->front().Name;
  1503. if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
  1504. return make_error<StringError>(
  1505. formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
  1506. PipelineText)
  1507. .str(),
  1508. inconvertibleErrorCode());
  1509. if (auto Err = parseCGSCCPassPipeline(CGPM, *Pipeline))
  1510. return Err;
  1511. return Error::success();
  1512. }
  1513. // Primary pass pipeline description parsing routine for a \c
  1514. // FunctionPassManager
  1515. Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
  1516. StringRef PipelineText) {
  1517. auto Pipeline = parsePipelineText(PipelineText);
  1518. if (!Pipeline || Pipeline->empty())
  1519. return make_error<StringError>(
  1520. formatv("invalid pipeline '{0}'", PipelineText).str(),
  1521. inconvertibleErrorCode());
  1522. StringRef FirstName = Pipeline->front().Name;
  1523. if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
  1524. return make_error<StringError>(
  1525. formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
  1526. PipelineText)
  1527. .str(),
  1528. inconvertibleErrorCode());
  1529. if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline))
  1530. return Err;
  1531. return Error::success();
  1532. }
  1533. // Primary pass pipeline description parsing routine for a \c LoopPassManager
  1534. Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
  1535. StringRef PipelineText) {
  1536. auto Pipeline = parsePipelineText(PipelineText);
  1537. if (!Pipeline || Pipeline->empty())
  1538. return make_error<StringError>(
  1539. formatv("invalid pipeline '{0}'", PipelineText).str(),
  1540. inconvertibleErrorCode());
  1541. if (auto Err = parseLoopPassPipeline(CGPM, *Pipeline))
  1542. return Err;
  1543. return Error::success();
  1544. }
  1545. Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
  1546. // If the pipeline just consists of the word 'default' just replace the AA
  1547. // manager with our default one.
  1548. if (PipelineText == "default") {
  1549. AA = buildDefaultAAPipeline();
  1550. return Error::success();
  1551. }
  1552. while (!PipelineText.empty()) {
  1553. StringRef Name;
  1554. std::tie(Name, PipelineText) = PipelineText.split(',');
  1555. if (!parseAAPassName(AA, Name))
  1556. return make_error<StringError>(
  1557. formatv("unknown alias analysis name '{0}'", Name).str(),
  1558. inconvertibleErrorCode());
  1559. }
  1560. return Error::success();
  1561. }
  1562. bool PassBuilder::isAAPassName(StringRef PassName) {
  1563. #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
  1564. if (PassName == NAME) \
  1565. return true;
  1566. #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
  1567. if (PassName == NAME) \
  1568. return true;
  1569. #include "PassRegistry.def"
  1570. return false;
  1571. }
  1572. bool PassBuilder::isAnalysisPassName(StringRef PassName) {
  1573. #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
  1574. if (PassName == NAME) \
  1575. return true;
  1576. #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
  1577. if (PassName == NAME) \
  1578. return true;
  1579. #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
  1580. if (PassName == NAME) \
  1581. return true;
  1582. #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
  1583. if (PassName == NAME) \
  1584. return true;
  1585. #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
  1586. if (PassName == NAME) \
  1587. return true;
  1588. #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
  1589. if (PassName == NAME) \
  1590. return true;
  1591. #include "PassRegistry.def"
  1592. return false;
  1593. }
  1594. static void printPassName(StringRef PassName, raw_ostream &OS) {
  1595. OS << " " << PassName << "\n";
  1596. }
  1597. static void printPassName(StringRef PassName, StringRef Params,
  1598. raw_ostream &OS) {
  1599. OS << " " << PassName << "<" << Params << ">\n";
  1600. }
  1601. void PassBuilder::printPassNames(raw_ostream &OS) {
  1602. // TODO: print pass descriptions when they are available
  1603. OS << "Module passes:\n";
  1604. #define MODULE_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1605. #include "PassRegistry.def"
  1606. OS << "Module passes with params:\n";
  1607. #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1608. printPassName(NAME, PARAMS, OS);
  1609. #include "PassRegistry.def"
  1610. OS << "Module analyses:\n";
  1611. #define MODULE_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1612. #include "PassRegistry.def"
  1613. OS << "Module alias analyses:\n";
  1614. #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1615. #include "PassRegistry.def"
  1616. OS << "CGSCC passes:\n";
  1617. #define CGSCC_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1618. #include "PassRegistry.def"
  1619. OS << "CGSCC passes with params:\n";
  1620. #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1621. printPassName(NAME, PARAMS, OS);
  1622. #include "PassRegistry.def"
  1623. OS << "CGSCC analyses:\n";
  1624. #define CGSCC_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1625. #include "PassRegistry.def"
  1626. OS << "Function passes:\n";
  1627. #define FUNCTION_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1628. #include "PassRegistry.def"
  1629. OS << "Function passes with params:\n";
  1630. #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1631. printPassName(NAME, PARAMS, OS);
  1632. #include "PassRegistry.def"
  1633. OS << "Function analyses:\n";
  1634. #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1635. #include "PassRegistry.def"
  1636. OS << "Function alias analyses:\n";
  1637. #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1638. #include "PassRegistry.def"
  1639. OS << "LoopNest passes:\n";
  1640. #define LOOPNEST_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1641. #include "PassRegistry.def"
  1642. OS << "Loop passes:\n";
  1643. #define LOOP_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1644. #include "PassRegistry.def"
  1645. OS << "Loop passes with params:\n";
  1646. #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
  1647. printPassName(NAME, PARAMS, OS);
  1648. #include "PassRegistry.def"
  1649. OS << "Loop analyses:\n";
  1650. #define LOOP_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
  1651. #include "PassRegistry.def"
  1652. }
  1653. void PassBuilder::registerParseTopLevelPipelineCallback(
  1654. const std::function<bool(ModulePassManager &, ArrayRef<PipelineElement>)>
  1655. &C) {
  1656. TopLevelPipelineParsingCallbacks.push_back(C);
  1657. }