blob: 6ad1e4bca9196742341a27756cb8c3672538aa7f [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"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000142#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000143#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000144#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000145#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000146#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000147#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000148#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000149#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000150#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000151#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000152#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000153#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000154#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000155#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000156#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000157#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000158#include "llvm/Transforms/Utils/SymbolRewriter.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000159#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000160#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000161
Chandler Carruth66445382014-01-11 08:16:35 +0000162using namespace llvm;
163
Chandler Carruth719ffe12017-02-12 05:38:04 +0000164static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
165 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000166static cl::opt<bool>
167 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
168 cl::Hidden, cl::ZeroOrMore,
169 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000170
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000171static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000172 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000173 cl::Hidden, cl::ZeroOrMore,
174 cl::desc("Run NewGVN instead of GVN"));
175
Geoff Berry3cca1da2017-06-10 15:20:03 +0000176static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000177 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
178 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000179
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000180static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000181 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
182 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000183
Davide Italianobe1b6a92017-06-03 23:18:29 +0000184static cl::opt<bool> EnableGVNSink(
185 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
186 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
187
David Green963401d2018-07-01 12:47:30 +0000188static cl::opt<bool> EnableUnrollAndJam(
189 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
190 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
191
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000192static cl::opt<bool> EnableSyntheticCounts(
193 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
194 cl::desc("Run synthetic function entry count generation "
195 "pass"));
196
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000197static Regex DefaultAliasRegex(
198 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000199
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000200static cl::opt<bool>
201 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
202 cl::desc("Enable control height reduction optimization (CHR)"));
203
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000204extern cl::opt<bool> EnableHotColdSplit;
205
Chandler Carruthe3f50642016-12-22 06:59:15 +0000206static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
207 switch (Level) {
208 case PassBuilder::O0:
209 case PassBuilder::O1:
210 case PassBuilder::O2:
211 case PassBuilder::O3:
212 return false;
213
214 case PassBuilder::Os:
215 case PassBuilder::Oz:
216 return true;
217 }
218 llvm_unreachable("Invalid optimization level!");
219}
220
Chandler Carruth66445382014-01-11 08:16:35 +0000221namespace {
222
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000223/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000224struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000225 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000226 return PreservedAnalyses::all();
227 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000228 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000229};
230
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000231/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000232class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
233 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000234 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000235
236public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000237 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000238 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000239 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000240};
241
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000242/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000243struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000244 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
245 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000246 return PreservedAnalyses::all();
247 }
248 static StringRef name() { return "NoOpCGSCCPass"; }
249};
250
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000251/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000252class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
253 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000254 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000255
256public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000257 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000258 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000259 return Result();
260 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000261 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000262};
263
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000264/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000265struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000266 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000267 return PreservedAnalyses::all();
268 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000269 static StringRef name() { return "NoOpFunctionPass"; }
270};
271
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000272/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000273class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
274 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000275 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000276
277public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000278 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000279 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000280 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000281};
282
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000283/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000284struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000285 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
286 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000287 return PreservedAnalyses::all();
288 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000289 static StringRef name() { return "NoOpLoopPass"; }
290};
291
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000292/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000293class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
294 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000295 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000296
297public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000298 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000299 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
300 return Result();
301 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000302 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000303};
304
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000305AnalysisKey NoOpModuleAnalysis::Key;
306AnalysisKey NoOpCGSCCAnalysis::Key;
307AnalysisKey NoOpFunctionAnalysis::Key;
308AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000309
Chandler Carruth66445382014-01-11 08:16:35 +0000310} // End anonymous namespace.
311
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000312void PassBuilder::invokePeepholeEPCallbacks(
313 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
314 for (auto &C : PeepholeEPCallbacks)
315 C(FPM, Level);
316}
317
Chandler Carruth1ff77242015-03-07 09:02:36 +0000318void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000319#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000320 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000321#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000322
323 for (auto &C : ModuleAnalysisRegistrationCallbacks)
324 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000325}
326
Chandler Carruth1ff77242015-03-07 09:02:36 +0000327void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000328#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000329 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000330#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000331
332 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
333 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000334}
335
Chandler Carruth1ff77242015-03-07 09:02:36 +0000336void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000337#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000338 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000339#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000340
341 for (auto &C : FunctionAnalysisRegistrationCallbacks)
342 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000343}
344
Justin Bognereecc3c82016-02-25 07:23:08 +0000345void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000346#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000347 LAM.registerPass([&] { return CREATE_PASS; });
348#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000349
350 for (auto &C : LoopAnalysisRegistrationCallbacks)
351 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000352}
353
Chandler Carruthe3f50642016-12-22 06:59:15 +0000354FunctionPassManager
355PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000356 ThinLTOPhase Phase,
357 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000358 assert(Level != O0 && "Must request optimizations!");
359 FunctionPassManager FPM(DebugLogging);
360
361 // Form SSA out of local memory accesses after breaking apart aggregates into
362 // scalars.
363 FPM.addPass(SROA());
364
365 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000366 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000367
Davide Italianoc3688312017-06-01 23:08:14 +0000368 // Hoisting of scalars and load expressions.
369 if (EnableGVNHoist)
370 FPM.addPass(GVNHoistPass());
371
Davide Italianobe1b6a92017-06-03 23:18:29 +0000372 // Global value numbering based sinking.
373 if (EnableGVNSink) {
374 FPM.addPass(GVNSinkPass());
375 FPM.addPass(SimplifyCFGPass());
376 }
377
Chandler Carruthe3f50642016-12-22 06:59:15 +0000378 // Speculative execution if the target has divergent branches; otherwise nop.
379 FPM.addPass(SpeculativeExecutionPass());
380
381 // Optimize based on known information about branches, and cleanup afterward.
382 FPM.addPass(JumpThreadingPass());
383 FPM.addPass(CorrelatedValuePropagationPass());
384 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000385 if (Level == O3)
386 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000387 FPM.addPass(InstCombinePass());
388
389 if (!isOptimizingForSize(Level))
390 FPM.addPass(LibCallsShrinkWrapPass());
391
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000392 invokePeepholeEPCallbacks(FPM, Level);
393
Rong Xue1f42452017-10-23 22:21:29 +0000394 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
395 // using the size value profile. Don't perform this when optimizing for size.
396 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
397 !isOptimizingForSize(Level))
398 FPM.addPass(PGOMemOPSizeOpt());
399
Chandler Carruthe3f50642016-12-22 06:59:15 +0000400 FPM.addPass(TailCallElimPass());
401 FPM.addPass(SimplifyCFGPass());
402
403 // Form canonically associated expression trees, and simplify the trees using
404 // basic mathematical properties. For example, this will form (nearly)
405 // minimal multiplication trees.
406 FPM.addPass(ReassociatePass());
407
408 // Add the primary loop simplification pipeline.
409 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000410 // some function passes in between them. These can and should be removed
411 // and/or replaced by scheduling the loop pass equivalents in the correct
412 // positions. But those equivalent passes aren't powerful enough yet.
413 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
414 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
415 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
416 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000417 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
418
Chandler Carruth71fd2702018-05-30 02:46:45 +0000419 // Simplify the loop body. We do this initially to clean up after other loop
420 // passes run, either when iterating on a loop or on inner loops with
421 // implications on the outer loop.
422 LPM1.addPass(LoopInstSimplifyPass());
423 LPM1.addPass(LoopSimplifyCFGPass());
424
Chandler Carruthe3f50642016-12-22 06:59:15 +0000425 // Rotate Loop - disable header duplication at -Oz
426 LPM1.addPass(LoopRotatePass(Level != Oz));
427 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000428 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000429 LPM2.addPass(IndVarSimplifyPass());
430 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000431
432 for (auto &C : LateLoopOptimizationsEPCallbacks)
433 C(LPM2, Level);
434
Chandler Carruth79b733b2017-01-26 23:21:17 +0000435 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000436 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000437 // because it changes IR to makes profile annotation in back compile
438 // inaccurate.
Dehao Chen95f00302017-07-30 04:55:39 +0000439 if (Phase != ThinLTOPhase::PreLink ||
440 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnsonecd90132017-08-02 20:35:29 +0000441 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000442
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000443 for (auto &C : LoopOptimizerEndEPCallbacks)
444 C(LPM2, Level);
445
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000446 // We provide the opt remark emitter pass for LICM to use. We only need to do
447 // this once as it is immutable.
448 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000449 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000450 FPM.addPass(SimplifyCFGPass());
451 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000452 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000453
454 // Eliminate redundancies.
455 if (Level != O1) {
456 // These passes add substantial compile time so skip them at O1.
457 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000458 if (RunNewGVN)
459 FPM.addPass(NewGVNPass());
460 else
461 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000462 }
463
464 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
465 FPM.addPass(MemCpyOptPass());
466
467 // Sparse conditional constant propagation.
468 // FIXME: It isn't clear why we do this *after* loop passes rather than
469 // before...
470 FPM.addPass(SCCPPass());
471
472 // Delete dead bit computations (instcombine runs after to fold away the dead
473 // computations, and then ADCE will run later to exploit any new DCE
474 // opportunities that creates).
475 FPM.addPass(BDCEPass());
476
477 // Run instcombine after redundancy and dead bit elimination to exploit
478 // opportunities opened up by them.
479 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000480 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000481
482 // Re-consider control flow based optimizations after redundancy elimination,
483 // redo DCE, etc.
484 FPM.addPass(JumpThreadingPass());
485 FPM.addPass(CorrelatedValuePropagationPass());
486 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000487 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000488
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000489 for (auto &C : ScalarOptimizerLateEPCallbacks)
490 C(FPM, Level);
491
Chandler Carruthe3f50642016-12-22 06:59:15 +0000492 // Finally, do an expensive DCE pass to catch all the dead code exposed by
493 // the simplifications and basic cleanup after all the simplifications.
494 FPM.addPass(ADCEPass());
495 FPM.addPass(SimplifyCFGPass());
496 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000497 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000498
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000499 if (EnableCHR && Level == O3 && PGOOpt &&
500 (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty()))
501 FPM.addPass(ControlHeightReductionPass());
502
Chandler Carruthe3f50642016-12-22 06:59:15 +0000503 return FPM;
504}
505
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000506void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
507 PassBuilder::OptimizationLevel Level,
508 bool RunProfileGen,
509 std::string ProfileGenFile,
Richard Smith6c676622018-10-10 23:13:47 +0000510 std::string ProfileUseFile,
511 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000512 // Generally running simplification passes and the inliner with an high
513 // threshold results in smaller executables, but there may be cases where
514 // the size grows, so let's be conservative here and skip this simplification
515 // at -Os/Oz.
516 if (!isOptimizingForSize(Level)) {
517 InlineParams IP;
518
519 // In the old pass manager, this is a cl::opt. Should still this be one?
520 IP.DefaultThreshold = 75;
521
522 // FIXME: The hint threshold has the same value used by the regular inliner.
523 // This should probably be lowered after performance testing.
524 // FIXME: this comment is cargo culted from the old pass manager, revisit).
525 IP.HintThreshold = 325;
526
527 CGSCCPassManager CGPipeline(DebugLogging);
528
529 CGPipeline.addPass(InlinerPass(IP));
530
531 FunctionPassManager FPM;
532 FPM.addPass(SROA());
533 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
534 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
535 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000536 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000537
Davide Italiano513dfaa2017-02-13 15:26:22 +0000538 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
539
540 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
541 }
542
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000543 // Delete anything that is now dead to make sure that we don't instrument
544 // dead code. Instrumentation can end up keeping dead code around and
545 // dramatically increase code size.
546 MPM.addPass(GlobalDCEPass());
547
Davide Italiano513dfaa2017-02-13 15:26:22 +0000548 if (RunProfileGen) {
549 MPM.addPass(PGOInstrumentationGen());
550
Xinliang David Lib67530e2017-06-25 00:26:43 +0000551 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000552 FPM.addPass(
553 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000554 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
555
Davide Italiano513dfaa2017-02-13 15:26:22 +0000556 // Add the profile lowering pass.
557 InstrProfOptions Options;
558 if (!ProfileGenFile.empty())
559 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000560 Options.DoCounterPromotion = true;
Davide Italiano513dfaa2017-02-13 15:26:22 +0000561 MPM.addPass(InstrProfiling(Options));
562 }
563
564 if (!ProfileUseFile.empty())
Richard Smith6c676622018-10-10 23:13:47 +0000565 MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000566}
567
Easwaran Raman8249fac2017-06-28 13:33:49 +0000568static InlineParams
569getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
570 auto O3 = PassBuilder::O3;
571 unsigned OptLevel = Level > O3 ? 2 : Level;
572 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
573 return getInlineParams(OptLevel, SizeLevel);
574}
575
Chandler Carruthe3f50642016-12-22 06:59:15 +0000576ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000577PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000578 ThinLTOPhase Phase,
579 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000580 ModulePassManager MPM(DebugLogging);
581
Chandler Carruthe3f50642016-12-22 06:59:15 +0000582 // Do basic inference of function attributes from known properties of system
583 // libraries and other oracles.
584 MPM.addPass(InferFunctionAttrsPass());
585
586 // Create an early function pass manager to cleanup the output of the
587 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000588 FunctionPassManager EarlyFPM(DebugLogging);
589 EarlyFPM.addPass(SimplifyCFGPass());
590 EarlyFPM.addPass(SROA());
591 EarlyFPM.addPass(EarlyCSEPass());
592 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000593 if (Level == O3)
594 EarlyFPM.addPass(CallSiteSplittingPass());
595
Dehao Chen08f88312017-08-07 20:23:20 +0000596 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
597 // to convert bitcast to direct calls so that they can be inlined during the
598 // profile annotation prepration step.
599 // More details about SamplePGO design can be found in:
600 // https://research.google.com/pubs/pub45290.html
601 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
602 if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
603 Phase == ThinLTOPhase::PostLink)
604 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000605 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000606
Dehao Chen08f88312017-08-07 20:23:20 +0000607 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
608 // Annotate sample profile right after early FPM to ensure freshness of
609 // the debug info.
Dehao Chend26dae02017-10-01 05:24:51 +0000610 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000611 PGOOpt->ProfileRemappingFile,
Dehao Chend26dae02017-10-01 05:24:51 +0000612 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000613 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
614 // for the profile annotation to be accurate in the ThinLTO backend.
615 if (Phase != ThinLTOPhase::PreLink)
616 // We perform early indirect call promotion here, before globalopt.
617 // This is important for the ThinLTO backend phase because otherwise
618 // imported available_externally functions look unreferenced and are
619 // removed.
620 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
621 true));
622 }
623
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000624 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000625 // and prior to optimizing globals.
626 // FIXME: This position in the pipeline hasn't been carefully considered in
627 // years, it should be re-analyzed.
628 MPM.addPass(IPSCCPPass());
629
Matthew Simpsoncb585582017-10-25 13:40:08 +0000630 // Attach metadata to indirect call sites indicating the set of functions
631 // they may target at run-time. This should follow IPSCCP.
632 MPM.addPass(CalledValuePropagationPass());
633
Chandler Carruthe3f50642016-12-22 06:59:15 +0000634 // Optimize globals to try and fold them into constants.
635 MPM.addPass(GlobalOptPass());
636
637 // Promote any localized globals to SSA registers.
638 // FIXME: Should this instead by a run of SROA?
639 // FIXME: We should probably run instcombine and simplify-cfg afterward to
640 // delete control flows that are dead once globals have been folded to
641 // constants.
642 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
643
644 // Remove any dead arguments exposed by cleanups and constand folding
645 // globals.
646 MPM.addPass(DeadArgumentEliminationPass());
647
648 // Create a small function pass pipeline to cleanup after all the global
649 // optimizations.
650 FunctionPassManager GlobalCleanupPM(DebugLogging);
651 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000652 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
653
Chandler Carruthe3f50642016-12-22 06:59:15 +0000654 GlobalCleanupPM.addPass(SimplifyCFGPass());
655 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
656
Dehao Chen89d32262017-08-02 01:28:31 +0000657 // Add all the requested passes for instrumentation PGO, if requested.
658 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
659 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
660 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
Richard Smith6c676622018-10-10 23:13:47 +0000661 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
662 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000663 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000664 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000665
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000666 // Synthesize function entry counts for non-PGO compilation.
667 if (EnableSyntheticCounts && !PGOOpt)
668 MPM.addPass(SyntheticCountsPropagation());
669
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000670 // Require the GlobalsAA analysis for the module so we can query it within
671 // the CGSCC pipeline.
672 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000673
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000674 // Require the ProfileSummaryAnalysis for the module so we can query it within
675 // the inliner pass.
676 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
677
Chandler Carruthe3f50642016-12-22 06:59:15 +0000678 // Now begin the main postorder CGSCC pipeline.
679 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
680 // manager and trying to emulate its precise behavior. Much of this doesn't
681 // make a lot of sense and we should revisit the core CGSCC structure.
682 CGSCCPassManager MainCGPipeline(DebugLogging);
683
684 // Note: historically, the PruneEH pass was run first to deduce nounwind and
685 // generally clean up exception handling overhead. It isn't clear this is
686 // valuable as the inliner doesn't currently care whether it is inlining an
687 // invoke or a call.
688
689 // Run the inliner first. The theory is that we are walking bottom-up and so
690 // the callees have already been fully optimized, and we want to inline them
691 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000692 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000693 // because it makes profile annotation in the backend inaccurate.
694 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000695 if (Phase == ThinLTOPhase::PreLink &&
696 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000697 IP.HotCallSiteThreshold = 0;
698 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000699
700 // Now deduce any function attributes based in the current code.
701 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
702
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000703 // When at O3 add argument promotion to the pass pipeline.
704 // FIXME: It isn't at all clear why this should be limited to O3.
705 if (Level == O3)
706 MainCGPipeline.addPass(ArgumentPromotionPass());
707
Chandler Carruthe3f50642016-12-22 06:59:15 +0000708 // Lastly, add the core function simplification pipeline nested inside the
709 // CGSCC walk.
710 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000711 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000712
Teresa Johnsond7253352018-10-23 22:57:40 +0000713 // We only want to do hot cold splitting once for ThinLTO, during the
714 // post-link ThinLTO.
715 if (EnableHotColdSplit && Phase != ThinLTOPhase::PreLink)
Aditya Kumard9e2e382018-10-21 18:11:56 +0000716 MPM.addPass(HotColdSplittingPass());
717
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000718 for (auto &C : CGSCCOptimizerLateEPCallbacks)
719 C(MainCGPipeline, Level);
720
Chandler Carruth719ffe12017-02-12 05:38:04 +0000721 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
722 // to detect when we devirtualize indirect calls and iterate the SCC passes
723 // in that case to try and catch knock-on inlining or function attrs
724 // opportunities. Then we add it to the module pipeline by walking the SCCs
725 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000726 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000727 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000728 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000729
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000730 return MPM;
731}
732
733ModulePassManager
734PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
735 bool DebugLogging) {
736 ModulePassManager MPM(DebugLogging);
737
738 // Optimize globals now that the module is fully simplified.
739 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000740 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000741
Xinliang David Li126157c2017-05-22 16:41:57 +0000742 // Run partial inlining pass to partially inline functions that have
743 // large bodies.
744 if (RunPartialInlining)
745 MPM.addPass(PartialInlinerPass());
746
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000747 // Remove avail extern fns and globals definitions since we aren't compiling
748 // an object file for later LTO. For LTO we want to preserve these so they
749 // are eligible for inlining at link-time. Note if they are unreferenced they
750 // will be removed by GlobalDCE later, so this only impacts referenced
751 // available externally globals. Eventually they will be suppressed during
752 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
753 // may make globals referenced by available external functions dead and saves
754 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000755 MPM.addPass(EliminateAvailableExternallyPass());
756
757 // Do RPO function attribute inference across the module to forward-propagate
758 // attributes where applicable.
759 // FIXME: Is this really an optimization rather than a canonicalization?
760 MPM.addPass(ReversePostOrderFunctionAttrsPass());
761
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000762 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000763 // useful as the above will have inlined, DCE'ed, and function-attr
764 // propagated everything. We should at this point have a reasonably minimal
765 // and richly annotated call graph. By computing aliasing and mod/ref
766 // information for all local globals here, the late loop passes and notably
767 // the vectorizer will be able to use them to help recognize vectorizable
768 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000769 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000770
771 FunctionPassManager OptimizePM(DebugLogging);
772 OptimizePM.addPass(Float2IntPass());
773 // FIXME: We need to run some loop optimizations to re-rotate loops after
774 // simplify-cfg and others undo their rotation.
775
776 // Optimize the loop execution. These passes operate on entire loop nests
777 // rather than on each loop in an inside-out manner, and so they are actually
778 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000779
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000780 for (auto &C : VectorizerStartEPCallbacks)
781 C(OptimizePM, Level);
782
Chandler Carrutha95ff382017-01-27 00:50:21 +0000783 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000784 OptimizePM.addPass(
785 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000786
787 // Distribute loops to allow partial vectorization. I.e. isolate dependences
788 // into separate loop that would otherwise inhibit vectorization. This is
789 // currently only performed for loops marked with the metadata
790 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000791 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000792
793 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000794 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000795
Chandler Carruthbaabda92017-01-27 01:32:26 +0000796 // Eliminate loads by forwarding stores from the previous iteration to loads
797 // of the current iteration.
798 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000799
800 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000801 OptimizePM.addPass(InstCombinePass());
802
Chandler Carrutha95ff382017-01-27 00:50:21 +0000803 // Now that we've formed fast to execute loop structures, we do further
804 // optimizations. These are run afterward as they might block doing complex
805 // analyses and transforms such as what are needed for loop vectorization.
806
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000807 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
808 // GVN, loop transforms, and others have already run, so it's now better to
809 // convert to more optimized IR using more aggressive simplify CFG options.
810 // The extra sinking transform can create larger basic blocks, so do this
811 // before SLP vectorization.
812 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
813 forwardSwitchCondToPhi(true).
814 convertSwitchToLookupTable(true).
815 needCanonicalLoops(false).
816 sinkCommonInsts(true)));
817
Chandler Carruthe3f50642016-12-22 06:59:15 +0000818 // Optimize parallel scalar instruction chains into SIMD instructions.
819 OptimizePM.addPass(SLPVectorizerPass());
820
Chandler Carruthe3f50642016-12-22 06:59:15 +0000821 OptimizePM.addPass(InstCombinePass());
822
823 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000824 // execution resources of an out-of-order processor. We also then need to
825 // clean up redundancies and loop invariant code.
826 // FIXME: It would be really good to use a loop-integrated instruction
827 // combiner for cleanup here so that the unrolling and LICM can be pipelined
828 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000829 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
830 if (EnableUnrollAndJam) {
831 OptimizePM.addPass(
832 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
833 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000834 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000835 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000836 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000837 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000838
839 // Now that we've vectorized and unrolled loops, we may have more refined
840 // alignment information, try to re-derive it here.
841 OptimizePM.addPass(AlignmentFromAssumptionsPass());
842
Chandler Carrutha95ff382017-01-27 00:50:21 +0000843 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
844 // canonicalization pass that enables other optimizations. As a result,
845 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
846 // result too early.
847 OptimizePM.addPass(LoopSinkPass());
848
849 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000850 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000851
Sanjay Patel6fd43912017-09-09 13:38:18 +0000852 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
853 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
854 // flattening of blocks.
855 OptimizePM.addPass(DivRemPairsPass());
856
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000857 // LoopSink (and other loop passes since the last simplifyCFG) might have
858 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
859 OptimizePM.addPass(SimplifyCFGPass());
860
Chandler Carruthc34f7892017-11-28 11:32:31 +0000861 // Optimize PHIs by speculating around them when profitable. Note that this
862 // pass needs to be run after any PRE or similar pass as it is essentially
863 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
864 OptimizePM.addPass(SpeculateAroundPHIsPass());
865
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000866 for (auto &C : OptimizerLastEPCallbacks)
867 C(OptimizePM, Level);
868
Chandler Carrutha95ff382017-01-27 00:50:21 +0000869 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000870 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
871
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000872 MPM.addPass(CGProfilePass());
873
Chandler Carruthe3f50642016-12-22 06:59:15 +0000874 // Now we need to do some global optimization transforms.
875 // FIXME: It would seem like these should come first in the optimization
876 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
877 // ordering here.
878 MPM.addPass(GlobalDCEPass());
879 MPM.addPass(ConstantMergePass());
880
881 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000882}
883
Chandler Carruthe3f50642016-12-22 06:59:15 +0000884ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000885PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
886 bool DebugLogging) {
887 assert(Level != O0 && "Must request optimizations for the default pipeline!");
888
889 ModulePassManager MPM(DebugLogging);
890
891 // Force any function attributes we want the rest of the pipeline to observe.
892 MPM.addPass(ForceFunctionAttrsPass());
893
David Blaikie0c64f5a2018-01-23 01:25:20 +0000894 // Apply module pipeline start EP callback.
895 for (auto &C : PipelineStartEPCallbacks)
896 C(MPM);
897
Dehao Chen08f88312017-08-07 20:23:20 +0000898 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000899 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
900
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000901 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000902 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
903 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000904
905 // Now add the optimization pipeline.
906 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
907
908 return MPM;
909}
910
911ModulePassManager
912PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
913 bool DebugLogging) {
914 assert(Level != O0 && "Must request optimizations for the default pipeline!");
915
916 ModulePassManager MPM(DebugLogging);
917
918 // Force any function attributes we want the rest of the pipeline to observe.
919 MPM.addPass(ForceFunctionAttrsPass());
920
Dehao Chen08f88312017-08-07 20:23:20 +0000921 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000922 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
923
David Blaikie0c64f5a2018-01-23 01:25:20 +0000924 // Apply module pipeline start EP callback.
925 for (auto &C : PipelineStartEPCallbacks)
926 C(MPM);
927
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000928 // If we are planning to perform ThinLTO later, we don't bloat the code with
929 // unrolling/vectorization/... now. Just simplify the module as much as we
930 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000931 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
932 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000933
934 // Run partial inlining pass to partially inline functions that have
935 // large bodies.
936 // FIXME: It isn't clear whether this is really the right place to run this
937 // in ThinLTO. Because there is another canonicalization and simplification
938 // phase that will run after the thin link, running this here ends up with
939 // less information than will be available later and it may grow functions in
940 // ways that aren't beneficial.
941 if (RunPartialInlining)
942 MPM.addPass(PartialInlinerPass());
943
944 // Reduce the size of the IR as much as possible.
945 MPM.addPass(GlobalOptPass());
946
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000947 return MPM;
948}
949
Teresa Johnson28023db2018-07-19 14:51:32 +0000950ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
951 OptimizationLevel Level, bool DebugLogging,
952 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000953 ModulePassManager MPM(DebugLogging);
954
Teresa Johnson28023db2018-07-19 14:51:32 +0000955 if (ImportSummary) {
956 // These passes import type identifier resolutions for whole-program
957 // devirtualization and CFI. They must run early because other passes may
958 // disturb the specific instruction patterns that these passes look for,
959 // creating dependencies on resolutions that may not appear in the summary.
960 //
961 // For example, GVN may transform the pattern assume(type.test) appearing in
962 // two basic blocks into assume(phi(type.test, type.test)), which would
963 // transform a dependency on a WPD resolution into a dependency on a type
964 // identifier resolution for CFI.
965 //
966 // Also, WPD has access to more precise information than ICP and can
967 // devirtualize more effectively, so it should operate on the IR first.
968 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
969 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
970 }
971
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000972 // Force any function attributes we want the rest of the pipeline to observe.
973 MPM.addPass(ForceFunctionAttrsPass());
974
975 // During the ThinLTO backend phase we perform early indirect call promotion
976 // here, before globalopt. Otherwise imported available_externally functions
977 // look unreferenced and are removed.
Dehao Chen08f88312017-08-07 20:23:20 +0000978 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
979 // with SamplePGO.
Dehao Chen2f4e2e22017-08-10 05:10:32 +0000980 if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
Dehao Chen08f88312017-08-07 20:23:20 +0000981 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
982 false /* SamplePGO */));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000983
984 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000985 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
986 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000987
988 // Now add the optimization pipeline.
989 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
990
991 return MPM;
992}
993
994ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +0000995PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
996 bool DebugLogging) {
997 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000998 // FIXME: We should use a customized pre-link pipeline!
Chandler Carruthe3f50642016-12-22 06:59:15 +0000999 return buildPerModuleDefaultPipeline(Level, DebugLogging);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001000}
1001
Teresa Johnson28023db2018-07-19 14:51:32 +00001002ModulePassManager
1003PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1004 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001005 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1006 ModulePassManager MPM(DebugLogging);
1007
Xin Tong642c8d32018-11-15 18:06:42 +00001008 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
1009 // Load sample profile before running the LTO optimization pipeline.
1010 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
1011 PGOOpt->ProfileRemappingFile,
1012 false /* ThinLTOPhase::PreLink */));
1013 }
1014
Davide Italiano089a9122017-01-24 00:57:39 +00001015 // Remove unused virtual tables to improve the quality of code generated by
1016 // whole-program devirtualization and bitset lowering.
1017 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001018
Davide Italiano089a9122017-01-24 00:57:39 +00001019 // Force any function attributes we want the rest of the pipeline to observe.
1020 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001021
Davide Italiano089a9122017-01-24 00:57:39 +00001022 // Do basic inference of function attributes from known properties of system
1023 // libraries and other oracles.
1024 MPM.addPass(InferFunctionAttrsPass());
1025
1026 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001027 FunctionPassManager EarlyFPM(DebugLogging);
1028 EarlyFPM.addPass(CallSiteSplittingPass());
1029 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1030
Davide Italiano089a9122017-01-24 00:57:39 +00001031 // Indirect call promotion. This should promote all the targets that are
1032 // left by the earlier promotion pass that promotes intra-module targets.
1033 // This two-step promotion is to save the compile time. For LTO, it should
1034 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001035 MPM.addPass(PGOIndirectCallPromotion(
1036 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +00001037 // Propagate constants at call sites into the functions they call. This
1038 // opens opportunities for globalopt (and inlining) by substituting function
1039 // pointers passed as arguments to direct uses of functions.
1040 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001041
1042 // Attach metadata to indirect call sites indicating the set of functions
1043 // they may target at run-time. This should follow IPSCCP.
1044 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001045 }
1046
1047 // Now deduce any function attributes based in the current code.
1048 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1049 PostOrderFunctionAttrsPass()));
1050
1051 // Do RPO function attribute inference across the module to forward-propagate
1052 // attributes where applicable.
1053 // FIXME: Is this really an optimization rather than a canonicalization?
1054 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1055
1056 // Use inragne annotations on GEP indices to split globals where beneficial.
1057 MPM.addPass(GlobalSplitPass());
1058
1059 // Run whole program optimization of virtual call when the list of callees
1060 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001061 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001062
1063 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001064 if (Level == 1) {
1065 // The LowerTypeTestsPass needs to run to lower type metadata and the
1066 // type.test intrinsics. The pass does nothing if CFI is disabled.
1067 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001068 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001069 }
Davide Italiano089a9122017-01-24 00:57:39 +00001070
1071 // Optimize globals to try and fold them into constants.
1072 MPM.addPass(GlobalOptPass());
1073
1074 // Promote any localized globals to SSA registers.
1075 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1076
1077 // Linking modules together can lead to duplicate global constant, only
1078 // keep one copy of each constant.
1079 MPM.addPass(ConstantMergePass());
1080
1081 // Remove unused arguments from functions.
1082 MPM.addPass(DeadArgumentEliminationPass());
1083
1084 // Reduce the code after globalopt and ipsccp. Both can open up significant
1085 // simplification opportunities, and both can propagate functions through
1086 // function pointers. When this happens, we often have to resolve varargs
1087 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001088 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001089 if (Level == O3)
1090 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001091 PeepholeFPM.addPass(InstCombinePass());
1092 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1093
1094 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001095
1096 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1097 // generally clean up exception handling overhead. It isn't clear this is
1098 // valuable as the inliner doesn't currently care whether it is inlining an
1099 // invoke or a call.
1100 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001101 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1102 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001103
1104 // Optimize globals again after we ran the inliner.
1105 MPM.addPass(GlobalOptPass());
1106
1107 // Garbage collect dead functions.
1108 // FIXME: Add ArgumentPromotion pass after once it's ported.
1109 MPM.addPass(GlobalDCEPass());
1110
1111 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001112 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001113 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001114 invokePeepholeEPCallbacks(FPM, Level);
1115
Davide Italiano089a9122017-01-24 00:57:39 +00001116 FPM.addPass(JumpThreadingPass());
1117
1118 // Break up allocas
1119 FPM.addPass(SROA());
1120
1121 // Run a few AA driver optimizations here and now to cleanup the code.
1122 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1123
1124 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1125 PostOrderFunctionAttrsPass()));
1126 // FIXME: here we run IP alias analysis in the legacy PM.
1127
1128 FunctionPassManager MainFPM;
1129
1130 // FIXME: once we fix LoopPass Manager, add LICM here.
1131 // FIXME: once we provide support for enabling MLSM, add it here.
1132 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001133 if (RunNewGVN)
1134 MainFPM.addPass(NewGVNPass());
1135 else
1136 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001137
1138 // Remove dead memcpy()'s.
1139 MainFPM.addPass(MemCpyOptPass());
1140
1141 // Nuke dead stores.
1142 MainFPM.addPass(DSEPass());
1143
1144 // FIXME: at this point, we run a bunch of loop passes:
1145 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1146 // loopVectorize. Enable them once the remaining issue with LPM
1147 // are sorted out.
1148
1149 MainFPM.addPass(InstCombinePass());
1150 MainFPM.addPass(SimplifyCFGPass());
1151 MainFPM.addPass(SCCPPass());
1152 MainFPM.addPass(InstCombinePass());
1153 MainFPM.addPass(BDCEPass());
1154
1155 // FIXME: We may want to run SLPVectorizer here.
1156 // After vectorization, assume intrinsics may tell us more
1157 // about pointer alignments.
1158#if 0
1159 MainFPM.add(AlignmentFromAssumptionsPass());
1160#endif
1161
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001162 // FIXME: Conditionally run LoadCombine here, after it's ported
1163 // (in case we still have this pass, given its questionable usefulness).
1164
Davide Italiano089a9122017-01-24 00:57:39 +00001165 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001166 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001167 MainFPM.addPass(JumpThreadingPass());
1168 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1169
1170 // Create a function that performs CFI checks for cross-DSO calls with
1171 // targets in the current module.
1172 MPM.addPass(CrossDSOCFIPass());
1173
1174 // Lower type metadata and the type.test intrinsic. This pass supports
1175 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1176 // to be run at link time if CFI is enabled. This pass does nothing if
1177 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001178 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001179
1180 // Add late LTO optimization passes.
1181 // Delete basic blocks, which optimization passes may have killed.
1182 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1183
1184 // Drop bodies of available eternally objects to improve GlobalDCE.
1185 MPM.addPass(EliminateAvailableExternallyPass());
1186
1187 // Now that we have optimized the program, discard unreachable functions.
1188 MPM.addPass(GlobalDCEPass());
1189
1190 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001191 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001192}
1193
Chandler Carruth060ad612016-12-23 20:38:19 +00001194AAManager PassBuilder::buildDefaultAAPipeline() {
1195 AAManager AA;
1196
1197 // The order in which these are registered determines their priority when
1198 // being queried.
1199
1200 // First we register the basic alias analysis that provides the majority of
1201 // per-function local AA logic. This is a stateless, on-demand local set of
1202 // AA techniques.
1203 AA.registerFunctionAnalysis<BasicAA>();
1204
1205 // Next we query fast, specialized alias analyses that wrap IR-embedded
1206 // information about aliasing.
1207 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1208 AA.registerFunctionAnalysis<TypeBasedAA>();
1209
1210 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001211 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1212 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001213 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001214 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001215
1216 return AA;
1217}
1218
Chandler Carruth241bf242016-08-03 07:44:48 +00001219static Optional<int> parseRepeatPassName(StringRef Name) {
1220 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1221 return None;
1222 int Count;
1223 if (Name.getAsInteger(0, Count) || Count <= 0)
1224 return None;
1225 return Count;
1226}
1227
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001228static Optional<int> parseDevirtPassName(StringRef Name) {
1229 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1230 return None;
1231 int Count;
1232 if (Name.getAsInteger(0, Count) || Count <= 0)
1233 return None;
1234 return Count;
1235}
1236
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001237/// Tests whether a pass name starts with a valid prefix for a default pipeline
1238/// alias.
1239static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1240 return Name.startswith("default") || Name.startswith("thinlto") ||
1241 Name.startswith("lto");
1242}
1243
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001244/// Tests whether registered callbacks will accept a given pass name.
1245///
1246/// When parsing a pipeline text, the type of the outermost pipeline may be
1247/// omitted, in which case the type is automatically determined from the first
1248/// pass name in the text. This may be a name that is handled through one of the
1249/// callbacks. We check this through the oridinary parsing callbacks by setting
1250/// up a dummy PassManager in order to not force the client to also handle this
1251/// type of query.
1252template <typename PassManagerT, typename CallbacksT>
1253static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1254 if (!Callbacks.empty()) {
1255 PassManagerT DummyPM;
1256 for (auto &CB : Callbacks)
1257 if (CB(Name, DummyPM, {}))
1258 return true;
1259 }
1260 return false;
1261}
1262
1263template <typename CallbacksT>
1264static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001265 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001266 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001267 return DefaultAliasRegex.match(Name);
1268
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001269 // Explicitly handle pass manager names.
1270 if (Name == "module")
1271 return true;
1272 if (Name == "cgscc")
1273 return true;
1274 if (Name == "function")
1275 return true;
1276
Chandler Carruth241bf242016-08-03 07:44:48 +00001277 // Explicitly handle custom-parsed pass names.
1278 if (parseRepeatPassName(Name))
1279 return true;
1280
Chandler Carruth74a8a222016-06-17 07:15:29 +00001281#define MODULE_PASS(NAME, CREATE_PASS) \
1282 if (Name == NAME) \
1283 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001284#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001285 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001286 return true;
1287#include "PassRegistry.def"
1288
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001289 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001290}
1291
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001292template <typename CallbacksT>
1293static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001294 // Explicitly handle pass manager names.
1295 if (Name == "cgscc")
1296 return true;
1297 if (Name == "function")
1298 return true;
1299
Chandler Carruth241bf242016-08-03 07:44:48 +00001300 // Explicitly handle custom-parsed pass names.
1301 if (parseRepeatPassName(Name))
1302 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001303 if (parseDevirtPassName(Name))
1304 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001305
Chandler Carruth74a8a222016-06-17 07:15:29 +00001306#define CGSCC_PASS(NAME, CREATE_PASS) \
1307 if (Name == NAME) \
1308 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001309#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001310 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001311 return true;
1312#include "PassRegistry.def"
1313
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001314 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001315}
1316
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001317template <typename CallbacksT>
1318static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001319 // Explicitly handle pass manager names.
1320 if (Name == "function")
1321 return true;
1322 if (Name == "loop")
1323 return true;
1324
Chandler Carruth241bf242016-08-03 07:44:48 +00001325 // Explicitly handle custom-parsed pass names.
1326 if (parseRepeatPassName(Name))
1327 return true;
1328
Chandler Carruth74a8a222016-06-17 07:15:29 +00001329#define FUNCTION_PASS(NAME, CREATE_PASS) \
1330 if (Name == NAME) \
1331 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001332#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001333 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001334 return true;
1335#include "PassRegistry.def"
1336
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001337 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001338}
1339
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001340template <typename CallbacksT>
1341static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001342 // Explicitly handle pass manager names.
1343 if (Name == "loop")
1344 return true;
1345
Chandler Carruth241bf242016-08-03 07:44:48 +00001346 // Explicitly handle custom-parsed pass names.
1347 if (parseRepeatPassName(Name))
1348 return true;
1349
Chandler Carruth74a8a222016-06-17 07:15:29 +00001350#define LOOP_PASS(NAME, CREATE_PASS) \
1351 if (Name == NAME) \
1352 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001353#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1354 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1355 return true;
1356#include "PassRegistry.def"
1357
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001358 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001359}
1360
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001361Optional<std::vector<PassBuilder::PipelineElement>>
1362PassBuilder::parsePipelineText(StringRef Text) {
1363 std::vector<PipelineElement> ResultPipeline;
1364
1365 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1366 &ResultPipeline};
1367 for (;;) {
1368 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1369 size_t Pos = Text.find_first_of(",()");
1370 Pipeline.push_back({Text.substr(0, Pos), {}});
1371
1372 // If we have a single terminating name, we're done.
1373 if (Pos == Text.npos)
1374 break;
1375
1376 char Sep = Text[Pos];
1377 Text = Text.substr(Pos + 1);
1378 if (Sep == ',')
1379 // Just a name ending in a comma, continue.
1380 continue;
1381
1382 if (Sep == '(') {
1383 // Push the inner pipeline onto the stack to continue processing.
1384 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1385 continue;
1386 }
1387
1388 assert(Sep == ')' && "Bogus separator!");
1389 // When handling the close parenthesis, we greedily consume them to avoid
1390 // empty strings in the pipeline.
1391 do {
1392 // If we try to pop the outer pipeline we have unbalanced parentheses.
1393 if (PipelineStack.size() == 1)
1394 return None;
1395
1396 PipelineStack.pop_back();
1397 } while (Text.consume_front(")"));
1398
1399 // Check if we've finished parsing.
1400 if (Text.empty())
1401 break;
1402
1403 // Otherwise, the end of an inner pipeline always has to be followed by
1404 // a comma, and then we can continue.
1405 if (!Text.consume_front(","))
1406 return None;
1407 }
1408
1409 if (PipelineStack.size() > 1)
1410 // Unbalanced paretheses.
1411 return None;
1412
1413 assert(PipelineStack.back() == &ResultPipeline &&
1414 "Wrong pipeline at the bottom of the stack!");
1415 return {std::move(ResultPipeline)};
1416}
1417
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001418Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1419 const PipelineElement &E,
1420 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001421 auto &Name = E.Name;
1422 auto &InnerPipeline = E.InnerPipeline;
1423
1424 // First handle complex passes like the pass managers which carry pipelines.
1425 if (!InnerPipeline.empty()) {
1426 if (Name == "module") {
1427 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001428 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1429 VerifyEachPass, DebugLogging))
1430 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001431 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001432 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001433 }
1434 if (Name == "cgscc") {
1435 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001436 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1437 DebugLogging))
1438 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001439 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001440 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001441 }
1442 if (Name == "function") {
1443 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001444 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1445 VerifyEachPass, DebugLogging))
1446 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001447 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001448 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001449 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001450 if (auto Count = parseRepeatPassName(Name)) {
1451 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001452 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1453 VerifyEachPass, DebugLogging))
1454 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001455 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001456 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001457 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001458
1459 for (auto &C : ModulePipelineParsingCallbacks)
1460 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001461 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001462
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001463 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001464 return make_error<StringError>(
1465 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1466 inconvertibleErrorCode());
1467 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001468 }
1469
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001470 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001471 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001472 SmallVector<StringRef, 3> Matches;
1473 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001474 return make_error<StringError>(
1475 formatv("unknown default pipeline alias '{0}'", Name).str(),
1476 inconvertibleErrorCode());
1477
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001478 assert(Matches.size() == 3 && "Must capture two matched strings!");
1479
Jordan Rosef85a95f2016-07-25 18:34:51 +00001480 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001481 .Case("O0", O0)
1482 .Case("O1", O1)
1483 .Case("O2", O2)
1484 .Case("O3", O3)
1485 .Case("Os", Os)
1486 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001487 if (L == O0)
1488 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001489 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001490
1491 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001492 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001493 } else if (Matches[1] == "thinlto-pre-link") {
1494 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1495 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001496 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001497 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001498 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001499 } else {
1500 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001501 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001502 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001503 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001504 }
1505
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001506 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001507#define MODULE_PASS(NAME, CREATE_PASS) \
1508 if (Name == NAME) { \
1509 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001510 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001511 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001512#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1513 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001514 MPM.addPass( \
1515 RequireAnalysisPass< \
1516 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001517 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001518 } \
1519 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001520 MPM.addPass(InvalidateAnalysisPass< \
1521 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001522 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001523 }
1524#include "PassRegistry.def"
1525
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001526 for (auto &C : ModulePipelineParsingCallbacks)
1527 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001528 return Error::success();
1529 return make_error<StringError>(
1530 formatv("unknown module pass '{0}'", Name).str(),
1531 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001532}
1533
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001534Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1535 const PipelineElement &E, bool VerifyEachPass,
1536 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001537 auto &Name = E.Name;
1538 auto &InnerPipeline = E.InnerPipeline;
1539
1540 // First handle complex passes like the pass managers which carry pipelines.
1541 if (!InnerPipeline.empty()) {
1542 if (Name == "cgscc") {
1543 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001544 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1545 VerifyEachPass, DebugLogging))
1546 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001547 // Add the nested pass manager with the appropriate adaptor.
1548 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001549 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001550 }
1551 if (Name == "function") {
1552 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001553 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1554 VerifyEachPass, DebugLogging))
1555 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001556 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001557 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001558 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001559 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001560 if (auto Count = parseRepeatPassName(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 Carrutha053a882016-08-04 03:52:53 +00001565 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001566 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001567 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001568 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1569 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001570 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1571 VerifyEachPass, DebugLogging))
1572 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001573 CGPM.addPass(
1574 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001575 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001576 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001577
1578 for (auto &C : CGSCCPipelineParsingCallbacks)
1579 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001580 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001581
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001582 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001583 return make_error<StringError>(
1584 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1585 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001586 }
1587
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001588// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001589#define CGSCC_PASS(NAME, CREATE_PASS) \
1590 if (Name == NAME) { \
1591 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001592 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001593 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001594#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1595 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001596 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001597 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001598 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1599 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001600 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001601 } \
1602 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001603 CGPM.addPass(InvalidateAnalysisPass< \
1604 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001605 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001606 }
1607#include "PassRegistry.def"
1608
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001609 for (auto &C : CGSCCPipelineParsingCallbacks)
1610 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001611 return Error::success();
1612 return make_error<StringError>(
1613 formatv("unknown cgscc pass '{0}'", Name).str(),
1614 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001615}
1616
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001617Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1618 const PipelineElement &E,
1619 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001620 auto &Name = E.Name;
1621 auto &InnerPipeline = E.InnerPipeline;
1622
1623 // First handle complex passes like the pass managers which carry pipelines.
1624 if (!InnerPipeline.empty()) {
1625 if (Name == "function") {
1626 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001627 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1628 VerifyEachPass, DebugLogging))
1629 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001630 // Add the nested pass manager with the appropriate adaptor.
1631 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001632 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001633 }
1634 if (Name == "loop") {
1635 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001636 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1637 DebugLogging))
1638 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001639 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001640 FPM.addPass(
1641 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001642 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001643 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001644 if (auto Count = parseRepeatPassName(Name)) {
1645 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001646 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1647 VerifyEachPass, DebugLogging))
1648 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001649 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001650 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001651 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001652
1653 for (auto &C : FunctionPipelineParsingCallbacks)
1654 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001655 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001656
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001657 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001658 return make_error<StringError>(
1659 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1660 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001661 }
1662
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001663// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001664#define FUNCTION_PASS(NAME, CREATE_PASS) \
1665 if (Name == NAME) { \
1666 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001667 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001668 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001669#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1670 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001671 FPM.addPass( \
1672 RequireAnalysisPass< \
1673 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001674 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001675 } \
1676 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001677 FPM.addPass(InvalidateAnalysisPass< \
1678 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001679 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001680 }
1681#include "PassRegistry.def"
1682
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001683 for (auto &C : FunctionPipelineParsingCallbacks)
1684 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001685 return Error::success();
1686 return make_error<StringError>(
1687 formatv("unknown function pass '{0}'", Name).str(),
1688 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001689}
1690
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001691Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1692 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001693 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001694 auto &InnerPipeline = E.InnerPipeline;
1695
1696 // First handle complex passes like the pass managers which carry pipelines.
1697 if (!InnerPipeline.empty()) {
1698 if (Name == "loop") {
1699 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001700 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1701 VerifyEachPass, DebugLogging))
1702 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001703 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001704 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001705 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001706 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001707 if (auto Count = parseRepeatPassName(Name)) {
1708 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001709 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1710 VerifyEachPass, DebugLogging))
1711 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001712 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001713 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001714 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001715
1716 for (auto &C : LoopPipelineParsingCallbacks)
1717 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001718 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001719
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001720 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001721 return make_error<StringError>(
1722 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1723 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001724 }
1725
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001726// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001727#define LOOP_PASS(NAME, CREATE_PASS) \
1728 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001729 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001730 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001731 }
1732#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1733 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001734 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001735 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1736 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1737 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001738 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001739 } \
1740 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001741 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001742 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001743 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001744 }
1745#include "PassRegistry.def"
1746
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001747 for (auto &C : LoopPipelineParsingCallbacks)
1748 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001749 return Error::success();
1750 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1751 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001752}
1753
Chandler Carruthedf59962016-02-18 09:45:17 +00001754bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001755#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1756 if (Name == NAME) { \
1757 AA.registerModuleAnalysis< \
1758 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1759 return true; \
1760 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001761#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1762 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001763 AA.registerFunctionAnalysis< \
1764 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001765 return true; \
1766 }
1767#include "PassRegistry.def"
1768
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001769 for (auto &C : AAParsingCallbacks)
1770 if (C(Name, AA))
1771 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001772 return false;
1773}
1774
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001775Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001776 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001777 bool VerifyEachPass,
1778 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001779 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001780 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1781 return Err;
1782 // FIXME: No verifier support for Loop passes!
1783 }
1784 return Error::success();
1785}
1786
1787Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1788 ArrayRef<PipelineElement> Pipeline,
1789 bool VerifyEachPass,
1790 bool DebugLogging) {
1791 for (const auto &Element : Pipeline) {
1792 if (auto Err =
1793 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1794 return Err;
1795 if (VerifyEachPass)
1796 FPM.addPass(VerifierPass());
1797 }
1798 return Error::success();
1799}
1800
1801Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1802 ArrayRef<PipelineElement> Pipeline,
1803 bool VerifyEachPass,
1804 bool DebugLogging) {
1805 for (const auto &Element : Pipeline) {
1806 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1807 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001808 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001809 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001810 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00001811}
1812
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001813void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1814 FunctionAnalysisManager &FAM,
1815 CGSCCAnalysisManager &CGAM,
1816 ModuleAnalysisManager &MAM) {
1817 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1818 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001819 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1820 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1821 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1822 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1823 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1824}
1825
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001826Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1827 ArrayRef<PipelineElement> Pipeline,
1828 bool VerifyEachPass,
1829 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001830 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001831 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1832 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001833 if (VerifyEachPass)
1834 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001835 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001836 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001837}
1838
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001839// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00001840// FIXME: Should this routine accept a TargetMachine or require the caller to
1841// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001842Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1843 StringRef PipelineText,
1844 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001845 auto Pipeline = parsePipelineText(PipelineText);
1846 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001847 return make_error<StringError>(
1848 formatv("invalid pipeline '{0}'", PipelineText).str(),
1849 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001850
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001851 // If the first name isn't at the module layer, wrap the pipeline up
1852 // automatically.
1853 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00001854
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001855 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1856 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001857 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001858 } else if (isFunctionPassName(FirstName,
1859 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001860 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001861 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001862 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001863 } else {
1864 for (auto &C : TopLevelPipelineParsingCallbacks)
1865 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001866 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001867
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001868 // Unknown pass or pipeline name!
1869 auto &InnerPipeline = Pipeline->front().InnerPipeline;
1870 return make_error<StringError>(
1871 formatv("unknown {0} name '{1}'",
1872 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1873 .str(),
1874 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001875 }
Chandler Carruth572e3402014-04-21 11:12:00 +00001876 }
1877
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001878 if (auto Err =
1879 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1880 return Err;
1881 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001882}
Chandler Carruthedf59962016-02-18 09:45:17 +00001883
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001884// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001885Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1886 StringRef PipelineText,
1887 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001888 auto Pipeline = parsePipelineText(PipelineText);
1889 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001890 return make_error<StringError>(
1891 formatv("invalid pipeline '{0}'", PipelineText).str(),
1892 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001893
1894 StringRef FirstName = Pipeline->front().Name;
1895 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001896 return make_error<StringError>(
1897 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
1898 PipelineText)
1899 .str(),
1900 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001901
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001902 if (auto Err =
1903 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
1904 return Err;
1905 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001906}
1907
1908// Primary pass pipeline description parsing routine for a \c
1909// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001910Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
1911 StringRef PipelineText,
1912 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001913 auto Pipeline = parsePipelineText(PipelineText);
1914 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001915 return make_error<StringError>(
1916 formatv("invalid pipeline '{0}'", PipelineText).str(),
1917 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001918
1919 StringRef FirstName = Pipeline->front().Name;
1920 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001921 return make_error<StringError>(
1922 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
1923 PipelineText)
1924 .str(),
1925 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001926
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001927 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
1928 DebugLogging))
1929 return Err;
1930 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001931}
1932
1933// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001934Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
1935 StringRef PipelineText,
1936 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001937 auto Pipeline = parsePipelineText(PipelineText);
1938 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001939 return make_error<StringError>(
1940 formatv("invalid pipeline '{0}'", PipelineText).str(),
1941 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001942
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001943 if (auto Err =
1944 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
1945 return Err;
1946
1947 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001948}
1949
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001950Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00001951 // If the pipeline just consists of the word 'default' just replace the AA
1952 // manager with our default one.
1953 if (PipelineText == "default") {
1954 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001955 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00001956 }
1957
Chandler Carruthedf59962016-02-18 09:45:17 +00001958 while (!PipelineText.empty()) {
1959 StringRef Name;
1960 std::tie(Name, PipelineText) = PipelineText.split(',');
1961 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001962 return make_error<StringError>(
1963 formatv("unknown alias analysis name '{0}'", Name).str(),
1964 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00001965 }
1966
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001967 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00001968}