blob: 2f567262fbb7456ff79b6cbf668de800c1ea4969 [file] [log] [blame]
Chandler Carruth1ff77242015-03-07 09:02:36 +00001//===- Parsing, selection, and construction of pass pipelines -------------===//
Chandler Carruth66445382014-01-11 08:16:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10///
Chandler Carruth1ff77242015-03-07 09:02:36 +000011/// This file provides the implementation of the PassBuilder based on our
12/// static pass registry as well as related functionality. It also provides
13/// helpers to aid in analyzing, debugging, and testing passes and pass
14/// pipelines.
Chandler Carruth66445382014-01-11 08:16:35 +000015///
16//===----------------------------------------------------------------------===//
17
Chandler Carruth1ff77242015-03-07 09:02:36 +000018#include "llvm/Passes/PassBuilder.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000019#include "llvm/ADT/StringSwitch.h"
Chandler Carruth6f5770b102016-02-13 23:32:00 +000020#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth4f846a52016-02-20 03:46:03 +000021#include "llvm/Analysis/AliasAnalysisEvaluator.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000022#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthbece8d52016-02-13 23:46:24 +000023#include "llvm/Analysis/BasicAliasAnalysis.h"
Xinliang David Li28a93272016-05-05 21:13:27 +000024#include "llvm/Analysis/BlockFrequencyInfo.h"
Xinliang David Li6e5dd412016-05-05 02:59:57 +000025#include "llvm/Analysis/BranchProbabilityInfo.h"
Mehdi Amini27d23792016-09-16 16:56:30 +000026#include "llvm/Analysis/CFGPrinter.h"
George Burgess IVbfa401e2016-07-06 00:26:41 +000027#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
28#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
Chandler Carruth572e3402014-04-21 11:12:00 +000029#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruth4c660f72016-03-10 11:24:11 +000030#include "llvm/Analysis/CallGraph.h"
Michael Kupersteinde16b442016-04-18 23:55:01 +000031#include "llvm/Analysis/DemandedBits.h"
Chandler Carruth49c22192016-05-12 22:19:39 +000032#include "llvm/Analysis/DependenceAnalysis.h"
Hongbin Zheng751337f2016-02-25 17:54:15 +000033#include "llvm/Analysis/DominanceFrontier.h"
Chandler Carruth45a9c202016-03-11 09:15:11 +000034#include "llvm/Analysis/GlobalsModRef.h"
Dehao Chen1a444522016-07-16 22:51:33 +000035#include "llvm/Analysis/IVUsers.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000036#include "llvm/Analysis/LazyCallGraph.h"
Sean Silva687019f2016-06-13 22:01:25 +000037#include "llvm/Analysis/LazyValueInfo.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000038#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000039#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth61440d22016-03-10 00:55:30 +000040#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000041#include "llvm/Analysis/MemorySSA.h"
Teresa Johnsonf93b2462016-08-12 13:53:02 +000042#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000043#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawnbdbbd832018-06-28 14:13:06 +000044#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng3f978402016-02-25 17:54:07 +000045#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000046#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000047#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000048#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000049#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000050#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000051#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000052#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000053#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000054#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000055#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000056#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000057#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000058#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000059#include "llvm/IR/PassManager.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000060#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000061#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000062#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000063#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000064#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000065#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000066#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000067#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000068#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000069#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000070#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000071#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000072#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000073#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000074#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000075#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000076#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000077#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000078#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000079#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000080#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000081#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000082#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000083#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000084#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000085#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000086#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000087#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000088#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000089#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000090#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000091#include "llvm/Transforms/Instrumentation.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000092#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000093#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000094#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000095#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
96#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000097#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +000098#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Justin Bogner19b67992015-10-30 23:13:18 +000099#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000100#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000101#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000102#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000103#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000104#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000105#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000106#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000107#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000108#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000109#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000110#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000111#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000112#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000113#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000114#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000115#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000116#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000117#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000118#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000119#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000120#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000121#include "llvm/Transforms/Scalar/LoopDistribute.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000122#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000123#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000124#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000125#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000126#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000127#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000128#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000129#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000130#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000131#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000132#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000133#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000134#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000135#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000136#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000137#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000138#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000139#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000140#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000141#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000142#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000143#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000144#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000145#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000146#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000147#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000148#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000149#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000150#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000151#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000152#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000153#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000154#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000155#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000156#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000157#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000158#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000159#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000160#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000161#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000162#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000163#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000164#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000165#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000166#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000167
Chandler Carruth66445382014-01-11 08:16:35 +0000168using namespace llvm;
169
Chandler Carruth719ffe12017-02-12 05:38:04 +0000170static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
171 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000172static cl::opt<bool>
173 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
174 cl::Hidden, cl::ZeroOrMore,
175 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000176
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000177static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000178 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000179 cl::Hidden, cl::ZeroOrMore,
180 cl::desc("Run NewGVN instead of GVN"));
181
Geoff Berry3cca1da2017-06-10 15:20:03 +0000182static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000183 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
184 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000185
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000186static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000187 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
188 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000189
Davide Italianobe1b6a92017-06-03 23:18:29 +0000190static cl::opt<bool> EnableGVNSink(
191 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
192 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
193
David Green963401d2018-07-01 12:47:30 +0000194static cl::opt<bool> EnableUnrollAndJam(
195 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
196 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
197
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000198static cl::opt<bool> EnableSyntheticCounts(
199 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
200 cl::desc("Run synthetic function entry count generation "
201 "pass"));
202
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000203static Regex DefaultAliasRegex(
204 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000205
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000206static cl::opt<bool>
207 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
208 cl::desc("Enable control height reduction optimization (CHR)"));
209
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000210extern cl::opt<bool> EnableHotColdSplit;
211
Chandler Carruthe3f50642016-12-22 06:59:15 +0000212static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
213 switch (Level) {
214 case PassBuilder::O0:
215 case PassBuilder::O1:
216 case PassBuilder::O2:
217 case PassBuilder::O3:
218 return false;
219
220 case PassBuilder::Os:
221 case PassBuilder::Oz:
222 return true;
223 }
224 llvm_unreachable("Invalid optimization level!");
225}
226
Chandler Carruth66445382014-01-11 08:16:35 +0000227namespace {
228
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000229/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000230struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000231 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000232 return PreservedAnalyses::all();
233 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000234 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000235};
236
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000237/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000238class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
239 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000240 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000241
242public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000243 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000244 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000245 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000246};
247
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000248/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000249struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000250 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
251 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000252 return PreservedAnalyses::all();
253 }
254 static StringRef name() { return "NoOpCGSCCPass"; }
255};
256
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000257/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000258class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
259 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000260 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000261
262public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000263 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000264 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000265 return Result();
266 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000267 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000268};
269
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000270/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000271struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000272 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000273 return PreservedAnalyses::all();
274 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000275 static StringRef name() { return "NoOpFunctionPass"; }
276};
277
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000278/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000279class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
280 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000281 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000282
283public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000284 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000285 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000286 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000287};
288
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000289/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000290struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000291 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
292 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000293 return PreservedAnalyses::all();
294 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000295 static StringRef name() { return "NoOpLoopPass"; }
296};
297
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000298/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000299class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
300 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000301 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000302
303public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000304 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000305 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
306 return Result();
307 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000308 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000309};
310
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000311AnalysisKey NoOpModuleAnalysis::Key;
312AnalysisKey NoOpCGSCCAnalysis::Key;
313AnalysisKey NoOpFunctionAnalysis::Key;
314AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000315
Chandler Carruth66445382014-01-11 08:16:35 +0000316} // End anonymous namespace.
317
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000318void PassBuilder::invokePeepholeEPCallbacks(
319 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
320 for (auto &C : PeepholeEPCallbacks)
321 C(FPM, Level);
322}
323
Chandler Carruth1ff77242015-03-07 09:02:36 +0000324void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000325#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000326 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000327#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000328
329 for (auto &C : ModuleAnalysisRegistrationCallbacks)
330 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000331}
332
Chandler Carruth1ff77242015-03-07 09:02:36 +0000333void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000334#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000335 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000336#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000337
338 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
339 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000340}
341
Chandler Carruth1ff77242015-03-07 09:02:36 +0000342void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000343#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000344 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000345#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000346
347 for (auto &C : FunctionAnalysisRegistrationCallbacks)
348 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000349}
350
Justin Bognereecc3c82016-02-25 07:23:08 +0000351void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000352#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000353 LAM.registerPass([&] { return CREATE_PASS; });
354#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000355
356 for (auto &C : LoopAnalysisRegistrationCallbacks)
357 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000358}
359
Chandler Carruthe3f50642016-12-22 06:59:15 +0000360FunctionPassManager
361PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000362 ThinLTOPhase Phase,
363 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000364 assert(Level != O0 && "Must request optimizations!");
365 FunctionPassManager FPM(DebugLogging);
366
367 // Form SSA out of local memory accesses after breaking apart aggregates into
368 // scalars.
369 FPM.addPass(SROA());
370
371 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000372 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000373
Davide Italianoc3688312017-06-01 23:08:14 +0000374 // Hoisting of scalars and load expressions.
375 if (EnableGVNHoist)
376 FPM.addPass(GVNHoistPass());
377
Davide Italianobe1b6a92017-06-03 23:18:29 +0000378 // Global value numbering based sinking.
379 if (EnableGVNSink) {
380 FPM.addPass(GVNSinkPass());
381 FPM.addPass(SimplifyCFGPass());
382 }
383
Chandler Carruthe3f50642016-12-22 06:59:15 +0000384 // Speculative execution if the target has divergent branches; otherwise nop.
385 FPM.addPass(SpeculativeExecutionPass());
386
387 // Optimize based on known information about branches, and cleanup afterward.
388 FPM.addPass(JumpThreadingPass());
389 FPM.addPass(CorrelatedValuePropagationPass());
390 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000391 if (Level == O3)
392 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000393 FPM.addPass(InstCombinePass());
394
395 if (!isOptimizingForSize(Level))
396 FPM.addPass(LibCallsShrinkWrapPass());
397
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000398 invokePeepholeEPCallbacks(FPM, Level);
399
Rong Xue1f42452017-10-23 22:21:29 +0000400 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
401 // using the size value profile. Don't perform this when optimizing for size.
402 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
403 !isOptimizingForSize(Level))
404 FPM.addPass(PGOMemOPSizeOpt());
405
Chandler Carruthe3f50642016-12-22 06:59:15 +0000406 FPM.addPass(TailCallElimPass());
407 FPM.addPass(SimplifyCFGPass());
408
409 // Form canonically associated expression trees, and simplify the trees using
410 // basic mathematical properties. For example, this will form (nearly)
411 // minimal multiplication trees.
412 FPM.addPass(ReassociatePass());
413
414 // Add the primary loop simplification pipeline.
415 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000416 // some function passes in between them. These can and should be removed
417 // and/or replaced by scheduling the loop pass equivalents in the correct
418 // positions. But those equivalent passes aren't powerful enough yet.
419 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
420 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
421 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
422 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000423 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
424
Chandler Carruth71fd2702018-05-30 02:46:45 +0000425 // Simplify the loop body. We do this initially to clean up after other loop
426 // passes run, either when iterating on a loop or on inner loops with
427 // implications on the outer loop.
428 LPM1.addPass(LoopInstSimplifyPass());
429 LPM1.addPass(LoopSimplifyCFGPass());
430
Chandler Carruthe3f50642016-12-22 06:59:15 +0000431 // Rotate Loop - disable header duplication at -Oz
432 LPM1.addPass(LoopRotatePass(Level != Oz));
433 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000434 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000435 LPM2.addPass(IndVarSimplifyPass());
436 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000437
438 for (auto &C : LateLoopOptimizationsEPCallbacks)
439 C(LPM2, Level);
440
Chandler Carruth79b733b2017-01-26 23:21:17 +0000441 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000442 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000443 // because it changes IR to makes profile annotation in back compile
444 // inaccurate.
Dehao Chen95f00302017-07-30 04:55:39 +0000445 if (Phase != ThinLTOPhase::PreLink ||
446 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnsonecd90132017-08-02 20:35:29 +0000447 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000448
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000449 for (auto &C : LoopOptimizerEndEPCallbacks)
450 C(LPM2, Level);
451
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000452 // We provide the opt remark emitter pass for LICM to use. We only need to do
453 // this once as it is immutable.
454 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000455 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000456 FPM.addPass(SimplifyCFGPass());
457 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000458 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000459
460 // Eliminate redundancies.
461 if (Level != O1) {
462 // These passes add substantial compile time so skip them at O1.
463 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000464 if (RunNewGVN)
465 FPM.addPass(NewGVNPass());
466 else
467 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000468 }
469
470 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
471 FPM.addPass(MemCpyOptPass());
472
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
478 // Delete dead bit computations (instcombine runs after to fold away the dead
479 // computations, and then ADCE will run later to exploit any new DCE
480 // opportunities that creates).
481 FPM.addPass(BDCEPass());
482
483 // Run instcombine after redundancy and dead bit elimination to exploit
484 // opportunities opened up by them.
485 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000486 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000487
488 // Re-consider control flow based optimizations after redundancy elimination,
489 // redo DCE, etc.
490 FPM.addPass(JumpThreadingPass());
491 FPM.addPass(CorrelatedValuePropagationPass());
492 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000493 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000494
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000495 for (auto &C : ScalarOptimizerLateEPCallbacks)
496 C(FPM, Level);
497
Chandler Carruthe3f50642016-12-22 06:59:15 +0000498 // Finally, do an expensive DCE pass to catch all the dead code exposed by
499 // the simplifications and basic cleanup after all the simplifications.
500 FPM.addPass(ADCEPass());
501 FPM.addPass(SimplifyCFGPass());
502 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000503 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000504
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000505 if (EnableCHR && Level == O3 && PGOOpt &&
506 (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty()))
507 FPM.addPass(ControlHeightReductionPass());
508
Chandler Carruthe3f50642016-12-22 06:59:15 +0000509 return FPM;
510}
511
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000512void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
513 PassBuilder::OptimizationLevel Level,
514 bool RunProfileGen,
515 std::string ProfileGenFile,
Richard Smith6c676622018-10-10 23:13:47 +0000516 std::string ProfileUseFile,
517 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000518 // Generally running simplification passes and the inliner with an high
519 // threshold results in smaller executables, but there may be cases where
520 // the size grows, so let's be conservative here and skip this simplification
521 // at -Os/Oz.
522 if (!isOptimizingForSize(Level)) {
523 InlineParams IP;
524
525 // In the old pass manager, this is a cl::opt. Should still this be one?
526 IP.DefaultThreshold = 75;
527
528 // FIXME: The hint threshold has the same value used by the regular inliner.
529 // This should probably be lowered after performance testing.
530 // FIXME: this comment is cargo culted from the old pass manager, revisit).
531 IP.HintThreshold = 325;
532
533 CGSCCPassManager CGPipeline(DebugLogging);
534
535 CGPipeline.addPass(InlinerPass(IP));
536
537 FunctionPassManager FPM;
538 FPM.addPass(SROA());
539 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
540 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
541 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000542 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000543
Davide Italiano513dfaa2017-02-13 15:26:22 +0000544 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
545
546 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
547 }
548
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000549 // Delete anything that is now dead to make sure that we don't instrument
550 // dead code. Instrumentation can end up keeping dead code around and
551 // dramatically increase code size.
552 MPM.addPass(GlobalDCEPass());
553
Davide Italiano513dfaa2017-02-13 15:26:22 +0000554 if (RunProfileGen) {
555 MPM.addPass(PGOInstrumentationGen());
556
Xinliang David Lib67530e2017-06-25 00:26:43 +0000557 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000558 FPM.addPass(
559 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000560 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
561
Davide Italiano513dfaa2017-02-13 15:26:22 +0000562 // Add the profile lowering pass.
563 InstrProfOptions Options;
564 if (!ProfileGenFile.empty())
565 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000566 Options.DoCounterPromotion = true;
Davide Italiano513dfaa2017-02-13 15:26:22 +0000567 MPM.addPass(InstrProfiling(Options));
568 }
569
570 if (!ProfileUseFile.empty())
Richard Smith6c676622018-10-10 23:13:47 +0000571 MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000572}
573
Easwaran Raman8249fac2017-06-28 13:33:49 +0000574static InlineParams
575getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
576 auto O3 = PassBuilder::O3;
577 unsigned OptLevel = Level > O3 ? 2 : Level;
578 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
579 return getInlineParams(OptLevel, SizeLevel);
580}
581
Chandler Carruthe3f50642016-12-22 06:59:15 +0000582ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000583PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000584 ThinLTOPhase Phase,
585 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000586 ModulePassManager MPM(DebugLogging);
587
Chandler Carruthe3f50642016-12-22 06:59:15 +0000588 // Do basic inference of function attributes from known properties of system
589 // libraries and other oracles.
590 MPM.addPass(InferFunctionAttrsPass());
591
592 // Create an early function pass manager to cleanup the output of the
593 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000594 FunctionPassManager EarlyFPM(DebugLogging);
595 EarlyFPM.addPass(SimplifyCFGPass());
596 EarlyFPM.addPass(SROA());
597 EarlyFPM.addPass(EarlyCSEPass());
598 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000599 if (Level == O3)
600 EarlyFPM.addPass(CallSiteSplittingPass());
601
Dehao Chen08f88312017-08-07 20:23:20 +0000602 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
603 // to convert bitcast to direct calls so that they can be inlined during the
604 // profile annotation prepration step.
605 // More details about SamplePGO design can be found in:
606 // https://research.google.com/pubs/pub45290.html
607 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
608 if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
609 Phase == ThinLTOPhase::PostLink)
610 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000611 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000612
Dehao Chen08f88312017-08-07 20:23:20 +0000613 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
614 // Annotate sample profile right after early FPM to ensure freshness of
615 // the debug info.
Dehao Chend26dae02017-10-01 05:24:51 +0000616 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000617 PGOOpt->ProfileRemappingFile,
Dehao Chend26dae02017-10-01 05:24:51 +0000618 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000619 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
620 // for the profile annotation to be accurate in the ThinLTO backend.
621 if (Phase != ThinLTOPhase::PreLink)
622 // We perform early indirect call promotion here, before globalopt.
623 // This is important for the ThinLTO backend phase because otherwise
624 // imported available_externally functions look unreferenced and are
625 // removed.
626 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
627 true));
628 }
629
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000630 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000631 // and prior to optimizing globals.
632 // FIXME: This position in the pipeline hasn't been carefully considered in
633 // years, it should be re-analyzed.
634 MPM.addPass(IPSCCPPass());
635
Matthew Simpsoncb585582017-10-25 13:40:08 +0000636 // Attach metadata to indirect call sites indicating the set of functions
637 // they may target at run-time. This should follow IPSCCP.
638 MPM.addPass(CalledValuePropagationPass());
639
Chandler Carruthe3f50642016-12-22 06:59:15 +0000640 // Optimize globals to try and fold them into constants.
641 MPM.addPass(GlobalOptPass());
642
643 // Promote any localized globals to SSA registers.
644 // FIXME: Should this instead by a run of SROA?
645 // FIXME: We should probably run instcombine and simplify-cfg afterward to
646 // delete control flows that are dead once globals have been folded to
647 // constants.
648 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
649
650 // Remove any dead arguments exposed by cleanups and constand folding
651 // globals.
652 MPM.addPass(DeadArgumentEliminationPass());
653
654 // Create a small function pass pipeline to cleanup after all the global
655 // optimizations.
656 FunctionPassManager GlobalCleanupPM(DebugLogging);
657 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000658 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
659
Chandler Carruthe3f50642016-12-22 06:59:15 +0000660 GlobalCleanupPM.addPass(SimplifyCFGPass());
661 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
662
Dehao Chen89d32262017-08-02 01:28:31 +0000663 // Add all the requested passes for instrumentation PGO, if requested.
664 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
665 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
666 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
Richard Smith6c676622018-10-10 23:13:47 +0000667 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
668 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000669 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000670 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000671
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000672 // Synthesize function entry counts for non-PGO compilation.
673 if (EnableSyntheticCounts && !PGOOpt)
674 MPM.addPass(SyntheticCountsPropagation());
675
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000676 // Require the GlobalsAA analysis for the module so we can query it within
677 // the CGSCC pipeline.
678 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000679
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000680 // Require the ProfileSummaryAnalysis for the module so we can query it within
681 // the inliner pass.
682 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
683
Chandler Carruthe3f50642016-12-22 06:59:15 +0000684 // Now begin the main postorder CGSCC pipeline.
685 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
686 // manager and trying to emulate its precise behavior. Much of this doesn't
687 // make a lot of sense and we should revisit the core CGSCC structure.
688 CGSCCPassManager MainCGPipeline(DebugLogging);
689
690 // Note: historically, the PruneEH pass was run first to deduce nounwind and
691 // generally clean up exception handling overhead. It isn't clear this is
692 // valuable as the inliner doesn't currently care whether it is inlining an
693 // invoke or a call.
694
695 // Run the inliner first. The theory is that we are walking bottom-up and so
696 // the callees have already been fully optimized, and we want to inline them
697 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000698 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000699 // because it makes profile annotation in the backend inaccurate.
700 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000701 if (Phase == ThinLTOPhase::PreLink &&
702 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000703 IP.HotCallSiteThreshold = 0;
704 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000705
706 // Now deduce any function attributes based in the current code.
707 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
708
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000709 // When at O3 add argument promotion to the pass pipeline.
710 // FIXME: It isn't at all clear why this should be limited to O3.
711 if (Level == O3)
712 MainCGPipeline.addPass(ArgumentPromotionPass());
713
Chandler Carruthe3f50642016-12-22 06:59:15 +0000714 // Lastly, add the core function simplification pipeline nested inside the
715 // CGSCC walk.
716 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000717 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000718
Teresa Johnsond7253352018-10-23 22:57:40 +0000719 // We only want to do hot cold splitting once for ThinLTO, during the
720 // post-link ThinLTO.
721 if (EnableHotColdSplit && Phase != ThinLTOPhase::PreLink)
Aditya Kumard9e2e382018-10-21 18:11:56 +0000722 MPM.addPass(HotColdSplittingPass());
723
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000724 for (auto &C : CGSCCOptimizerLateEPCallbacks)
725 C(MainCGPipeline, Level);
726
Chandler Carruth719ffe12017-02-12 05:38:04 +0000727 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
728 // to detect when we devirtualize indirect calls and iterate the SCC passes
729 // in that case to try and catch knock-on inlining or function attrs
730 // opportunities. Then we add it to the module pipeline by walking the SCCs
731 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000732 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000733 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000734 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000735
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000736 return MPM;
737}
738
739ModulePassManager
740PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
741 bool DebugLogging) {
742 ModulePassManager MPM(DebugLogging);
743
744 // Optimize globals now that the module is fully simplified.
745 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000746 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000747
Xinliang David Li126157c2017-05-22 16:41:57 +0000748 // Run partial inlining pass to partially inline functions that have
749 // large bodies.
750 if (RunPartialInlining)
751 MPM.addPass(PartialInlinerPass());
752
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000753 // Remove avail extern fns and globals definitions since we aren't compiling
754 // an object file for later LTO. For LTO we want to preserve these so they
755 // are eligible for inlining at link-time. Note if they are unreferenced they
756 // will be removed by GlobalDCE later, so this only impacts referenced
757 // available externally globals. Eventually they will be suppressed during
758 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
759 // may make globals referenced by available external functions dead and saves
760 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000761 MPM.addPass(EliminateAvailableExternallyPass());
762
763 // Do RPO function attribute inference across the module to forward-propagate
764 // attributes where applicable.
765 // FIXME: Is this really an optimization rather than a canonicalization?
766 MPM.addPass(ReversePostOrderFunctionAttrsPass());
767
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000768 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000769 // useful as the above will have inlined, DCE'ed, and function-attr
770 // propagated everything. We should at this point have a reasonably minimal
771 // and richly annotated call graph. By computing aliasing and mod/ref
772 // information for all local globals here, the late loop passes and notably
773 // the vectorizer will be able to use them to help recognize vectorizable
774 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000775 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000776
777 FunctionPassManager OptimizePM(DebugLogging);
778 OptimizePM.addPass(Float2IntPass());
779 // FIXME: We need to run some loop optimizations to re-rotate loops after
780 // simplify-cfg and others undo their rotation.
781
782 // Optimize the loop execution. These passes operate on entire loop nests
783 // rather than on each loop in an inside-out manner, and so they are actually
784 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000785
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000786 for (auto &C : VectorizerStartEPCallbacks)
787 C(OptimizePM, Level);
788
Chandler Carrutha95ff382017-01-27 00:50:21 +0000789 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000790 OptimizePM.addPass(
791 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000792
793 // Distribute loops to allow partial vectorization. I.e. isolate dependences
794 // into separate loop that would otherwise inhibit vectorization. This is
795 // currently only performed for loops marked with the metadata
796 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000797 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000798
799 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000800 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000801
Chandler Carruthbaabda92017-01-27 01:32:26 +0000802 // Eliminate loads by forwarding stores from the previous iteration to loads
803 // of the current iteration.
804 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000805
806 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000807 OptimizePM.addPass(InstCombinePass());
808
Chandler Carrutha95ff382017-01-27 00:50:21 +0000809 // Now that we've formed fast to execute loop structures, we do further
810 // optimizations. These are run afterward as they might block doing complex
811 // analyses and transforms such as what are needed for loop vectorization.
812
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000813 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
814 // GVN, loop transforms, and others have already run, so it's now better to
815 // convert to more optimized IR using more aggressive simplify CFG options.
816 // The extra sinking transform can create larger basic blocks, so do this
817 // before SLP vectorization.
818 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
819 forwardSwitchCondToPhi(true).
820 convertSwitchToLookupTable(true).
821 needCanonicalLoops(false).
822 sinkCommonInsts(true)));
823
Chandler Carruthe3f50642016-12-22 06:59:15 +0000824 // Optimize parallel scalar instruction chains into SIMD instructions.
825 OptimizePM.addPass(SLPVectorizerPass());
826
Chandler Carruthe3f50642016-12-22 06:59:15 +0000827 OptimizePM.addPass(InstCombinePass());
828
829 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000830 // execution resources of an out-of-order processor. We also then need to
831 // clean up redundancies and loop invariant code.
832 // FIXME: It would be really good to use a loop-integrated instruction
833 // combiner for cleanup here so that the unrolling and LICM can be pipelined
834 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000835 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
836 if (EnableUnrollAndJam) {
837 OptimizePM.addPass(
838 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
839 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000840 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000841 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000842 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000843 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000844 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000845
846 // Now that we've vectorized and unrolled loops, we may have more refined
847 // alignment information, try to re-derive it here.
848 OptimizePM.addPass(AlignmentFromAssumptionsPass());
849
Chandler Carrutha95ff382017-01-27 00:50:21 +0000850 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
851 // canonicalization pass that enables other optimizations. As a result,
852 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
853 // result too early.
854 OptimizePM.addPass(LoopSinkPass());
855
856 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000857 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000858
Sanjay Patel6fd43912017-09-09 13:38:18 +0000859 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
860 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
861 // flattening of blocks.
862 OptimizePM.addPass(DivRemPairsPass());
863
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000864 // LoopSink (and other loop passes since the last simplifyCFG) might have
865 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
866 OptimizePM.addPass(SimplifyCFGPass());
867
Chandler Carruthc34f7892017-11-28 11:32:31 +0000868 // Optimize PHIs by speculating around them when profitable. Note that this
869 // pass needs to be run after any PRE or similar pass as it is essentially
870 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
871 OptimizePM.addPass(SpeculateAroundPHIsPass());
872
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000873 for (auto &C : OptimizerLastEPCallbacks)
874 C(OptimizePM, Level);
875
Chandler Carrutha95ff382017-01-27 00:50:21 +0000876 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000877 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
878
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000879 MPM.addPass(CGProfilePass());
880
Chandler Carruthe3f50642016-12-22 06:59:15 +0000881 // Now we need to do some global optimization transforms.
882 // FIXME: It would seem like these should come first in the optimization
883 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
884 // ordering here.
885 MPM.addPass(GlobalDCEPass());
886 MPM.addPass(ConstantMergePass());
887
888 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000889}
890
Chandler Carruthe3f50642016-12-22 06:59:15 +0000891ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000892PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
893 bool DebugLogging) {
894 assert(Level != O0 && "Must request optimizations for the default pipeline!");
895
896 ModulePassManager MPM(DebugLogging);
897
898 // Force any function attributes we want the rest of the pipeline to observe.
899 MPM.addPass(ForceFunctionAttrsPass());
900
David Blaikie0c64f5a2018-01-23 01:25:20 +0000901 // Apply module pipeline start EP callback.
902 for (auto &C : PipelineStartEPCallbacks)
903 C(MPM);
904
Dehao Chen08f88312017-08-07 20:23:20 +0000905 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000906 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
907
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000908 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000909 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
910 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000911
912 // Now add the optimization pipeline.
913 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
914
915 return MPM;
916}
917
918ModulePassManager
919PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
920 bool DebugLogging) {
921 assert(Level != O0 && "Must request optimizations for the default pipeline!");
922
923 ModulePassManager MPM(DebugLogging);
924
925 // Force any function attributes we want the rest of the pipeline to observe.
926 MPM.addPass(ForceFunctionAttrsPass());
927
Dehao Chen08f88312017-08-07 20:23:20 +0000928 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000929 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
930
David Blaikie0c64f5a2018-01-23 01:25:20 +0000931 // Apply module pipeline start EP callback.
932 for (auto &C : PipelineStartEPCallbacks)
933 C(MPM);
934
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000935 // If we are planning to perform ThinLTO later, we don't bloat the code with
936 // unrolling/vectorization/... now. Just simplify the module as much as we
937 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000938 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
939 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000940
941 // Run partial inlining pass to partially inline functions that have
942 // large bodies.
943 // FIXME: It isn't clear whether this is really the right place to run this
944 // in ThinLTO. Because there is another canonicalization and simplification
945 // phase that will run after the thin link, running this here ends up with
946 // less information than will be available later and it may grow functions in
947 // ways that aren't beneficial.
948 if (RunPartialInlining)
949 MPM.addPass(PartialInlinerPass());
950
951 // Reduce the size of the IR as much as possible.
952 MPM.addPass(GlobalOptPass());
953
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000954 return MPM;
955}
956
Teresa Johnson28023db2018-07-19 14:51:32 +0000957ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
958 OptimizationLevel Level, bool DebugLogging,
959 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000960 ModulePassManager MPM(DebugLogging);
961
Teresa Johnson28023db2018-07-19 14:51:32 +0000962 if (ImportSummary) {
963 // These passes import type identifier resolutions for whole-program
964 // devirtualization and CFI. They must run early because other passes may
965 // disturb the specific instruction patterns that these passes look for,
966 // creating dependencies on resolutions that may not appear in the summary.
967 //
968 // For example, GVN may transform the pattern assume(type.test) appearing in
969 // two basic blocks into assume(phi(type.test, type.test)), which would
970 // transform a dependency on a WPD resolution into a dependency on a type
971 // identifier resolution for CFI.
972 //
973 // Also, WPD has access to more precise information than ICP and can
974 // devirtualize more effectively, so it should operate on the IR first.
975 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
976 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
977 }
978
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000979 // Force any function attributes we want the rest of the pipeline to observe.
980 MPM.addPass(ForceFunctionAttrsPass());
981
982 // During the ThinLTO backend phase we perform early indirect call promotion
983 // here, before globalopt. Otherwise imported available_externally functions
984 // look unreferenced and are removed.
Dehao Chen08f88312017-08-07 20:23:20 +0000985 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
986 // with SamplePGO.
Dehao Chen2f4e2e22017-08-10 05:10:32 +0000987 if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
Dehao Chen08f88312017-08-07 20:23:20 +0000988 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
989 false /* SamplePGO */));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000990
991 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000992 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
993 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000994
995 // Now add the optimization pipeline.
996 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
997
998 return MPM;
999}
1000
1001ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001002PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1003 bool DebugLogging) {
1004 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001005 // FIXME: We should use a customized pre-link pipeline!
Chandler Carruthe3f50642016-12-22 06:59:15 +00001006 return buildPerModuleDefaultPipeline(Level, DebugLogging);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001007}
1008
Teresa Johnson28023db2018-07-19 14:51:32 +00001009ModulePassManager
1010PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1011 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001012 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1013 ModulePassManager MPM(DebugLogging);
1014
Xin Tong642c8d32018-11-15 18:06:42 +00001015 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
1016 // Load sample profile before running the LTO optimization pipeline.
1017 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
1018 PGOOpt->ProfileRemappingFile,
1019 false /* ThinLTOPhase::PreLink */));
1020 }
1021
Davide Italiano089a9122017-01-24 00:57:39 +00001022 // Remove unused virtual tables to improve the quality of code generated by
1023 // whole-program devirtualization and bitset lowering.
1024 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001025
Davide Italiano089a9122017-01-24 00:57:39 +00001026 // Force any function attributes we want the rest of the pipeline to observe.
1027 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001028
Davide Italiano089a9122017-01-24 00:57:39 +00001029 // Do basic inference of function attributes from known properties of system
1030 // libraries and other oracles.
1031 MPM.addPass(InferFunctionAttrsPass());
1032
1033 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001034 FunctionPassManager EarlyFPM(DebugLogging);
1035 EarlyFPM.addPass(CallSiteSplittingPass());
1036 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1037
Davide Italiano089a9122017-01-24 00:57:39 +00001038 // Indirect call promotion. This should promote all the targets that are
1039 // left by the earlier promotion pass that promotes intra-module targets.
1040 // This two-step promotion is to save the compile time. For LTO, it should
1041 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001042 MPM.addPass(PGOIndirectCallPromotion(
1043 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +00001044 // Propagate constants at call sites into the functions they call. This
1045 // opens opportunities for globalopt (and inlining) by substituting function
1046 // pointers passed as arguments to direct uses of functions.
1047 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001048
1049 // Attach metadata to indirect call sites indicating the set of functions
1050 // they may target at run-time. This should follow IPSCCP.
1051 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001052 }
1053
1054 // Now deduce any function attributes based in the current code.
1055 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1056 PostOrderFunctionAttrsPass()));
1057
1058 // Do RPO function attribute inference across the module to forward-propagate
1059 // attributes where applicable.
1060 // FIXME: Is this really an optimization rather than a canonicalization?
1061 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1062
1063 // Use inragne annotations on GEP indices to split globals where beneficial.
1064 MPM.addPass(GlobalSplitPass());
1065
1066 // Run whole program optimization of virtual call when the list of callees
1067 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001068 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001069
1070 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001071 if (Level == 1) {
1072 // The LowerTypeTestsPass needs to run to lower type metadata and the
1073 // type.test intrinsics. The pass does nothing if CFI is disabled.
1074 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001075 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001076 }
Davide Italiano089a9122017-01-24 00:57:39 +00001077
1078 // Optimize globals to try and fold them into constants.
1079 MPM.addPass(GlobalOptPass());
1080
1081 // Promote any localized globals to SSA registers.
1082 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1083
1084 // Linking modules together can lead to duplicate global constant, only
1085 // keep one copy of each constant.
1086 MPM.addPass(ConstantMergePass());
1087
1088 // Remove unused arguments from functions.
1089 MPM.addPass(DeadArgumentEliminationPass());
1090
1091 // Reduce the code after globalopt and ipsccp. Both can open up significant
1092 // simplification opportunities, and both can propagate functions through
1093 // function pointers. When this happens, we often have to resolve varargs
1094 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001095 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001096 if (Level == O3)
1097 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001098 PeepholeFPM.addPass(InstCombinePass());
1099 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1100
1101 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001102
1103 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1104 // generally clean up exception handling overhead. It isn't clear this is
1105 // valuable as the inliner doesn't currently care whether it is inlining an
1106 // invoke or a call.
1107 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001108 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1109 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001110
1111 // Optimize globals again after we ran the inliner.
1112 MPM.addPass(GlobalOptPass());
1113
1114 // Garbage collect dead functions.
1115 // FIXME: Add ArgumentPromotion pass after once it's ported.
1116 MPM.addPass(GlobalDCEPass());
1117
1118 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001119 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001120 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001121 invokePeepholeEPCallbacks(FPM, Level);
1122
Davide Italiano089a9122017-01-24 00:57:39 +00001123 FPM.addPass(JumpThreadingPass());
1124
1125 // Break up allocas
1126 FPM.addPass(SROA());
1127
1128 // Run a few AA driver optimizations here and now to cleanup the code.
1129 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1130
1131 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1132 PostOrderFunctionAttrsPass()));
1133 // FIXME: here we run IP alias analysis in the legacy PM.
1134
1135 FunctionPassManager MainFPM;
1136
1137 // FIXME: once we fix LoopPass Manager, add LICM here.
1138 // FIXME: once we provide support for enabling MLSM, add it here.
1139 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001140 if (RunNewGVN)
1141 MainFPM.addPass(NewGVNPass());
1142 else
1143 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001144
1145 // Remove dead memcpy()'s.
1146 MainFPM.addPass(MemCpyOptPass());
1147
1148 // Nuke dead stores.
1149 MainFPM.addPass(DSEPass());
1150
1151 // FIXME: at this point, we run a bunch of loop passes:
1152 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1153 // loopVectorize. Enable them once the remaining issue with LPM
1154 // are sorted out.
1155
1156 MainFPM.addPass(InstCombinePass());
1157 MainFPM.addPass(SimplifyCFGPass());
1158 MainFPM.addPass(SCCPPass());
1159 MainFPM.addPass(InstCombinePass());
1160 MainFPM.addPass(BDCEPass());
1161
1162 // FIXME: We may want to run SLPVectorizer here.
1163 // After vectorization, assume intrinsics may tell us more
1164 // about pointer alignments.
1165#if 0
1166 MainFPM.add(AlignmentFromAssumptionsPass());
1167#endif
1168
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001169 // FIXME: Conditionally run LoadCombine here, after it's ported
1170 // (in case we still have this pass, given its questionable usefulness).
1171
Davide Italiano089a9122017-01-24 00:57:39 +00001172 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001173 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001174 MainFPM.addPass(JumpThreadingPass());
1175 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1176
1177 // Create a function that performs CFI checks for cross-DSO calls with
1178 // targets in the current module.
1179 MPM.addPass(CrossDSOCFIPass());
1180
1181 // Lower type metadata and the type.test intrinsic. This pass supports
1182 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1183 // to be run at link time if CFI is enabled. This pass does nothing if
1184 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001185 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001186
1187 // Add late LTO optimization passes.
1188 // Delete basic blocks, which optimization passes may have killed.
1189 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1190
1191 // Drop bodies of available eternally objects to improve GlobalDCE.
1192 MPM.addPass(EliminateAvailableExternallyPass());
1193
1194 // Now that we have optimized the program, discard unreachable functions.
1195 MPM.addPass(GlobalDCEPass());
1196
1197 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001198 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001199}
1200
Chandler Carruth060ad612016-12-23 20:38:19 +00001201AAManager PassBuilder::buildDefaultAAPipeline() {
1202 AAManager AA;
1203
1204 // The order in which these are registered determines their priority when
1205 // being queried.
1206
1207 // First we register the basic alias analysis that provides the majority of
1208 // per-function local AA logic. This is a stateless, on-demand local set of
1209 // AA techniques.
1210 AA.registerFunctionAnalysis<BasicAA>();
1211
1212 // Next we query fast, specialized alias analyses that wrap IR-embedded
1213 // information about aliasing.
1214 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1215 AA.registerFunctionAnalysis<TypeBasedAA>();
1216
1217 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001218 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1219 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001220 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001221 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001222
1223 return AA;
1224}
1225
Chandler Carruth241bf242016-08-03 07:44:48 +00001226static Optional<int> parseRepeatPassName(StringRef Name) {
1227 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1228 return None;
1229 int Count;
1230 if (Name.getAsInteger(0, Count) || Count <= 0)
1231 return None;
1232 return Count;
1233}
1234
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001235static Optional<int> parseDevirtPassName(StringRef Name) {
1236 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1237 return None;
1238 int Count;
1239 if (Name.getAsInteger(0, Count) || Count <= 0)
1240 return None;
1241 return Count;
1242}
1243
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001244/// Tests whether a pass name starts with a valid prefix for a default pipeline
1245/// alias.
1246static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1247 return Name.startswith("default") || Name.startswith("thinlto") ||
1248 Name.startswith("lto");
1249}
1250
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001251/// Tests whether registered callbacks will accept a given pass name.
1252///
1253/// When parsing a pipeline text, the type of the outermost pipeline may be
1254/// omitted, in which case the type is automatically determined from the first
1255/// pass name in the text. This may be a name that is handled through one of the
1256/// callbacks. We check this through the oridinary parsing callbacks by setting
1257/// up a dummy PassManager in order to not force the client to also handle this
1258/// type of query.
1259template <typename PassManagerT, typename CallbacksT>
1260static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1261 if (!Callbacks.empty()) {
1262 PassManagerT DummyPM;
1263 for (auto &CB : Callbacks)
1264 if (CB(Name, DummyPM, {}))
1265 return true;
1266 }
1267 return false;
1268}
1269
1270template <typename CallbacksT>
1271static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001272 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001273 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001274 return DefaultAliasRegex.match(Name);
1275
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001276 // Explicitly handle pass manager names.
1277 if (Name == "module")
1278 return true;
1279 if (Name == "cgscc")
1280 return true;
1281 if (Name == "function")
1282 return true;
1283
Chandler Carruth241bf242016-08-03 07:44:48 +00001284 // Explicitly handle custom-parsed pass names.
1285 if (parseRepeatPassName(Name))
1286 return true;
1287
Chandler Carruth74a8a222016-06-17 07:15:29 +00001288#define MODULE_PASS(NAME, CREATE_PASS) \
1289 if (Name == NAME) \
1290 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001291#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001292 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001293 return true;
1294#include "PassRegistry.def"
1295
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001296 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001297}
1298
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001299template <typename CallbacksT>
1300static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001301 // Explicitly handle pass manager names.
1302 if (Name == "cgscc")
1303 return true;
1304 if (Name == "function")
1305 return true;
1306
Chandler Carruth241bf242016-08-03 07:44:48 +00001307 // Explicitly handle custom-parsed pass names.
1308 if (parseRepeatPassName(Name))
1309 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001310 if (parseDevirtPassName(Name))
1311 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001312
Chandler Carruth74a8a222016-06-17 07:15:29 +00001313#define CGSCC_PASS(NAME, CREATE_PASS) \
1314 if (Name == NAME) \
1315 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001316#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001317 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001318 return true;
1319#include "PassRegistry.def"
1320
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001321 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001322}
1323
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001324template <typename CallbacksT>
1325static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001326 // Explicitly handle pass manager names.
1327 if (Name == "function")
1328 return true;
1329 if (Name == "loop")
1330 return true;
1331
Chandler Carruth241bf242016-08-03 07:44:48 +00001332 // Explicitly handle custom-parsed pass names.
1333 if (parseRepeatPassName(Name))
1334 return true;
1335
Chandler Carruth74a8a222016-06-17 07:15:29 +00001336#define FUNCTION_PASS(NAME, CREATE_PASS) \
1337 if (Name == NAME) \
1338 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001339#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001340 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001341 return true;
1342#include "PassRegistry.def"
1343
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001344 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001345}
1346
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001347template <typename CallbacksT>
1348static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001349 // Explicitly handle pass manager names.
1350 if (Name == "loop")
1351 return true;
1352
Chandler Carruth241bf242016-08-03 07:44:48 +00001353 // Explicitly handle custom-parsed pass names.
1354 if (parseRepeatPassName(Name))
1355 return true;
1356
Chandler Carruth74a8a222016-06-17 07:15:29 +00001357#define LOOP_PASS(NAME, CREATE_PASS) \
1358 if (Name == NAME) \
1359 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001360#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1361 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1362 return true;
1363#include "PassRegistry.def"
1364
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001365 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001366}
1367
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001368Optional<std::vector<PassBuilder::PipelineElement>>
1369PassBuilder::parsePipelineText(StringRef Text) {
1370 std::vector<PipelineElement> ResultPipeline;
1371
1372 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1373 &ResultPipeline};
1374 for (;;) {
1375 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1376 size_t Pos = Text.find_first_of(",()");
1377 Pipeline.push_back({Text.substr(0, Pos), {}});
1378
1379 // If we have a single terminating name, we're done.
1380 if (Pos == Text.npos)
1381 break;
1382
1383 char Sep = Text[Pos];
1384 Text = Text.substr(Pos + 1);
1385 if (Sep == ',')
1386 // Just a name ending in a comma, continue.
1387 continue;
1388
1389 if (Sep == '(') {
1390 // Push the inner pipeline onto the stack to continue processing.
1391 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1392 continue;
1393 }
1394
1395 assert(Sep == ')' && "Bogus separator!");
1396 // When handling the close parenthesis, we greedily consume them to avoid
1397 // empty strings in the pipeline.
1398 do {
1399 // If we try to pop the outer pipeline we have unbalanced parentheses.
1400 if (PipelineStack.size() == 1)
1401 return None;
1402
1403 PipelineStack.pop_back();
1404 } while (Text.consume_front(")"));
1405
1406 // Check if we've finished parsing.
1407 if (Text.empty())
1408 break;
1409
1410 // Otherwise, the end of an inner pipeline always has to be followed by
1411 // a comma, and then we can continue.
1412 if (!Text.consume_front(","))
1413 return None;
1414 }
1415
1416 if (PipelineStack.size() > 1)
1417 // Unbalanced paretheses.
1418 return None;
1419
1420 assert(PipelineStack.back() == &ResultPipeline &&
1421 "Wrong pipeline at the bottom of the stack!");
1422 return {std::move(ResultPipeline)};
1423}
1424
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001425Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1426 const PipelineElement &E,
1427 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001428 auto &Name = E.Name;
1429 auto &InnerPipeline = E.InnerPipeline;
1430
1431 // First handle complex passes like the pass managers which carry pipelines.
1432 if (!InnerPipeline.empty()) {
1433 if (Name == "module") {
1434 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001435 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1436 VerifyEachPass, DebugLogging))
1437 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001438 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001439 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001440 }
1441 if (Name == "cgscc") {
1442 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001443 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1444 DebugLogging))
1445 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001446 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001447 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001448 }
1449 if (Name == "function") {
1450 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001451 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1452 VerifyEachPass, DebugLogging))
1453 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001454 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001455 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001456 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001457 if (auto Count = parseRepeatPassName(Name)) {
1458 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001459 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1460 VerifyEachPass, DebugLogging))
1461 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001462 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001463 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001464 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001465
1466 for (auto &C : ModulePipelineParsingCallbacks)
1467 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001468 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001469
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001470 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001471 return make_error<StringError>(
1472 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1473 inconvertibleErrorCode());
1474 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001475 }
1476
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001477 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001478 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001479 SmallVector<StringRef, 3> Matches;
1480 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001481 return make_error<StringError>(
1482 formatv("unknown default pipeline alias '{0}'", Name).str(),
1483 inconvertibleErrorCode());
1484
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001485 assert(Matches.size() == 3 && "Must capture two matched strings!");
1486
Jordan Rosef85a95f2016-07-25 18:34:51 +00001487 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001488 .Case("O0", O0)
1489 .Case("O1", O1)
1490 .Case("O2", O2)
1491 .Case("O3", O3)
1492 .Case("Os", Os)
1493 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001494 if (L == O0)
1495 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001496 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001497
1498 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001499 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001500 } else if (Matches[1] == "thinlto-pre-link") {
1501 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1502 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001503 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001504 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001505 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001506 } else {
1507 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001508 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001509 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001510 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001511 }
1512
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001513 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001514#define MODULE_PASS(NAME, CREATE_PASS) \
1515 if (Name == NAME) { \
1516 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001517 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001518 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001519#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1520 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001521 MPM.addPass( \
1522 RequireAnalysisPass< \
1523 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001524 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001525 } \
1526 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001527 MPM.addPass(InvalidateAnalysisPass< \
1528 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001529 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001530 }
1531#include "PassRegistry.def"
1532
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001533 for (auto &C : ModulePipelineParsingCallbacks)
1534 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001535 return Error::success();
1536 return make_error<StringError>(
1537 formatv("unknown module pass '{0}'", Name).str(),
1538 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001539}
1540
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001541Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1542 const PipelineElement &E, bool VerifyEachPass,
1543 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001544 auto &Name = E.Name;
1545 auto &InnerPipeline = E.InnerPipeline;
1546
1547 // First handle complex passes like the pass managers which carry pipelines.
1548 if (!InnerPipeline.empty()) {
1549 if (Name == "cgscc") {
1550 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001551 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1552 VerifyEachPass, DebugLogging))
1553 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001554 // Add the nested pass manager with the appropriate adaptor.
1555 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001556 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001557 }
1558 if (Name == "function") {
1559 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001560 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1561 VerifyEachPass, DebugLogging))
1562 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001563 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001564 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001565 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001566 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001567 if (auto Count = parseRepeatPassName(Name)) {
1568 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001569 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1570 VerifyEachPass, DebugLogging))
1571 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001572 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001573 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001574 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001575 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1576 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001577 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1578 VerifyEachPass, DebugLogging))
1579 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001580 CGPM.addPass(
1581 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001582 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001583 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001584
1585 for (auto &C : CGSCCPipelineParsingCallbacks)
1586 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001587 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001588
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001589 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001590 return make_error<StringError>(
1591 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1592 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001593 }
1594
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001595// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001596#define CGSCC_PASS(NAME, CREATE_PASS) \
1597 if (Name == NAME) { \
1598 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001599 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001600 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001601#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1602 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001603 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001604 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001605 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1606 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001607 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001608 } \
1609 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001610 CGPM.addPass(InvalidateAnalysisPass< \
1611 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001612 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001613 }
1614#include "PassRegistry.def"
1615
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001616 for (auto &C : CGSCCPipelineParsingCallbacks)
1617 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001618 return Error::success();
1619 return make_error<StringError>(
1620 formatv("unknown cgscc pass '{0}'", Name).str(),
1621 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001622}
1623
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001624Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1625 const PipelineElement &E,
1626 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001627 auto &Name = E.Name;
1628 auto &InnerPipeline = E.InnerPipeline;
1629
1630 // First handle complex passes like the pass managers which carry pipelines.
1631 if (!InnerPipeline.empty()) {
1632 if (Name == "function") {
1633 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001634 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1635 VerifyEachPass, DebugLogging))
1636 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001637 // Add the nested pass manager with the appropriate adaptor.
1638 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001639 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001640 }
1641 if (Name == "loop") {
1642 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001643 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1644 DebugLogging))
1645 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001646 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001647 FPM.addPass(
1648 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001649 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001650 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001651 if (auto Count = parseRepeatPassName(Name)) {
1652 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001653 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1654 VerifyEachPass, DebugLogging))
1655 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001656 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001657 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001658 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001659
1660 for (auto &C : FunctionPipelineParsingCallbacks)
1661 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001662 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001663
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001664 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001665 return make_error<StringError>(
1666 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1667 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001668 }
1669
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001670// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001671#define FUNCTION_PASS(NAME, CREATE_PASS) \
1672 if (Name == NAME) { \
1673 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001674 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001675 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001676#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1677 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001678 FPM.addPass( \
1679 RequireAnalysisPass< \
1680 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001681 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001682 } \
1683 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001684 FPM.addPass(InvalidateAnalysisPass< \
1685 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001686 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001687 }
1688#include "PassRegistry.def"
1689
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001690 for (auto &C : FunctionPipelineParsingCallbacks)
1691 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001692 return Error::success();
1693 return make_error<StringError>(
1694 formatv("unknown function pass '{0}'", Name).str(),
1695 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001696}
1697
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001698Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1699 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001700 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001701 auto &InnerPipeline = E.InnerPipeline;
1702
1703 // First handle complex passes like the pass managers which carry pipelines.
1704 if (!InnerPipeline.empty()) {
1705 if (Name == "loop") {
1706 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001707 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1708 VerifyEachPass, DebugLogging))
1709 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001710 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001711 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001712 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001713 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001714 if (auto Count = parseRepeatPassName(Name)) {
1715 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001716 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1717 VerifyEachPass, DebugLogging))
1718 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001719 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001720 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001721 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001722
1723 for (auto &C : LoopPipelineParsingCallbacks)
1724 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001725 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001726
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001727 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001728 return make_error<StringError>(
1729 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1730 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001731 }
1732
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001733// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001734#define LOOP_PASS(NAME, CREATE_PASS) \
1735 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001736 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001737 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001738 }
1739#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1740 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001741 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001742 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1743 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1744 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001745 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001746 } \
1747 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001748 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001749 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001750 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001751 }
1752#include "PassRegistry.def"
1753
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001754 for (auto &C : LoopPipelineParsingCallbacks)
1755 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001756 return Error::success();
1757 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1758 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001759}
1760
Chandler Carruthedf59962016-02-18 09:45:17 +00001761bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001762#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1763 if (Name == NAME) { \
1764 AA.registerModuleAnalysis< \
1765 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1766 return true; \
1767 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001768#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1769 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001770 AA.registerFunctionAnalysis< \
1771 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001772 return true; \
1773 }
1774#include "PassRegistry.def"
1775
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001776 for (auto &C : AAParsingCallbacks)
1777 if (C(Name, AA))
1778 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001779 return false;
1780}
1781
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001782Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001783 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001784 bool VerifyEachPass,
1785 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001786 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001787 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1788 return Err;
1789 // FIXME: No verifier support for Loop passes!
1790 }
1791 return Error::success();
1792}
1793
1794Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1795 ArrayRef<PipelineElement> Pipeline,
1796 bool VerifyEachPass,
1797 bool DebugLogging) {
1798 for (const auto &Element : Pipeline) {
1799 if (auto Err =
1800 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1801 return Err;
1802 if (VerifyEachPass)
1803 FPM.addPass(VerifierPass());
1804 }
1805 return Error::success();
1806}
1807
1808Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1809 ArrayRef<PipelineElement> Pipeline,
1810 bool VerifyEachPass,
1811 bool DebugLogging) {
1812 for (const auto &Element : Pipeline) {
1813 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1814 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001815 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001816 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001817 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00001818}
1819
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001820void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1821 FunctionAnalysisManager &FAM,
1822 CGSCCAnalysisManager &CGAM,
1823 ModuleAnalysisManager &MAM) {
1824 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1825 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001826 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1827 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1828 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1829 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1830 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1831}
1832
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001833Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1834 ArrayRef<PipelineElement> Pipeline,
1835 bool VerifyEachPass,
1836 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001837 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001838 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1839 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001840 if (VerifyEachPass)
1841 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001842 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001843 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001844}
1845
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001846// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00001847// FIXME: Should this routine accept a TargetMachine or require the caller to
1848// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001849Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1850 StringRef PipelineText,
1851 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001852 auto Pipeline = parsePipelineText(PipelineText);
1853 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001854 return make_error<StringError>(
1855 formatv("invalid pipeline '{0}'", PipelineText).str(),
1856 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001857
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001858 // If the first name isn't at the module layer, wrap the pipeline up
1859 // automatically.
1860 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00001861
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001862 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1863 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001864 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001865 } else if (isFunctionPassName(FirstName,
1866 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001867 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001868 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001869 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001870 } else {
1871 for (auto &C : TopLevelPipelineParsingCallbacks)
1872 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001873 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001874
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001875 // Unknown pass or pipeline name!
1876 auto &InnerPipeline = Pipeline->front().InnerPipeline;
1877 return make_error<StringError>(
1878 formatv("unknown {0} name '{1}'",
1879 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1880 .str(),
1881 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001882 }
Chandler Carruth572e3402014-04-21 11:12:00 +00001883 }
1884
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001885 if (auto Err =
1886 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1887 return Err;
1888 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001889}
Chandler Carruthedf59962016-02-18 09:45:17 +00001890
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001891// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001892Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1893 StringRef PipelineText,
1894 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001895 auto Pipeline = parsePipelineText(PipelineText);
1896 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001897 return make_error<StringError>(
1898 formatv("invalid pipeline '{0}'", PipelineText).str(),
1899 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001900
1901 StringRef FirstName = Pipeline->front().Name;
1902 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001903 return make_error<StringError>(
1904 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
1905 PipelineText)
1906 .str(),
1907 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001908
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001909 if (auto Err =
1910 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
1911 return Err;
1912 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001913}
1914
1915// Primary pass pipeline description parsing routine for a \c
1916// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001917Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
1918 StringRef PipelineText,
1919 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001920 auto Pipeline = parsePipelineText(PipelineText);
1921 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001922 return make_error<StringError>(
1923 formatv("invalid pipeline '{0}'", PipelineText).str(),
1924 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001925
1926 StringRef FirstName = Pipeline->front().Name;
1927 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001928 return make_error<StringError>(
1929 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
1930 PipelineText)
1931 .str(),
1932 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001933
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001934 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
1935 DebugLogging))
1936 return Err;
1937 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001938}
1939
1940// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001941Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
1942 StringRef PipelineText,
1943 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001944 auto Pipeline = parsePipelineText(PipelineText);
1945 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001946 return make_error<StringError>(
1947 formatv("invalid pipeline '{0}'", PipelineText).str(),
1948 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001949
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001950 if (auto Err =
1951 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
1952 return Err;
1953
1954 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001955}
1956
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001957Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00001958 // If the pipeline just consists of the word 'default' just replace the AA
1959 // manager with our default one.
1960 if (PipelineText == "default") {
1961 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001962 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00001963 }
1964
Chandler Carruthedf59962016-02-18 09:45:17 +00001965 while (!PipelineText.empty()) {
1966 StringRef Name;
1967 std::tie(Name, PipelineText) = PipelineText.split(',');
1968 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001969 return make_error<StringError>(
1970 formatv("unknown alias analysis name '{0}'", Name).str(),
1971 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00001972 }
1973
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001974 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00001975}