blob: 33f74cfd9ed80f16d3f752e3fe72365881ffdee1 [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"
Chandler Carruth8ca43222015-01-15 11:39:46 +000051#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000052#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000053#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000054#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000055#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000056#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000057#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000058#include "llvm/IR/PassManager.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000059#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000060#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000061#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000062#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000063#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000064#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Leonard Chaneebecb32018-10-26 22:51:51 +000065#include "llvm/Transforms/Instrumentation/CGProfile.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"
Chandler Carruth00a301d2017-11-14 01:30:04 +000091#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000092#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000093#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
94#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +000095#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Justin Bogner19b67992015-10-30 23:13:18 +000096#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +000097#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +000098#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +000099#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000100#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000101#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000102#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000103#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000104#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000105#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000106#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000107#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000108#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000109#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000110#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000111#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000112#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000113#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000114#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000115#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000116#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000117#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000118#include "llvm/Transforms/Scalar/LoopDistribute.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000119#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000120#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000121#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000122#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000123#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000124#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000125#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000126#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000127#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000128#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000129#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000130#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000131#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000132#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Sean Silva6347df02016-06-14 02:44:55 +0000133#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000134#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000135#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000136#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000137#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000138#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000139#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000140#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000141#include "llvm/Transforms/Scalar/SROA.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000142#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000143#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000144#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000145#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000146#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000147#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000148#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000149#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000150#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000151#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000152#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000153#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000154#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000155#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000156#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000157#include "llvm/Transforms/Utils/SymbolRewriter.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000158#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000159#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000160
Chandler Carruth66445382014-01-11 08:16:35 +0000161using namespace llvm;
162
Chandler Carruth719ffe12017-02-12 05:38:04 +0000163static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
164 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000165static cl::opt<bool>
166 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
167 cl::Hidden, cl::ZeroOrMore,
168 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000169
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000170static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000171 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000172 cl::Hidden, cl::ZeroOrMore,
173 cl::desc("Run NewGVN instead of GVN"));
174
Geoff Berry3cca1da2017-06-10 15:20:03 +0000175static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000176 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
177 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000178
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000179static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000180 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
181 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000182
Davide Italianobe1b6a92017-06-03 23:18:29 +0000183static cl::opt<bool> EnableGVNSink(
184 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
185 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
186
David Green963401d2018-07-01 12:47:30 +0000187static cl::opt<bool> EnableUnrollAndJam(
188 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
189 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
190
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000191static cl::opt<bool> EnableSyntheticCounts(
192 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
193 cl::desc("Run synthetic function entry count generation "
194 "pass"));
195
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000196static Regex DefaultAliasRegex(
197 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000198
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000199static cl::opt<bool>
200 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
201 cl::desc("Enable control height reduction optimization (CHR)"));
202
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000203extern cl::opt<bool> EnableHotColdSplit;
204
Chandler Carruthe3f50642016-12-22 06:59:15 +0000205static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
206 switch (Level) {
207 case PassBuilder::O0:
208 case PassBuilder::O1:
209 case PassBuilder::O2:
210 case PassBuilder::O3:
211 return false;
212
213 case PassBuilder::Os:
214 case PassBuilder::Oz:
215 return true;
216 }
217 llvm_unreachable("Invalid optimization level!");
218}
219
Chandler Carruth66445382014-01-11 08:16:35 +0000220namespace {
221
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000222/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000223struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000224 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000225 return PreservedAnalyses::all();
226 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000227 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000228};
229
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000230/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000231class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
232 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000233 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000234
235public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000236 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000237 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000238 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000239};
240
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000241/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000242struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000243 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
244 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000245 return PreservedAnalyses::all();
246 }
247 static StringRef name() { return "NoOpCGSCCPass"; }
248};
249
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000250/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000251class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
252 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000253 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000254
255public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000256 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000257 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000258 return Result();
259 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000260 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000261};
262
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000263/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000264struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000265 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000266 return PreservedAnalyses::all();
267 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000268 static StringRef name() { return "NoOpFunctionPass"; }
269};
270
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000271/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000272class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
273 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000274 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000275
276public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000277 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000278 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000279 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000280};
281
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000282/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000283struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000284 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
285 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000286 return PreservedAnalyses::all();
287 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000288 static StringRef name() { return "NoOpLoopPass"; }
289};
290
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000291/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000292class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
293 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000294 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000295
296public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000297 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000298 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
299 return Result();
300 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000301 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000302};
303
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000304AnalysisKey NoOpModuleAnalysis::Key;
305AnalysisKey NoOpCGSCCAnalysis::Key;
306AnalysisKey NoOpFunctionAnalysis::Key;
307AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000308
Chandler Carruth66445382014-01-11 08:16:35 +0000309} // End anonymous namespace.
310
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000311void PassBuilder::invokePeepholeEPCallbacks(
312 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
313 for (auto &C : PeepholeEPCallbacks)
314 C(FPM, Level);
315}
316
Chandler Carruth1ff77242015-03-07 09:02:36 +0000317void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000318#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000319 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000320#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000321
322 for (auto &C : ModuleAnalysisRegistrationCallbacks)
323 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000324}
325
Chandler Carruth1ff77242015-03-07 09:02:36 +0000326void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000327#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000328 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000329#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000330
331 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
332 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000333}
334
Chandler Carruth1ff77242015-03-07 09:02:36 +0000335void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000336#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000337 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000338#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000339
340 for (auto &C : FunctionAnalysisRegistrationCallbacks)
341 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000342}
343
Justin Bognereecc3c82016-02-25 07:23:08 +0000344void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000345#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000346 LAM.registerPass([&] { return CREATE_PASS; });
347#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000348
349 for (auto &C : LoopAnalysisRegistrationCallbacks)
350 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000351}
352
Chandler Carruthe3f50642016-12-22 06:59:15 +0000353FunctionPassManager
354PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000355 ThinLTOPhase Phase,
356 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000357 assert(Level != O0 && "Must request optimizations!");
358 FunctionPassManager FPM(DebugLogging);
359
360 // Form SSA out of local memory accesses after breaking apart aggregates into
361 // scalars.
362 FPM.addPass(SROA());
363
364 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000365 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000366
Davide Italianoc3688312017-06-01 23:08:14 +0000367 // Hoisting of scalars and load expressions.
368 if (EnableGVNHoist)
369 FPM.addPass(GVNHoistPass());
370
Davide Italianobe1b6a92017-06-03 23:18:29 +0000371 // Global value numbering based sinking.
372 if (EnableGVNSink) {
373 FPM.addPass(GVNSinkPass());
374 FPM.addPass(SimplifyCFGPass());
375 }
376
Chandler Carruthe3f50642016-12-22 06:59:15 +0000377 // Speculative execution if the target has divergent branches; otherwise nop.
378 FPM.addPass(SpeculativeExecutionPass());
379
380 // Optimize based on known information about branches, and cleanup afterward.
381 FPM.addPass(JumpThreadingPass());
382 FPM.addPass(CorrelatedValuePropagationPass());
383 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000384 if (Level == O3)
385 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000386 FPM.addPass(InstCombinePass());
387
388 if (!isOptimizingForSize(Level))
389 FPM.addPass(LibCallsShrinkWrapPass());
390
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000391 invokePeepholeEPCallbacks(FPM, Level);
392
Rong Xue1f42452017-10-23 22:21:29 +0000393 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
394 // using the size value profile. Don't perform this when optimizing for size.
395 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
396 !isOptimizingForSize(Level))
397 FPM.addPass(PGOMemOPSizeOpt());
398
Chandler Carruthe3f50642016-12-22 06:59:15 +0000399 FPM.addPass(TailCallElimPass());
400 FPM.addPass(SimplifyCFGPass());
401
402 // Form canonically associated expression trees, and simplify the trees using
403 // basic mathematical properties. For example, this will form (nearly)
404 // minimal multiplication trees.
405 FPM.addPass(ReassociatePass());
406
407 // Add the primary loop simplification pipeline.
408 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000409 // some function passes in between them. These can and should be removed
410 // and/or replaced by scheduling the loop pass equivalents in the correct
411 // positions. But those equivalent passes aren't powerful enough yet.
412 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
413 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
414 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
415 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000416 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
417
Chandler Carruth71fd2702018-05-30 02:46:45 +0000418 // Simplify the loop body. We do this initially to clean up after other loop
419 // passes run, either when iterating on a loop or on inner loops with
420 // implications on the outer loop.
421 LPM1.addPass(LoopInstSimplifyPass());
422 LPM1.addPass(LoopSimplifyCFGPass());
423
Chandler Carruthe3f50642016-12-22 06:59:15 +0000424 // Rotate Loop - disable header duplication at -Oz
425 LPM1.addPass(LoopRotatePass(Level != Oz));
426 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000427 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000428 LPM2.addPass(IndVarSimplifyPass());
429 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000430
431 for (auto &C : LateLoopOptimizationsEPCallbacks)
432 C(LPM2, Level);
433
Chandler Carruth79b733b2017-01-26 23:21:17 +0000434 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000435 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000436 // because it changes IR to makes profile annotation in back compile
437 // inaccurate.
Dehao Chen95f00302017-07-30 04:55:39 +0000438 if (Phase != ThinLTOPhase::PreLink ||
439 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnsonecd90132017-08-02 20:35:29 +0000440 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000441
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000442 for (auto &C : LoopOptimizerEndEPCallbacks)
443 C(LPM2, Level);
444
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000445 // We provide the opt remark emitter pass for LICM to use. We only need to do
446 // this once as it is immutable.
447 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000448 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000449 FPM.addPass(SimplifyCFGPass());
450 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000451 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000452
453 // Eliminate redundancies.
454 if (Level != O1) {
455 // These passes add substantial compile time so skip them at O1.
456 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000457 if (RunNewGVN)
458 FPM.addPass(NewGVNPass());
459 else
460 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000461 }
462
463 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
464 FPM.addPass(MemCpyOptPass());
465
466 // Sparse conditional constant propagation.
467 // FIXME: It isn't clear why we do this *after* loop passes rather than
468 // before...
469 FPM.addPass(SCCPPass());
470
471 // Delete dead bit computations (instcombine runs after to fold away the dead
472 // computations, and then ADCE will run later to exploit any new DCE
473 // opportunities that creates).
474 FPM.addPass(BDCEPass());
475
476 // Run instcombine after redundancy and dead bit elimination to exploit
477 // opportunities opened up by them.
478 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000479 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000480
481 // Re-consider control flow based optimizations after redundancy elimination,
482 // redo DCE, etc.
483 FPM.addPass(JumpThreadingPass());
484 FPM.addPass(CorrelatedValuePropagationPass());
485 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000486 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000487
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000488 for (auto &C : ScalarOptimizerLateEPCallbacks)
489 C(FPM, Level);
490
Chandler Carruthe3f50642016-12-22 06:59:15 +0000491 // Finally, do an expensive DCE pass to catch all the dead code exposed by
492 // the simplifications and basic cleanup after all the simplifications.
493 FPM.addPass(ADCEPass());
494 FPM.addPass(SimplifyCFGPass());
495 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000496 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000497
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000498 if (EnableCHR && Level == O3 && PGOOpt &&
499 (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty()))
500 FPM.addPass(ControlHeightReductionPass());
501
Chandler Carruthe3f50642016-12-22 06:59:15 +0000502 return FPM;
503}
504
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000505void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
506 PassBuilder::OptimizationLevel Level,
507 bool RunProfileGen,
508 std::string ProfileGenFile,
Richard Smith6c676622018-10-10 23:13:47 +0000509 std::string ProfileUseFile,
510 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000511 // Generally running simplification passes and the inliner with an high
512 // threshold results in smaller executables, but there may be cases where
513 // the size grows, so let's be conservative here and skip this simplification
514 // at -Os/Oz.
515 if (!isOptimizingForSize(Level)) {
516 InlineParams IP;
517
518 // In the old pass manager, this is a cl::opt. Should still this be one?
519 IP.DefaultThreshold = 75;
520
521 // FIXME: The hint threshold has the same value used by the regular inliner.
522 // This should probably be lowered after performance testing.
523 // FIXME: this comment is cargo culted from the old pass manager, revisit).
524 IP.HintThreshold = 325;
525
526 CGSCCPassManager CGPipeline(DebugLogging);
527
528 CGPipeline.addPass(InlinerPass(IP));
529
530 FunctionPassManager FPM;
531 FPM.addPass(SROA());
532 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
533 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
534 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000535 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000536
Davide Italiano513dfaa2017-02-13 15:26:22 +0000537 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
538
539 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
540 }
541
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000542 // Delete anything that is now dead to make sure that we don't instrument
543 // dead code. Instrumentation can end up keeping dead code around and
544 // dramatically increase code size.
545 MPM.addPass(GlobalDCEPass());
546
Davide Italiano513dfaa2017-02-13 15:26:22 +0000547 if (RunProfileGen) {
548 MPM.addPass(PGOInstrumentationGen());
549
Xinliang David Lib67530e2017-06-25 00:26:43 +0000550 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000551 FPM.addPass(
552 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000553 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
554
Davide Italiano513dfaa2017-02-13 15:26:22 +0000555 // Add the profile lowering pass.
556 InstrProfOptions Options;
557 if (!ProfileGenFile.empty())
558 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000559 Options.DoCounterPromotion = true;
Davide Italiano513dfaa2017-02-13 15:26:22 +0000560 MPM.addPass(InstrProfiling(Options));
561 }
562
563 if (!ProfileUseFile.empty())
Richard Smith6c676622018-10-10 23:13:47 +0000564 MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000565}
566
Easwaran Raman8249fac2017-06-28 13:33:49 +0000567static InlineParams
568getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
569 auto O3 = PassBuilder::O3;
570 unsigned OptLevel = Level > O3 ? 2 : Level;
571 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
572 return getInlineParams(OptLevel, SizeLevel);
573}
574
Chandler Carruthe3f50642016-12-22 06:59:15 +0000575ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000576PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000577 ThinLTOPhase Phase,
578 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000579 ModulePassManager MPM(DebugLogging);
580
Chandler Carruthe3f50642016-12-22 06:59:15 +0000581 // Do basic inference of function attributes from known properties of system
582 // libraries and other oracles.
583 MPM.addPass(InferFunctionAttrsPass());
584
585 // Create an early function pass manager to cleanup the output of the
586 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000587 FunctionPassManager EarlyFPM(DebugLogging);
588 EarlyFPM.addPass(SimplifyCFGPass());
589 EarlyFPM.addPass(SROA());
590 EarlyFPM.addPass(EarlyCSEPass());
591 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000592 if (Level == O3)
593 EarlyFPM.addPass(CallSiteSplittingPass());
594
Dehao Chen08f88312017-08-07 20:23:20 +0000595 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
596 // to convert bitcast to direct calls so that they can be inlined during the
597 // profile annotation prepration step.
598 // More details about SamplePGO design can be found in:
599 // https://research.google.com/pubs/pub45290.html
600 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
601 if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
602 Phase == ThinLTOPhase::PostLink)
603 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000604 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000605
Dehao Chen08f88312017-08-07 20:23:20 +0000606 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
607 // Annotate sample profile right after early FPM to ensure freshness of
608 // the debug info.
Dehao Chend26dae02017-10-01 05:24:51 +0000609 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000610 PGOOpt->ProfileRemappingFile,
Dehao Chend26dae02017-10-01 05:24:51 +0000611 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000612 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
613 // for the profile annotation to be accurate in the ThinLTO backend.
614 if (Phase != ThinLTOPhase::PreLink)
615 // We perform early indirect call promotion here, before globalopt.
616 // This is important for the ThinLTO backend phase because otherwise
617 // imported available_externally functions look unreferenced and are
618 // removed.
619 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
620 true));
621 }
622
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000623 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000624 // and prior to optimizing globals.
625 // FIXME: This position in the pipeline hasn't been carefully considered in
626 // years, it should be re-analyzed.
627 MPM.addPass(IPSCCPPass());
628
Matthew Simpsoncb585582017-10-25 13:40:08 +0000629 // Attach metadata to indirect call sites indicating the set of functions
630 // they may target at run-time. This should follow IPSCCP.
631 MPM.addPass(CalledValuePropagationPass());
632
Chandler Carruthe3f50642016-12-22 06:59:15 +0000633 // Optimize globals to try and fold them into constants.
634 MPM.addPass(GlobalOptPass());
635
636 // Promote any localized globals to SSA registers.
637 // FIXME: Should this instead by a run of SROA?
638 // FIXME: We should probably run instcombine and simplify-cfg afterward to
639 // delete control flows that are dead once globals have been folded to
640 // constants.
641 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
642
643 // Remove any dead arguments exposed by cleanups and constand folding
644 // globals.
645 MPM.addPass(DeadArgumentEliminationPass());
646
647 // Create a small function pass pipeline to cleanup after all the global
648 // optimizations.
649 FunctionPassManager GlobalCleanupPM(DebugLogging);
650 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000651 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
652
Chandler Carruthe3f50642016-12-22 06:59:15 +0000653 GlobalCleanupPM.addPass(SimplifyCFGPass());
654 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
655
Dehao Chen89d32262017-08-02 01:28:31 +0000656 // Add all the requested passes for instrumentation PGO, if requested.
657 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
658 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
659 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
Richard Smith6c676622018-10-10 23:13:47 +0000660 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
661 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000662 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000663 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000664
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000665 // Synthesize function entry counts for non-PGO compilation.
666 if (EnableSyntheticCounts && !PGOOpt)
667 MPM.addPass(SyntheticCountsPropagation());
668
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000669 // Require the GlobalsAA analysis for the module so we can query it within
670 // the CGSCC pipeline.
671 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000672
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000673 // Require the ProfileSummaryAnalysis for the module so we can query it within
674 // the inliner pass.
675 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
676
Chandler Carruthe3f50642016-12-22 06:59:15 +0000677 // Now begin the main postorder CGSCC pipeline.
678 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
679 // manager and trying to emulate its precise behavior. Much of this doesn't
680 // make a lot of sense and we should revisit the core CGSCC structure.
681 CGSCCPassManager MainCGPipeline(DebugLogging);
682
683 // Note: historically, the PruneEH pass was run first to deduce nounwind and
684 // generally clean up exception handling overhead. It isn't clear this is
685 // valuable as the inliner doesn't currently care whether it is inlining an
686 // invoke or a call.
687
688 // Run the inliner first. The theory is that we are walking bottom-up and so
689 // the callees have already been fully optimized, and we want to inline them
690 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000691 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000692 // because it makes profile annotation in the backend inaccurate.
693 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000694 if (Phase == ThinLTOPhase::PreLink &&
695 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000696 IP.HotCallSiteThreshold = 0;
697 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000698
699 // Now deduce any function attributes based in the current code.
700 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
701
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000702 // When at O3 add argument promotion to the pass pipeline.
703 // FIXME: It isn't at all clear why this should be limited to O3.
704 if (Level == O3)
705 MainCGPipeline.addPass(ArgumentPromotionPass());
706
Chandler Carruthe3f50642016-12-22 06:59:15 +0000707 // Lastly, add the core function simplification pipeline nested inside the
708 // CGSCC walk.
709 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000710 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000711
Teresa Johnsond7253352018-10-23 22:57:40 +0000712 // We only want to do hot cold splitting once for ThinLTO, during the
713 // post-link ThinLTO.
714 if (EnableHotColdSplit && Phase != ThinLTOPhase::PreLink)
Aditya Kumard9e2e382018-10-21 18:11:56 +0000715 MPM.addPass(HotColdSplittingPass());
716
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000717 for (auto &C : CGSCCOptimizerLateEPCallbacks)
718 C(MainCGPipeline, Level);
719
Chandler Carruth719ffe12017-02-12 05:38:04 +0000720 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
721 // to detect when we devirtualize indirect calls and iterate the SCC passes
722 // in that case to try and catch knock-on inlining or function attrs
723 // opportunities. Then we add it to the module pipeline by walking the SCCs
724 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000725 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000726 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000727 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000728
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000729 return MPM;
730}
731
732ModulePassManager
733PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
734 bool DebugLogging) {
735 ModulePassManager MPM(DebugLogging);
736
737 // Optimize globals now that the module is fully simplified.
738 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000739 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000740
Xinliang David Li126157c2017-05-22 16:41:57 +0000741 // Run partial inlining pass to partially inline functions that have
742 // large bodies.
743 if (RunPartialInlining)
744 MPM.addPass(PartialInlinerPass());
745
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000746 // Remove avail extern fns and globals definitions since we aren't compiling
747 // an object file for later LTO. For LTO we want to preserve these so they
748 // are eligible for inlining at link-time. Note if they are unreferenced they
749 // will be removed by GlobalDCE later, so this only impacts referenced
750 // available externally globals. Eventually they will be suppressed during
751 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
752 // may make globals referenced by available external functions dead and saves
753 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000754 MPM.addPass(EliminateAvailableExternallyPass());
755
756 // Do RPO function attribute inference across the module to forward-propagate
757 // attributes where applicable.
758 // FIXME: Is this really an optimization rather than a canonicalization?
759 MPM.addPass(ReversePostOrderFunctionAttrsPass());
760
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000761 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000762 // useful as the above will have inlined, DCE'ed, and function-attr
763 // propagated everything. We should at this point have a reasonably minimal
764 // and richly annotated call graph. By computing aliasing and mod/ref
765 // information for all local globals here, the late loop passes and notably
766 // the vectorizer will be able to use them to help recognize vectorizable
767 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000768 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000769
770 FunctionPassManager OptimizePM(DebugLogging);
771 OptimizePM.addPass(Float2IntPass());
772 // FIXME: We need to run some loop optimizations to re-rotate loops after
773 // simplify-cfg and others undo their rotation.
774
775 // Optimize the loop execution. These passes operate on entire loop nests
776 // rather than on each loop in an inside-out manner, and so they are actually
777 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000778
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000779 for (auto &C : VectorizerStartEPCallbacks)
780 C(OptimizePM, Level);
781
Chandler Carrutha95ff382017-01-27 00:50:21 +0000782 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000783 OptimizePM.addPass(
784 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000785
786 // Distribute loops to allow partial vectorization. I.e. isolate dependences
787 // into separate loop that would otherwise inhibit vectorization. This is
788 // currently only performed for loops marked with the metadata
789 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000790 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000791
792 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000793 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000794
Chandler Carruthbaabda92017-01-27 01:32:26 +0000795 // Eliminate loads by forwarding stores from the previous iteration to loads
796 // of the current iteration.
797 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000798
799 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000800 OptimizePM.addPass(InstCombinePass());
801
Chandler Carrutha95ff382017-01-27 00:50:21 +0000802 // Now that we've formed fast to execute loop structures, we do further
803 // optimizations. These are run afterward as they might block doing complex
804 // analyses and transforms such as what are needed for loop vectorization.
805
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000806 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
807 // GVN, loop transforms, and others have already run, so it's now better to
808 // convert to more optimized IR using more aggressive simplify CFG options.
809 // The extra sinking transform can create larger basic blocks, so do this
810 // before SLP vectorization.
811 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
812 forwardSwitchCondToPhi(true).
813 convertSwitchToLookupTable(true).
814 needCanonicalLoops(false).
815 sinkCommonInsts(true)));
816
Chandler Carruthe3f50642016-12-22 06:59:15 +0000817 // Optimize parallel scalar instruction chains into SIMD instructions.
818 OptimizePM.addPass(SLPVectorizerPass());
819
Chandler Carruthe3f50642016-12-22 06:59:15 +0000820 OptimizePM.addPass(InstCombinePass());
821
822 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000823 // execution resources of an out-of-order processor. We also then need to
824 // clean up redundancies and loop invariant code.
825 // FIXME: It would be really good to use a loop-integrated instruction
826 // combiner for cleanup here so that the unrolling and LICM can be pipelined
827 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000828 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
829 if (EnableUnrollAndJam) {
830 OptimizePM.addPass(
831 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
832 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000833 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000834 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000835 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000836 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000837
838 // Now that we've vectorized and unrolled loops, we may have more refined
839 // alignment information, try to re-derive it here.
840 OptimizePM.addPass(AlignmentFromAssumptionsPass());
841
Chandler Carrutha95ff382017-01-27 00:50:21 +0000842 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
843 // canonicalization pass that enables other optimizations. As a result,
844 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
845 // result too early.
846 OptimizePM.addPass(LoopSinkPass());
847
848 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000849 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000850
Sanjay Patel6fd43912017-09-09 13:38:18 +0000851 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
852 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
853 // flattening of blocks.
854 OptimizePM.addPass(DivRemPairsPass());
855
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000856 // LoopSink (and other loop passes since the last simplifyCFG) might have
857 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
858 OptimizePM.addPass(SimplifyCFGPass());
859
Chandler Carruthc34f7892017-11-28 11:32:31 +0000860 // Optimize PHIs by speculating around them when profitable. Note that this
861 // pass needs to be run after any PRE or similar pass as it is essentially
862 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
863 OptimizePM.addPass(SpeculateAroundPHIsPass());
864
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000865 for (auto &C : OptimizerLastEPCallbacks)
866 C(OptimizePM, Level);
867
Chandler Carrutha95ff382017-01-27 00:50:21 +0000868 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000869 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
870
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000871 MPM.addPass(CGProfilePass());
872
Chandler Carruthe3f50642016-12-22 06:59:15 +0000873 // Now we need to do some global optimization transforms.
874 // FIXME: It would seem like these should come first in the optimization
875 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
876 // ordering here.
877 MPM.addPass(GlobalDCEPass());
878 MPM.addPass(ConstantMergePass());
879
880 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000881}
882
Chandler Carruthe3f50642016-12-22 06:59:15 +0000883ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000884PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
885 bool DebugLogging) {
886 assert(Level != O0 && "Must request optimizations for the default pipeline!");
887
888 ModulePassManager MPM(DebugLogging);
889
890 // Force any function attributes we want the rest of the pipeline to observe.
891 MPM.addPass(ForceFunctionAttrsPass());
892
David Blaikie0c64f5a2018-01-23 01:25:20 +0000893 // Apply module pipeline start EP callback.
894 for (auto &C : PipelineStartEPCallbacks)
895 C(MPM);
896
Dehao Chen08f88312017-08-07 20:23:20 +0000897 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000898 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
899
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000900 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000901 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
902 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000903
904 // Now add the optimization pipeline.
905 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
906
907 return MPM;
908}
909
910ModulePassManager
911PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
912 bool DebugLogging) {
913 assert(Level != O0 && "Must request optimizations for the default pipeline!");
914
915 ModulePassManager MPM(DebugLogging);
916
917 // Force any function attributes we want the rest of the pipeline to observe.
918 MPM.addPass(ForceFunctionAttrsPass());
919
Dehao Chen08f88312017-08-07 20:23:20 +0000920 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000921 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
922
David Blaikie0c64f5a2018-01-23 01:25:20 +0000923 // Apply module pipeline start EP callback.
924 for (auto &C : PipelineStartEPCallbacks)
925 C(MPM);
926
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000927 // If we are planning to perform ThinLTO later, we don't bloat the code with
928 // unrolling/vectorization/... now. Just simplify the module as much as we
929 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000930 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
931 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000932
933 // Run partial inlining pass to partially inline functions that have
934 // large bodies.
935 // FIXME: It isn't clear whether this is really the right place to run this
936 // in ThinLTO. Because there is another canonicalization and simplification
937 // phase that will run after the thin link, running this here ends up with
938 // less information than will be available later and it may grow functions in
939 // ways that aren't beneficial.
940 if (RunPartialInlining)
941 MPM.addPass(PartialInlinerPass());
942
943 // Reduce the size of the IR as much as possible.
944 MPM.addPass(GlobalOptPass());
945
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000946 return MPM;
947}
948
Teresa Johnson28023db2018-07-19 14:51:32 +0000949ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
950 OptimizationLevel Level, bool DebugLogging,
951 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000952 ModulePassManager MPM(DebugLogging);
953
Teresa Johnson28023db2018-07-19 14:51:32 +0000954 if (ImportSummary) {
955 // These passes import type identifier resolutions for whole-program
956 // devirtualization and CFI. They must run early because other passes may
957 // disturb the specific instruction patterns that these passes look for,
958 // creating dependencies on resolutions that may not appear in the summary.
959 //
960 // For example, GVN may transform the pattern assume(type.test) appearing in
961 // two basic blocks into assume(phi(type.test, type.test)), which would
962 // transform a dependency on a WPD resolution into a dependency on a type
963 // identifier resolution for CFI.
964 //
965 // Also, WPD has access to more precise information than ICP and can
966 // devirtualize more effectively, so it should operate on the IR first.
967 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
968 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
969 }
970
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000971 // Force any function attributes we want the rest of the pipeline to observe.
972 MPM.addPass(ForceFunctionAttrsPass());
973
974 // During the ThinLTO backend phase we perform early indirect call promotion
975 // here, before globalopt. Otherwise imported available_externally functions
976 // look unreferenced and are removed.
Dehao Chen08f88312017-08-07 20:23:20 +0000977 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
978 // with SamplePGO.
Dehao Chen2f4e2e22017-08-10 05:10:32 +0000979 if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
Dehao Chen08f88312017-08-07 20:23:20 +0000980 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
981 false /* SamplePGO */));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000982
983 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000984 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
985 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000986
987 // Now add the optimization pipeline.
988 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
989
990 return MPM;
991}
992
993ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +0000994PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
995 bool DebugLogging) {
996 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000997 // FIXME: We should use a customized pre-link pipeline!
Chandler Carruthe3f50642016-12-22 06:59:15 +0000998 return buildPerModuleDefaultPipeline(Level, DebugLogging);
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000999}
1000
Teresa Johnson28023db2018-07-19 14:51:32 +00001001ModulePassManager
1002PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1003 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001004 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1005 ModulePassManager MPM(DebugLogging);
1006
Davide Italiano089a9122017-01-24 00:57:39 +00001007 // Remove unused virtual tables to improve the quality of code generated by
1008 // whole-program devirtualization and bitset lowering.
1009 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001010
Davide Italiano089a9122017-01-24 00:57:39 +00001011 // Force any function attributes we want the rest of the pipeline to observe.
1012 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001013
Davide Italiano089a9122017-01-24 00:57:39 +00001014 // Do basic inference of function attributes from known properties of system
1015 // libraries and other oracles.
1016 MPM.addPass(InferFunctionAttrsPass());
1017
1018 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001019 FunctionPassManager EarlyFPM(DebugLogging);
1020 EarlyFPM.addPass(CallSiteSplittingPass());
1021 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1022
Davide Italiano089a9122017-01-24 00:57:39 +00001023 // Indirect call promotion. This should promote all the targets that are
1024 // left by the earlier promotion pass that promotes intra-module targets.
1025 // This two-step promotion is to save the compile time. For LTO, it should
1026 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001027 MPM.addPass(PGOIndirectCallPromotion(
1028 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +00001029 // Propagate constants at call sites into the functions they call. This
1030 // opens opportunities for globalopt (and inlining) by substituting function
1031 // pointers passed as arguments to direct uses of functions.
1032 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001033
1034 // Attach metadata to indirect call sites indicating the set of functions
1035 // they may target at run-time. This should follow IPSCCP.
1036 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001037 }
1038
1039 // Now deduce any function attributes based in the current code.
1040 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1041 PostOrderFunctionAttrsPass()));
1042
1043 // Do RPO function attribute inference across the module to forward-propagate
1044 // attributes where applicable.
1045 // FIXME: Is this really an optimization rather than a canonicalization?
1046 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1047
1048 // Use inragne annotations on GEP indices to split globals where beneficial.
1049 MPM.addPass(GlobalSplitPass());
1050
1051 // Run whole program optimization of virtual call when the list of callees
1052 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001053 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001054
1055 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001056 if (Level == 1) {
1057 // The LowerTypeTestsPass needs to run to lower type metadata and the
1058 // type.test intrinsics. The pass does nothing if CFI is disabled.
1059 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001060 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001061 }
Davide Italiano089a9122017-01-24 00:57:39 +00001062
1063 // Optimize globals to try and fold them into constants.
1064 MPM.addPass(GlobalOptPass());
1065
1066 // Promote any localized globals to SSA registers.
1067 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1068
1069 // Linking modules together can lead to duplicate global constant, only
1070 // keep one copy of each constant.
1071 MPM.addPass(ConstantMergePass());
1072
1073 // Remove unused arguments from functions.
1074 MPM.addPass(DeadArgumentEliminationPass());
1075
1076 // Reduce the code after globalopt and ipsccp. Both can open up significant
1077 // simplification opportunities, and both can propagate functions through
1078 // function pointers. When this happens, we often have to resolve varargs
1079 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001080 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001081 if (Level == O3)
1082 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001083 PeepholeFPM.addPass(InstCombinePass());
1084 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1085
1086 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001087
1088 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1089 // generally clean up exception handling overhead. It isn't clear this is
1090 // valuable as the inliner doesn't currently care whether it is inlining an
1091 // invoke or a call.
1092 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001093 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1094 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001095
1096 // Optimize globals again after we ran the inliner.
1097 MPM.addPass(GlobalOptPass());
1098
1099 // Garbage collect dead functions.
1100 // FIXME: Add ArgumentPromotion pass after once it's ported.
1101 MPM.addPass(GlobalDCEPass());
1102
1103 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001104 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001105 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001106 invokePeepholeEPCallbacks(FPM, Level);
1107
Davide Italiano089a9122017-01-24 00:57:39 +00001108 FPM.addPass(JumpThreadingPass());
1109
1110 // Break up allocas
1111 FPM.addPass(SROA());
1112
1113 // Run a few AA driver optimizations here and now to cleanup the code.
1114 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1115
1116 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1117 PostOrderFunctionAttrsPass()));
1118 // FIXME: here we run IP alias analysis in the legacy PM.
1119
1120 FunctionPassManager MainFPM;
1121
1122 // FIXME: once we fix LoopPass Manager, add LICM here.
1123 // FIXME: once we provide support for enabling MLSM, add it here.
1124 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001125 if (RunNewGVN)
1126 MainFPM.addPass(NewGVNPass());
1127 else
1128 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001129
1130 // Remove dead memcpy()'s.
1131 MainFPM.addPass(MemCpyOptPass());
1132
1133 // Nuke dead stores.
1134 MainFPM.addPass(DSEPass());
1135
1136 // FIXME: at this point, we run a bunch of loop passes:
1137 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1138 // loopVectorize. Enable them once the remaining issue with LPM
1139 // are sorted out.
1140
1141 MainFPM.addPass(InstCombinePass());
1142 MainFPM.addPass(SimplifyCFGPass());
1143 MainFPM.addPass(SCCPPass());
1144 MainFPM.addPass(InstCombinePass());
1145 MainFPM.addPass(BDCEPass());
1146
1147 // FIXME: We may want to run SLPVectorizer here.
1148 // After vectorization, assume intrinsics may tell us more
1149 // about pointer alignments.
1150#if 0
1151 MainFPM.add(AlignmentFromAssumptionsPass());
1152#endif
1153
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001154 // FIXME: Conditionally run LoadCombine here, after it's ported
1155 // (in case we still have this pass, given its questionable usefulness).
1156
Davide Italiano089a9122017-01-24 00:57:39 +00001157 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001158 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001159 MainFPM.addPass(JumpThreadingPass());
1160 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1161
1162 // Create a function that performs CFI checks for cross-DSO calls with
1163 // targets in the current module.
1164 MPM.addPass(CrossDSOCFIPass());
1165
1166 // Lower type metadata and the type.test intrinsic. This pass supports
1167 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1168 // to be run at link time if CFI is enabled. This pass does nothing if
1169 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001170 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001171
1172 // Add late LTO optimization passes.
1173 // Delete basic blocks, which optimization passes may have killed.
1174 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1175
1176 // Drop bodies of available eternally objects to improve GlobalDCE.
1177 MPM.addPass(EliminateAvailableExternallyPass());
1178
1179 // Now that we have optimized the program, discard unreachable functions.
1180 MPM.addPass(GlobalDCEPass());
1181
1182 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001183 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001184}
1185
Chandler Carruth060ad612016-12-23 20:38:19 +00001186AAManager PassBuilder::buildDefaultAAPipeline() {
1187 AAManager AA;
1188
1189 // The order in which these are registered determines their priority when
1190 // being queried.
1191
1192 // First we register the basic alias analysis that provides the majority of
1193 // per-function local AA logic. This is a stateless, on-demand local set of
1194 // AA techniques.
1195 AA.registerFunctionAnalysis<BasicAA>();
1196
1197 // Next we query fast, specialized alias analyses that wrap IR-embedded
1198 // information about aliasing.
1199 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1200 AA.registerFunctionAnalysis<TypeBasedAA>();
1201
1202 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001203 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1204 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001205 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001206 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001207
1208 return AA;
1209}
1210
Chandler Carruth241bf242016-08-03 07:44:48 +00001211static Optional<int> parseRepeatPassName(StringRef Name) {
1212 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1213 return None;
1214 int Count;
1215 if (Name.getAsInteger(0, Count) || Count <= 0)
1216 return None;
1217 return Count;
1218}
1219
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001220static Optional<int> parseDevirtPassName(StringRef Name) {
1221 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1222 return None;
1223 int Count;
1224 if (Name.getAsInteger(0, Count) || Count <= 0)
1225 return None;
1226 return Count;
1227}
1228
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001229/// Tests whether a pass name starts with a valid prefix for a default pipeline
1230/// alias.
1231static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1232 return Name.startswith("default") || Name.startswith("thinlto") ||
1233 Name.startswith("lto");
1234}
1235
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001236/// Tests whether registered callbacks will accept a given pass name.
1237///
1238/// When parsing a pipeline text, the type of the outermost pipeline may be
1239/// omitted, in which case the type is automatically determined from the first
1240/// pass name in the text. This may be a name that is handled through one of the
1241/// callbacks. We check this through the oridinary parsing callbacks by setting
1242/// up a dummy PassManager in order to not force the client to also handle this
1243/// type of query.
1244template <typename PassManagerT, typename CallbacksT>
1245static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1246 if (!Callbacks.empty()) {
1247 PassManagerT DummyPM;
1248 for (auto &CB : Callbacks)
1249 if (CB(Name, DummyPM, {}))
1250 return true;
1251 }
1252 return false;
1253}
1254
1255template <typename CallbacksT>
1256static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001257 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001258 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001259 return DefaultAliasRegex.match(Name);
1260
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001261 // Explicitly handle pass manager names.
1262 if (Name == "module")
1263 return true;
1264 if (Name == "cgscc")
1265 return true;
1266 if (Name == "function")
1267 return true;
1268
Chandler Carruth241bf242016-08-03 07:44:48 +00001269 // Explicitly handle custom-parsed pass names.
1270 if (parseRepeatPassName(Name))
1271 return true;
1272
Chandler Carruth74a8a222016-06-17 07:15:29 +00001273#define MODULE_PASS(NAME, CREATE_PASS) \
1274 if (Name == NAME) \
1275 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001276#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001277 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001278 return true;
1279#include "PassRegistry.def"
1280
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001281 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001282}
1283
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001284template <typename CallbacksT>
1285static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001286 // Explicitly handle pass manager names.
1287 if (Name == "cgscc")
1288 return true;
1289 if (Name == "function")
1290 return true;
1291
Chandler Carruth241bf242016-08-03 07:44:48 +00001292 // Explicitly handle custom-parsed pass names.
1293 if (parseRepeatPassName(Name))
1294 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001295 if (parseDevirtPassName(Name))
1296 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001297
Chandler Carruth74a8a222016-06-17 07:15:29 +00001298#define CGSCC_PASS(NAME, CREATE_PASS) \
1299 if (Name == NAME) \
1300 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001301#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001302 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001303 return true;
1304#include "PassRegistry.def"
1305
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001306 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001307}
1308
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001309template <typename CallbacksT>
1310static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001311 // Explicitly handle pass manager names.
1312 if (Name == "function")
1313 return true;
1314 if (Name == "loop")
1315 return true;
1316
Chandler Carruth241bf242016-08-03 07:44:48 +00001317 // Explicitly handle custom-parsed pass names.
1318 if (parseRepeatPassName(Name))
1319 return true;
1320
Chandler Carruth74a8a222016-06-17 07:15:29 +00001321#define FUNCTION_PASS(NAME, CREATE_PASS) \
1322 if (Name == NAME) \
1323 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001324#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001325 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001326 return true;
1327#include "PassRegistry.def"
1328
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001329 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001330}
1331
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001332template <typename CallbacksT>
1333static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001334 // Explicitly handle pass manager names.
1335 if (Name == "loop")
1336 return true;
1337
Chandler Carruth241bf242016-08-03 07:44:48 +00001338 // Explicitly handle custom-parsed pass names.
1339 if (parseRepeatPassName(Name))
1340 return true;
1341
Chandler Carruth74a8a222016-06-17 07:15:29 +00001342#define LOOP_PASS(NAME, CREATE_PASS) \
1343 if (Name == NAME) \
1344 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001345#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1346 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1347 return true;
1348#include "PassRegistry.def"
1349
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001350 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001351}
1352
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001353Optional<std::vector<PassBuilder::PipelineElement>>
1354PassBuilder::parsePipelineText(StringRef Text) {
1355 std::vector<PipelineElement> ResultPipeline;
1356
1357 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1358 &ResultPipeline};
1359 for (;;) {
1360 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1361 size_t Pos = Text.find_first_of(",()");
1362 Pipeline.push_back({Text.substr(0, Pos), {}});
1363
1364 // If we have a single terminating name, we're done.
1365 if (Pos == Text.npos)
1366 break;
1367
1368 char Sep = Text[Pos];
1369 Text = Text.substr(Pos + 1);
1370 if (Sep == ',')
1371 // Just a name ending in a comma, continue.
1372 continue;
1373
1374 if (Sep == '(') {
1375 // Push the inner pipeline onto the stack to continue processing.
1376 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1377 continue;
1378 }
1379
1380 assert(Sep == ')' && "Bogus separator!");
1381 // When handling the close parenthesis, we greedily consume them to avoid
1382 // empty strings in the pipeline.
1383 do {
1384 // If we try to pop the outer pipeline we have unbalanced parentheses.
1385 if (PipelineStack.size() == 1)
1386 return None;
1387
1388 PipelineStack.pop_back();
1389 } while (Text.consume_front(")"));
1390
1391 // Check if we've finished parsing.
1392 if (Text.empty())
1393 break;
1394
1395 // Otherwise, the end of an inner pipeline always has to be followed by
1396 // a comma, and then we can continue.
1397 if (!Text.consume_front(","))
1398 return None;
1399 }
1400
1401 if (PipelineStack.size() > 1)
1402 // Unbalanced paretheses.
1403 return None;
1404
1405 assert(PipelineStack.back() == &ResultPipeline &&
1406 "Wrong pipeline at the bottom of the stack!");
1407 return {std::move(ResultPipeline)};
1408}
1409
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001410Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1411 const PipelineElement &E,
1412 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001413 auto &Name = E.Name;
1414 auto &InnerPipeline = E.InnerPipeline;
1415
1416 // First handle complex passes like the pass managers which carry pipelines.
1417 if (!InnerPipeline.empty()) {
1418 if (Name == "module") {
1419 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001420 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1421 VerifyEachPass, DebugLogging))
1422 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001423 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001424 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001425 }
1426 if (Name == "cgscc") {
1427 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001428 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1429 DebugLogging))
1430 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001431 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001432 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001433 }
1434 if (Name == "function") {
1435 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001436 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1437 VerifyEachPass, DebugLogging))
1438 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001439 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001440 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001441 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001442 if (auto Count = parseRepeatPassName(Name)) {
1443 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001444 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1445 VerifyEachPass, DebugLogging))
1446 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001447 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001448 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001449 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001450
1451 for (auto &C : ModulePipelineParsingCallbacks)
1452 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001453 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001454
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001455 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001456 return make_error<StringError>(
1457 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1458 inconvertibleErrorCode());
1459 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001460 }
1461
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001462 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001463 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001464 SmallVector<StringRef, 3> Matches;
1465 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001466 return make_error<StringError>(
1467 formatv("unknown default pipeline alias '{0}'", Name).str(),
1468 inconvertibleErrorCode());
1469
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001470 assert(Matches.size() == 3 && "Must capture two matched strings!");
1471
Jordan Rosef85a95f2016-07-25 18:34:51 +00001472 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001473 .Case("O0", O0)
1474 .Case("O1", O1)
1475 .Case("O2", O2)
1476 .Case("O3", O3)
1477 .Case("Os", Os)
1478 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001479 if (L == O0)
1480 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001481 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001482
1483 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001484 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001485 } else if (Matches[1] == "thinlto-pre-link") {
1486 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1487 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001488 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001489 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001490 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001491 } else {
1492 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001493 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001494 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001495 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001496 }
1497
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001498 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001499#define MODULE_PASS(NAME, CREATE_PASS) \
1500 if (Name == NAME) { \
1501 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001502 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001503 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001504#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1505 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001506 MPM.addPass( \
1507 RequireAnalysisPass< \
1508 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001509 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001510 } \
1511 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001512 MPM.addPass(InvalidateAnalysisPass< \
1513 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001514 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001515 }
1516#include "PassRegistry.def"
1517
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001518 for (auto &C : ModulePipelineParsingCallbacks)
1519 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001520 return Error::success();
1521 return make_error<StringError>(
1522 formatv("unknown module pass '{0}'", Name).str(),
1523 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001524}
1525
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001526Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1527 const PipelineElement &E, bool VerifyEachPass,
1528 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001529 auto &Name = E.Name;
1530 auto &InnerPipeline = E.InnerPipeline;
1531
1532 // First handle complex passes like the pass managers which carry pipelines.
1533 if (!InnerPipeline.empty()) {
1534 if (Name == "cgscc") {
1535 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001536 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1537 VerifyEachPass, DebugLogging))
1538 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001539 // Add the nested pass manager with the appropriate adaptor.
1540 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001541 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001542 }
1543 if (Name == "function") {
1544 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001545 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1546 VerifyEachPass, DebugLogging))
1547 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001548 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001549 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001550 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001551 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001552 if (auto Count = parseRepeatPassName(Name)) {
1553 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001554 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1555 VerifyEachPass, DebugLogging))
1556 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001557 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001558 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001559 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001560 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1561 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001562 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1563 VerifyEachPass, DebugLogging))
1564 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001565 CGPM.addPass(
1566 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001567 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001568 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001569
1570 for (auto &C : CGSCCPipelineParsingCallbacks)
1571 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001572 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001573
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001574 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001575 return make_error<StringError>(
1576 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1577 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001578 }
1579
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001580// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001581#define CGSCC_PASS(NAME, CREATE_PASS) \
1582 if (Name == NAME) { \
1583 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001584 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001585 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001586#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1587 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001588 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001589 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001590 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1591 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001592 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001593 } \
1594 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001595 CGPM.addPass(InvalidateAnalysisPass< \
1596 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001597 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001598 }
1599#include "PassRegistry.def"
1600
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001601 for (auto &C : CGSCCPipelineParsingCallbacks)
1602 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001603 return Error::success();
1604 return make_error<StringError>(
1605 formatv("unknown cgscc pass '{0}'", Name).str(),
1606 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001607}
1608
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001609Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1610 const PipelineElement &E,
1611 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001612 auto &Name = E.Name;
1613 auto &InnerPipeline = E.InnerPipeline;
1614
1615 // First handle complex passes like the pass managers which carry pipelines.
1616 if (!InnerPipeline.empty()) {
1617 if (Name == "function") {
1618 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001619 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1620 VerifyEachPass, DebugLogging))
1621 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001622 // Add the nested pass manager with the appropriate adaptor.
1623 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001624 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001625 }
1626 if (Name == "loop") {
1627 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001628 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1629 DebugLogging))
1630 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001631 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001632 FPM.addPass(
1633 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001634 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001635 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001636 if (auto Count = parseRepeatPassName(Name)) {
1637 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001638 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1639 VerifyEachPass, DebugLogging))
1640 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001641 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001642 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001643 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001644
1645 for (auto &C : FunctionPipelineParsingCallbacks)
1646 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001647 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001648
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001649 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001650 return make_error<StringError>(
1651 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1652 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001653 }
1654
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001655// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001656#define FUNCTION_PASS(NAME, CREATE_PASS) \
1657 if (Name == NAME) { \
1658 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001659 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001660 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001661#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1662 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001663 FPM.addPass( \
1664 RequireAnalysisPass< \
1665 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001666 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001667 } \
1668 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001669 FPM.addPass(InvalidateAnalysisPass< \
1670 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001671 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001672 }
1673#include "PassRegistry.def"
1674
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001675 for (auto &C : FunctionPipelineParsingCallbacks)
1676 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001677 return Error::success();
1678 return make_error<StringError>(
1679 formatv("unknown function pass '{0}'", Name).str(),
1680 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001681}
1682
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001683Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1684 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001685 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001686 auto &InnerPipeline = E.InnerPipeline;
1687
1688 // First handle complex passes like the pass managers which carry pipelines.
1689 if (!InnerPipeline.empty()) {
1690 if (Name == "loop") {
1691 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001692 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1693 VerifyEachPass, DebugLogging))
1694 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001695 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001696 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001697 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001698 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001699 if (auto Count = parseRepeatPassName(Name)) {
1700 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001701 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1702 VerifyEachPass, DebugLogging))
1703 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001704 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001705 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001706 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001707
1708 for (auto &C : LoopPipelineParsingCallbacks)
1709 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001710 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001711
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001712 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001713 return make_error<StringError>(
1714 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1715 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001716 }
1717
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001718// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001719#define LOOP_PASS(NAME, CREATE_PASS) \
1720 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001721 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001722 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001723 }
1724#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1725 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001726 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001727 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1728 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1729 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001730 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001731 } \
1732 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001733 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001734 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001735 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001736 }
1737#include "PassRegistry.def"
1738
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001739 for (auto &C : LoopPipelineParsingCallbacks)
1740 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001741 return Error::success();
1742 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1743 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001744}
1745
Chandler Carruthedf59962016-02-18 09:45:17 +00001746bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001747#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1748 if (Name == NAME) { \
1749 AA.registerModuleAnalysis< \
1750 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1751 return true; \
1752 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001753#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1754 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001755 AA.registerFunctionAnalysis< \
1756 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001757 return true; \
1758 }
1759#include "PassRegistry.def"
1760
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001761 for (auto &C : AAParsingCallbacks)
1762 if (C(Name, AA))
1763 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001764 return false;
1765}
1766
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001767Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001768 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001769 bool VerifyEachPass,
1770 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001771 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001772 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1773 return Err;
1774 // FIXME: No verifier support for Loop passes!
1775 }
1776 return Error::success();
1777}
1778
1779Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1780 ArrayRef<PipelineElement> Pipeline,
1781 bool VerifyEachPass,
1782 bool DebugLogging) {
1783 for (const auto &Element : Pipeline) {
1784 if (auto Err =
1785 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1786 return Err;
1787 if (VerifyEachPass)
1788 FPM.addPass(VerifierPass());
1789 }
1790 return Error::success();
1791}
1792
1793Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1794 ArrayRef<PipelineElement> Pipeline,
1795 bool VerifyEachPass,
1796 bool DebugLogging) {
1797 for (const auto &Element : Pipeline) {
1798 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1799 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001800 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001801 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001802 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00001803}
1804
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001805void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1806 FunctionAnalysisManager &FAM,
1807 CGSCCAnalysisManager &CGAM,
1808 ModuleAnalysisManager &MAM) {
1809 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1810 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001811 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1812 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1813 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1814 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1815 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1816}
1817
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001818Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1819 ArrayRef<PipelineElement> Pipeline,
1820 bool VerifyEachPass,
1821 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001822 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001823 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1824 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001825 if (VerifyEachPass)
1826 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001827 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001828 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001829}
1830
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001831// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00001832// FIXME: Should this routine accept a TargetMachine or require the caller to
1833// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001834Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1835 StringRef PipelineText,
1836 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001837 auto Pipeline = parsePipelineText(PipelineText);
1838 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001839 return make_error<StringError>(
1840 formatv("invalid pipeline '{0}'", PipelineText).str(),
1841 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001842
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001843 // If the first name isn't at the module layer, wrap the pipeline up
1844 // automatically.
1845 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00001846
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001847 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1848 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001849 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001850 } else if (isFunctionPassName(FirstName,
1851 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001852 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001853 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001854 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001855 } else {
1856 for (auto &C : TopLevelPipelineParsingCallbacks)
1857 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001858 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001859
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001860 // Unknown pass or pipeline name!
1861 auto &InnerPipeline = Pipeline->front().InnerPipeline;
1862 return make_error<StringError>(
1863 formatv("unknown {0} name '{1}'",
1864 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1865 .str(),
1866 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001867 }
Chandler Carruth572e3402014-04-21 11:12:00 +00001868 }
1869
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001870 if (auto Err =
1871 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1872 return Err;
1873 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001874}
Chandler Carruthedf59962016-02-18 09:45:17 +00001875
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001876// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001877Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1878 StringRef PipelineText,
1879 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001880 auto Pipeline = parsePipelineText(PipelineText);
1881 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001882 return make_error<StringError>(
1883 formatv("invalid pipeline '{0}'", PipelineText).str(),
1884 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001885
1886 StringRef FirstName = Pipeline->front().Name;
1887 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001888 return make_error<StringError>(
1889 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
1890 PipelineText)
1891 .str(),
1892 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001893
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001894 if (auto Err =
1895 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
1896 return Err;
1897 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001898}
1899
1900// Primary pass pipeline description parsing routine for a \c
1901// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001902Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
1903 StringRef PipelineText,
1904 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001905 auto Pipeline = parsePipelineText(PipelineText);
1906 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001907 return make_error<StringError>(
1908 formatv("invalid pipeline '{0}'", PipelineText).str(),
1909 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001910
1911 StringRef FirstName = Pipeline->front().Name;
1912 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001913 return make_error<StringError>(
1914 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
1915 PipelineText)
1916 .str(),
1917 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001918
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001919 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
1920 DebugLogging))
1921 return Err;
1922 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001923}
1924
1925// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001926Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
1927 StringRef PipelineText,
1928 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001929 auto Pipeline = parsePipelineText(PipelineText);
1930 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001931 return make_error<StringError>(
1932 formatv("invalid pipeline '{0}'", PipelineText).str(),
1933 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001934
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001935 if (auto Err =
1936 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
1937 return Err;
1938
1939 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001940}
1941
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001942Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00001943 // If the pipeline just consists of the word 'default' just replace the AA
1944 // manager with our default one.
1945 if (PipelineText == "default") {
1946 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001947 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00001948 }
1949
Chandler Carruthedf59962016-02-18 09:45:17 +00001950 while (!PipelineText.empty()) {
1951 StringRef Name;
1952 std::tie(Name, PipelineText) = PipelineText.split(',');
1953 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001954 return make_error<StringError>(
1955 formatv("unknown alias analysis name '{0}'", Name).str(),
1956 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00001957 }
1958
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001959 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00001960}