blob: f6313d23e2d96f350aef756ec5dd05d0db693b38 [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"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000065#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000066#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000067#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000068#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000069#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000070#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000071#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000072#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000073#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000074#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000075#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000076#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000077#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000078#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000079#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000080#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000081#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000082#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000083#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000084#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000085#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000086#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000087#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000088#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000089#include "llvm/Transforms/InstCombine/InstCombine.h"
Leonard Chan64e21b52018-10-11 18:31:51 +000090#include "llvm/Transforms/Instrumentation/AddressSanitizerPass.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000091#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Leonard Chan64e21b52018-10-11 18:31:51 +000092#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000093#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000094#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
95#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +000096#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Justin Bogner19b67992015-10-30 23:13:18 +000097#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +000098#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +000099#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000100#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000101#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000102#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000103#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000104#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000105#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000106#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000107#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000108#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000109#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000110#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000111#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000112#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000113#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000114#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000115#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000116#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000117#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000118#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000119#include "llvm/Transforms/Scalar/LoopDistribute.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000120#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000121#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000122#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000123#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000124#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000125#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000126#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000127#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000128#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000129#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000130#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000131#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000132#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000133#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Sean Silva6347df02016-06-14 02:44:55 +0000134#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000135#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000136#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000137#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000138#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000139#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000140#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000141#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000142#include "llvm/Transforms/Scalar/SROA.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
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000624 if (EnableHotColdSplit)
625 MPM.addPass(HotColdSplittingPass());
626
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000627 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000628 // and prior to optimizing globals.
629 // FIXME: This position in the pipeline hasn't been carefully considered in
630 // years, it should be re-analyzed.
631 MPM.addPass(IPSCCPPass());
632
Matthew Simpsoncb585582017-10-25 13:40:08 +0000633 // Attach metadata to indirect call sites indicating the set of functions
634 // they may target at run-time. This should follow IPSCCP.
635 MPM.addPass(CalledValuePropagationPass());
636
Chandler Carruthe3f50642016-12-22 06:59:15 +0000637 // Optimize globals to try and fold them into constants.
638 MPM.addPass(GlobalOptPass());
639
640 // Promote any localized globals to SSA registers.
641 // FIXME: Should this instead by a run of SROA?
642 // FIXME: We should probably run instcombine and simplify-cfg afterward to
643 // delete control flows that are dead once globals have been folded to
644 // constants.
645 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
646
647 // Remove any dead arguments exposed by cleanups and constand folding
648 // globals.
649 MPM.addPass(DeadArgumentEliminationPass());
650
651 // Create a small function pass pipeline to cleanup after all the global
652 // optimizations.
653 FunctionPassManager GlobalCleanupPM(DebugLogging);
654 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000655 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
656
Chandler Carruthe3f50642016-12-22 06:59:15 +0000657 GlobalCleanupPM.addPass(SimplifyCFGPass());
658 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
659
Dehao Chen89d32262017-08-02 01:28:31 +0000660 // Add all the requested passes for instrumentation PGO, if requested.
661 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
662 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
663 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
Richard Smith6c676622018-10-10 23:13:47 +0000664 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
665 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000666 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000667 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000668
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000669 // Synthesize function entry counts for non-PGO compilation.
670 if (EnableSyntheticCounts && !PGOOpt)
671 MPM.addPass(SyntheticCountsPropagation());
672
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000673 // Require the GlobalsAA analysis for the module so we can query it within
674 // the CGSCC pipeline.
675 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000676
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000677 // Require the ProfileSummaryAnalysis for the module so we can query it within
678 // the inliner pass.
679 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
680
Chandler Carruthe3f50642016-12-22 06:59:15 +0000681 // Now begin the main postorder CGSCC pipeline.
682 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
683 // manager and trying to emulate its precise behavior. Much of this doesn't
684 // make a lot of sense and we should revisit the core CGSCC structure.
685 CGSCCPassManager MainCGPipeline(DebugLogging);
686
687 // Note: historically, the PruneEH pass was run first to deduce nounwind and
688 // generally clean up exception handling overhead. It isn't clear this is
689 // valuable as the inliner doesn't currently care whether it is inlining an
690 // invoke or a call.
691
692 // Run the inliner first. The theory is that we are walking bottom-up and so
693 // the callees have already been fully optimized, and we want to inline them
694 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000695 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000696 // because it makes profile annotation in the backend inaccurate.
697 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000698 if (Phase == ThinLTOPhase::PreLink &&
699 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000700 IP.HotCallSiteThreshold = 0;
701 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000702
703 // Now deduce any function attributes based in the current code.
704 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
705
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000706 // When at O3 add argument promotion to the pass pipeline.
707 // FIXME: It isn't at all clear why this should be limited to O3.
708 if (Level == O3)
709 MainCGPipeline.addPass(ArgumentPromotionPass());
710
Chandler Carruthe3f50642016-12-22 06:59:15 +0000711 // Lastly, add the core function simplification pipeline nested inside the
712 // CGSCC walk.
713 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000714 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000715
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000716 for (auto &C : CGSCCOptimizerLateEPCallbacks)
717 C(MainCGPipeline, Level);
718
Chandler Carruth719ffe12017-02-12 05:38:04 +0000719 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
720 // to detect when we devirtualize indirect calls and iterate the SCC passes
721 // in that case to try and catch knock-on inlining or function attrs
722 // opportunities. Then we add it to the module pipeline by walking the SCCs
723 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000724 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000725 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000726 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000727
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000728 return MPM;
729}
730
731ModulePassManager
732PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
733 bool DebugLogging) {
734 ModulePassManager MPM(DebugLogging);
735
736 // Optimize globals now that the module is fully simplified.
737 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000738 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000739
Xinliang David Li126157c2017-05-22 16:41:57 +0000740 // Run partial inlining pass to partially inline functions that have
741 // large bodies.
742 if (RunPartialInlining)
743 MPM.addPass(PartialInlinerPass());
744
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000745 // Remove avail extern fns and globals definitions since we aren't compiling
746 // an object file for later LTO. For LTO we want to preserve these so they
747 // are eligible for inlining at link-time. Note if they are unreferenced they
748 // will be removed by GlobalDCE later, so this only impacts referenced
749 // available externally globals. Eventually they will be suppressed during
750 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
751 // may make globals referenced by available external functions dead and saves
752 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000753 MPM.addPass(EliminateAvailableExternallyPass());
754
755 // Do RPO function attribute inference across the module to forward-propagate
756 // attributes where applicable.
757 // FIXME: Is this really an optimization rather than a canonicalization?
758 MPM.addPass(ReversePostOrderFunctionAttrsPass());
759
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000760 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000761 // useful as the above will have inlined, DCE'ed, and function-attr
762 // propagated everything. We should at this point have a reasonably minimal
763 // and richly annotated call graph. By computing aliasing and mod/ref
764 // information for all local globals here, the late loop passes and notably
765 // the vectorizer will be able to use them to help recognize vectorizable
766 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000767 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000768
769 FunctionPassManager OptimizePM(DebugLogging);
770 OptimizePM.addPass(Float2IntPass());
771 // FIXME: We need to run some loop optimizations to re-rotate loops after
772 // simplify-cfg and others undo their rotation.
773
774 // Optimize the loop execution. These passes operate on entire loop nests
775 // rather than on each loop in an inside-out manner, and so they are actually
776 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000777
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000778 for (auto &C : VectorizerStartEPCallbacks)
779 C(OptimizePM, Level);
780
Chandler Carrutha95ff382017-01-27 00:50:21 +0000781 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000782 OptimizePM.addPass(
783 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000784
785 // Distribute loops to allow partial vectorization. I.e. isolate dependences
786 // into separate loop that would otherwise inhibit vectorization. This is
787 // currently only performed for loops marked with the metadata
788 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000789 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000790
791 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000792 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000793
Chandler Carruthbaabda92017-01-27 01:32:26 +0000794 // Eliminate loads by forwarding stores from the previous iteration to loads
795 // of the current iteration.
796 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000797
798 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000799 OptimizePM.addPass(InstCombinePass());
800
Chandler Carrutha95ff382017-01-27 00:50:21 +0000801 // Now that we've formed fast to execute loop structures, we do further
802 // optimizations. These are run afterward as they might block doing complex
803 // analyses and transforms such as what are needed for loop vectorization.
804
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000805 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
806 // GVN, loop transforms, and others have already run, so it's now better to
807 // convert to more optimized IR using more aggressive simplify CFG options.
808 // The extra sinking transform can create larger basic blocks, so do this
809 // before SLP vectorization.
810 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
811 forwardSwitchCondToPhi(true).
812 convertSwitchToLookupTable(true).
813 needCanonicalLoops(false).
814 sinkCommonInsts(true)));
815
Chandler Carruthe3f50642016-12-22 06:59:15 +0000816 // Optimize parallel scalar instruction chains into SIMD instructions.
817 OptimizePM.addPass(SLPVectorizerPass());
818
Chandler Carruthe3f50642016-12-22 06:59:15 +0000819 OptimizePM.addPass(InstCombinePass());
820
821 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000822 // execution resources of an out-of-order processor. We also then need to
823 // clean up redundancies and loop invariant code.
824 // FIXME: It would be really good to use a loop-integrated instruction
825 // combiner for cleanup here so that the unrolling and LICM can be pipelined
826 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000827 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
828 if (EnableUnrollAndJam) {
829 OptimizePM.addPass(
830 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
831 }
Teresa Johnsonecd90132017-08-02 20:35:29 +0000832 OptimizePM.addPass(LoopUnrollPass(Level));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000833 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000834 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000835 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000836
837 // Now that we've vectorized and unrolled loops, we may have more refined
838 // alignment information, try to re-derive it here.
839 OptimizePM.addPass(AlignmentFromAssumptionsPass());
840
Chandler Carrutha95ff382017-01-27 00:50:21 +0000841 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
842 // canonicalization pass that enables other optimizations. As a result,
843 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
844 // result too early.
845 OptimizePM.addPass(LoopSinkPass());
846
847 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000848 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000849
Sanjay Patel6fd43912017-09-09 13:38:18 +0000850 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
851 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
852 // flattening of blocks.
853 OptimizePM.addPass(DivRemPairsPass());
854
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000855 // LoopSink (and other loop passes since the last simplifyCFG) might have
856 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
857 OptimizePM.addPass(SimplifyCFGPass());
858
Chandler Carruthc34f7892017-11-28 11:32:31 +0000859 // Optimize PHIs by speculating around them when profitable. Note that this
860 // pass needs to be run after any PRE or similar pass as it is essentially
861 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
862 OptimizePM.addPass(SpeculateAroundPHIsPass());
863
Chandler Carrutha95ff382017-01-27 00:50:21 +0000864 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000865 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
866
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000867 MPM.addPass(CGProfilePass());
868
Chandler Carruthe3f50642016-12-22 06:59:15 +0000869 // Now we need to do some global optimization transforms.
870 // FIXME: It would seem like these should come first in the optimization
871 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
872 // ordering here.
873 MPM.addPass(GlobalDCEPass());
874 MPM.addPass(ConstantMergePass());
875
876 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000877}
878
Chandler Carruthe3f50642016-12-22 06:59:15 +0000879ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000880PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
881 bool DebugLogging) {
882 assert(Level != O0 && "Must request optimizations for the default pipeline!");
883
884 ModulePassManager MPM(DebugLogging);
885
886 // Force any function attributes we want the rest of the pipeline to observe.
887 MPM.addPass(ForceFunctionAttrsPass());
888
David Blaikie0c64f5a2018-01-23 01:25:20 +0000889 // Apply module pipeline start EP callback.
890 for (auto &C : PipelineStartEPCallbacks)
891 C(MPM);
892
Dehao Chen08f88312017-08-07 20:23:20 +0000893 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000894 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
895
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000896 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000897 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
898 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000899
900 // Now add the optimization pipeline.
901 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
902
903 return MPM;
904}
905
906ModulePassManager
907PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
908 bool DebugLogging) {
909 assert(Level != O0 && "Must request optimizations for the default pipeline!");
910
911 ModulePassManager MPM(DebugLogging);
912
913 // Force any function attributes we want the rest of the pipeline to observe.
914 MPM.addPass(ForceFunctionAttrsPass());
915
Dehao Chen08f88312017-08-07 20:23:20 +0000916 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000917 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
918
David Blaikie0c64f5a2018-01-23 01:25:20 +0000919 // Apply module pipeline start EP callback.
920 for (auto &C : PipelineStartEPCallbacks)
921 C(MPM);
922
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000923 // If we are planning to perform ThinLTO later, we don't bloat the code with
924 // unrolling/vectorization/... now. Just simplify the module as much as we
925 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000926 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
927 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000928
929 // Run partial inlining pass to partially inline functions that have
930 // large bodies.
931 // FIXME: It isn't clear whether this is really the right place to run this
932 // in ThinLTO. Because there is another canonicalization and simplification
933 // phase that will run after the thin link, running this here ends up with
934 // less information than will be available later and it may grow functions in
935 // ways that aren't beneficial.
936 if (RunPartialInlining)
937 MPM.addPass(PartialInlinerPass());
938
939 // Reduce the size of the IR as much as possible.
940 MPM.addPass(GlobalOptPass());
941
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000942 return MPM;
943}
944
Teresa Johnson28023db2018-07-19 14:51:32 +0000945ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
946 OptimizationLevel Level, bool DebugLogging,
947 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000948 ModulePassManager MPM(DebugLogging);
949
Teresa Johnson28023db2018-07-19 14:51:32 +0000950 if (ImportSummary) {
951 // These passes import type identifier resolutions for whole-program
952 // devirtualization and CFI. They must run early because other passes may
953 // disturb the specific instruction patterns that these passes look for,
954 // creating dependencies on resolutions that may not appear in the summary.
955 //
956 // For example, GVN may transform the pattern assume(type.test) appearing in
957 // two basic blocks into assume(phi(type.test, type.test)), which would
958 // transform a dependency on a WPD resolution into a dependency on a type
959 // identifier resolution for CFI.
960 //
961 // Also, WPD has access to more precise information than ICP and can
962 // devirtualize more effectively, so it should operate on the IR first.
963 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
964 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
965 }
966
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000967 // Force any function attributes we want the rest of the pipeline to observe.
968 MPM.addPass(ForceFunctionAttrsPass());
969
970 // During the ThinLTO backend phase we perform early indirect call promotion
971 // here, before globalopt. Otherwise imported available_externally functions
972 // look unreferenced and are removed.
Dehao Chen08f88312017-08-07 20:23:20 +0000973 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
974 // with SamplePGO.
Dehao Chen2f4e2e22017-08-10 05:10:32 +0000975 if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
Dehao Chen08f88312017-08-07 20:23:20 +0000976 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
977 false /* SamplePGO */));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000978
979 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000980 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
981 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000982
983 // Now add the optimization pipeline.
984 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
985
986 return MPM;
987}
988
989ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +0000990PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
991 bool DebugLogging) {
992 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000993 // FIXME: We should use a customized pre-link pipeline!
Chandler Carruthe3f50642016-12-22 06:59:15 +0000994 return buildPerModuleDefaultPipeline(Level, DebugLogging);
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000995}
996
Teresa Johnson28023db2018-07-19 14:51:32 +0000997ModulePassManager
998PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
999 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001000 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1001 ModulePassManager MPM(DebugLogging);
1002
Davide Italiano089a9122017-01-24 00:57:39 +00001003 // Remove unused virtual tables to improve the quality of code generated by
1004 // whole-program devirtualization and bitset lowering.
1005 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001006
Davide Italiano089a9122017-01-24 00:57:39 +00001007 // Force any function attributes we want the rest of the pipeline to observe.
1008 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001009
Davide Italiano089a9122017-01-24 00:57:39 +00001010 // Do basic inference of function attributes from known properties of system
1011 // libraries and other oracles.
1012 MPM.addPass(InferFunctionAttrsPass());
1013
1014 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001015 FunctionPassManager EarlyFPM(DebugLogging);
1016 EarlyFPM.addPass(CallSiteSplittingPass());
1017 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1018
Davide Italiano089a9122017-01-24 00:57:39 +00001019 // Indirect call promotion. This should promote all the targets that are
1020 // left by the earlier promotion pass that promotes intra-module targets.
1021 // This two-step promotion is to save the compile time. For LTO, it should
1022 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001023 MPM.addPass(PGOIndirectCallPromotion(
1024 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +00001025 // Propagate constants at call sites into the functions they call. This
1026 // opens opportunities for globalopt (and inlining) by substituting function
1027 // pointers passed as arguments to direct uses of functions.
1028 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001029
1030 // Attach metadata to indirect call sites indicating the set of functions
1031 // they may target at run-time. This should follow IPSCCP.
1032 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001033 }
1034
1035 // Now deduce any function attributes based in the current code.
1036 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1037 PostOrderFunctionAttrsPass()));
1038
1039 // Do RPO function attribute inference across the module to forward-propagate
1040 // attributes where applicable.
1041 // FIXME: Is this really an optimization rather than a canonicalization?
1042 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1043
1044 // Use inragne annotations on GEP indices to split globals where beneficial.
1045 MPM.addPass(GlobalSplitPass());
1046
1047 // Run whole program optimization of virtual call when the list of callees
1048 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001049 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001050
1051 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001052 if (Level == 1) {
1053 // The LowerTypeTestsPass needs to run to lower type metadata and the
1054 // type.test intrinsics. The pass does nothing if CFI is disabled.
1055 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001056 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001057 }
Davide Italiano089a9122017-01-24 00:57:39 +00001058
1059 // Optimize globals to try and fold them into constants.
1060 MPM.addPass(GlobalOptPass());
1061
1062 // Promote any localized globals to SSA registers.
1063 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1064
1065 // Linking modules together can lead to duplicate global constant, only
1066 // keep one copy of each constant.
1067 MPM.addPass(ConstantMergePass());
1068
1069 // Remove unused arguments from functions.
1070 MPM.addPass(DeadArgumentEliminationPass());
1071
1072 // Reduce the code after globalopt and ipsccp. Both can open up significant
1073 // simplification opportunities, and both can propagate functions through
1074 // function pointers. When this happens, we often have to resolve varargs
1075 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001076 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001077 if (Level == O3)
1078 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001079 PeepholeFPM.addPass(InstCombinePass());
1080 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1081
1082 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001083
1084 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1085 // generally clean up exception handling overhead. It isn't clear this is
1086 // valuable as the inliner doesn't currently care whether it is inlining an
1087 // invoke or a call.
1088 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001089 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1090 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001091
1092 // Optimize globals again after we ran the inliner.
1093 MPM.addPass(GlobalOptPass());
1094
1095 // Garbage collect dead functions.
1096 // FIXME: Add ArgumentPromotion pass after once it's ported.
1097 MPM.addPass(GlobalDCEPass());
1098
1099 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001100 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001101 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001102 invokePeepholeEPCallbacks(FPM, Level);
1103
Davide Italiano089a9122017-01-24 00:57:39 +00001104 FPM.addPass(JumpThreadingPass());
1105
1106 // Break up allocas
1107 FPM.addPass(SROA());
1108
1109 // Run a few AA driver optimizations here and now to cleanup the code.
1110 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1111
1112 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1113 PostOrderFunctionAttrsPass()));
1114 // FIXME: here we run IP alias analysis in the legacy PM.
1115
1116 FunctionPassManager MainFPM;
1117
1118 // FIXME: once we fix LoopPass Manager, add LICM here.
1119 // FIXME: once we provide support for enabling MLSM, add it here.
1120 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001121 if (RunNewGVN)
1122 MainFPM.addPass(NewGVNPass());
1123 else
1124 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001125
1126 // Remove dead memcpy()'s.
1127 MainFPM.addPass(MemCpyOptPass());
1128
1129 // Nuke dead stores.
1130 MainFPM.addPass(DSEPass());
1131
1132 // FIXME: at this point, we run a bunch of loop passes:
1133 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1134 // loopVectorize. Enable them once the remaining issue with LPM
1135 // are sorted out.
1136
1137 MainFPM.addPass(InstCombinePass());
1138 MainFPM.addPass(SimplifyCFGPass());
1139 MainFPM.addPass(SCCPPass());
1140 MainFPM.addPass(InstCombinePass());
1141 MainFPM.addPass(BDCEPass());
1142
1143 // FIXME: We may want to run SLPVectorizer here.
1144 // After vectorization, assume intrinsics may tell us more
1145 // about pointer alignments.
1146#if 0
1147 MainFPM.add(AlignmentFromAssumptionsPass());
1148#endif
1149
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001150 // FIXME: Conditionally run LoadCombine here, after it's ported
1151 // (in case we still have this pass, given its questionable usefulness).
1152
Davide Italiano089a9122017-01-24 00:57:39 +00001153 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001154 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001155 MainFPM.addPass(JumpThreadingPass());
1156 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1157
1158 // Create a function that performs CFI checks for cross-DSO calls with
1159 // targets in the current module.
1160 MPM.addPass(CrossDSOCFIPass());
1161
1162 // Lower type metadata and the type.test intrinsic. This pass supports
1163 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1164 // to be run at link time if CFI is enabled. This pass does nothing if
1165 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001166 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001167
1168 // Add late LTO optimization passes.
1169 // Delete basic blocks, which optimization passes may have killed.
1170 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1171
1172 // Drop bodies of available eternally objects to improve GlobalDCE.
1173 MPM.addPass(EliminateAvailableExternallyPass());
1174
1175 // Now that we have optimized the program, discard unreachable functions.
1176 MPM.addPass(GlobalDCEPass());
1177
1178 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001179 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001180}
1181
Chandler Carruth060ad612016-12-23 20:38:19 +00001182AAManager PassBuilder::buildDefaultAAPipeline() {
1183 AAManager AA;
1184
1185 // The order in which these are registered determines their priority when
1186 // being queried.
1187
1188 // First we register the basic alias analysis that provides the majority of
1189 // per-function local AA logic. This is a stateless, on-demand local set of
1190 // AA techniques.
1191 AA.registerFunctionAnalysis<BasicAA>();
1192
1193 // Next we query fast, specialized alias analyses that wrap IR-embedded
1194 // information about aliasing.
1195 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1196 AA.registerFunctionAnalysis<TypeBasedAA>();
1197
1198 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001199 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1200 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001201 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001202 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001203
1204 return AA;
1205}
1206
Chandler Carruth241bf242016-08-03 07:44:48 +00001207static Optional<int> parseRepeatPassName(StringRef Name) {
1208 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1209 return None;
1210 int Count;
1211 if (Name.getAsInteger(0, Count) || Count <= 0)
1212 return None;
1213 return Count;
1214}
1215
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001216static Optional<int> parseDevirtPassName(StringRef Name) {
1217 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1218 return None;
1219 int Count;
1220 if (Name.getAsInteger(0, Count) || Count <= 0)
1221 return None;
1222 return Count;
1223}
1224
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001225/// Tests whether a pass name starts with a valid prefix for a default pipeline
1226/// alias.
1227static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1228 return Name.startswith("default") || Name.startswith("thinlto") ||
1229 Name.startswith("lto");
1230}
1231
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001232/// Tests whether registered callbacks will accept a given pass name.
1233///
1234/// When parsing a pipeline text, the type of the outermost pipeline may be
1235/// omitted, in which case the type is automatically determined from the first
1236/// pass name in the text. This may be a name that is handled through one of the
1237/// callbacks. We check this through the oridinary parsing callbacks by setting
1238/// up a dummy PassManager in order to not force the client to also handle this
1239/// type of query.
1240template <typename PassManagerT, typename CallbacksT>
1241static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1242 if (!Callbacks.empty()) {
1243 PassManagerT DummyPM;
1244 for (auto &CB : Callbacks)
1245 if (CB(Name, DummyPM, {}))
1246 return true;
1247 }
1248 return false;
1249}
1250
1251template <typename CallbacksT>
1252static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001253 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001254 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001255 return DefaultAliasRegex.match(Name);
1256
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001257 // Explicitly handle pass manager names.
1258 if (Name == "module")
1259 return true;
1260 if (Name == "cgscc")
1261 return true;
1262 if (Name == "function")
1263 return true;
1264
Chandler Carruth241bf242016-08-03 07:44:48 +00001265 // Explicitly handle custom-parsed pass names.
1266 if (parseRepeatPassName(Name))
1267 return true;
1268
Chandler Carruth74a8a222016-06-17 07:15:29 +00001269#define MODULE_PASS(NAME, CREATE_PASS) \
1270 if (Name == NAME) \
1271 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001272#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001273 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001274 return true;
1275#include "PassRegistry.def"
1276
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001277 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001278}
1279
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001280template <typename CallbacksT>
1281static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001282 // Explicitly handle pass manager names.
1283 if (Name == "cgscc")
1284 return true;
1285 if (Name == "function")
1286 return true;
1287
Chandler Carruth241bf242016-08-03 07:44:48 +00001288 // Explicitly handle custom-parsed pass names.
1289 if (parseRepeatPassName(Name))
1290 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001291 if (parseDevirtPassName(Name))
1292 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001293
Chandler Carruth74a8a222016-06-17 07:15:29 +00001294#define CGSCC_PASS(NAME, CREATE_PASS) \
1295 if (Name == NAME) \
1296 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001297#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001298 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001299 return true;
1300#include "PassRegistry.def"
1301
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001302 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001303}
1304
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001305template <typename CallbacksT>
1306static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001307 // Explicitly handle pass manager names.
1308 if (Name == "function")
1309 return true;
1310 if (Name == "loop")
1311 return true;
1312
Chandler Carruth241bf242016-08-03 07:44:48 +00001313 // Explicitly handle custom-parsed pass names.
1314 if (parseRepeatPassName(Name))
1315 return true;
1316
Chandler Carruth74a8a222016-06-17 07:15:29 +00001317#define FUNCTION_PASS(NAME, CREATE_PASS) \
1318 if (Name == NAME) \
1319 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001320#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001321 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001322 return true;
1323#include "PassRegistry.def"
1324
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001325 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001326}
1327
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001328template <typename CallbacksT>
1329static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001330 // Explicitly handle pass manager names.
1331 if (Name == "loop")
1332 return true;
1333
Chandler Carruth241bf242016-08-03 07:44:48 +00001334 // Explicitly handle custom-parsed pass names.
1335 if (parseRepeatPassName(Name))
1336 return true;
1337
Chandler Carruth74a8a222016-06-17 07:15:29 +00001338#define LOOP_PASS(NAME, CREATE_PASS) \
1339 if (Name == NAME) \
1340 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001341#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1342 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1343 return true;
1344#include "PassRegistry.def"
1345
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001346 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001347}
1348
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001349Optional<std::vector<PassBuilder::PipelineElement>>
1350PassBuilder::parsePipelineText(StringRef Text) {
1351 std::vector<PipelineElement> ResultPipeline;
1352
1353 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1354 &ResultPipeline};
1355 for (;;) {
1356 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1357 size_t Pos = Text.find_first_of(",()");
1358 Pipeline.push_back({Text.substr(0, Pos), {}});
1359
1360 // If we have a single terminating name, we're done.
1361 if (Pos == Text.npos)
1362 break;
1363
1364 char Sep = Text[Pos];
1365 Text = Text.substr(Pos + 1);
1366 if (Sep == ',')
1367 // Just a name ending in a comma, continue.
1368 continue;
1369
1370 if (Sep == '(') {
1371 // Push the inner pipeline onto the stack to continue processing.
1372 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1373 continue;
1374 }
1375
1376 assert(Sep == ')' && "Bogus separator!");
1377 // When handling the close parenthesis, we greedily consume them to avoid
1378 // empty strings in the pipeline.
1379 do {
1380 // If we try to pop the outer pipeline we have unbalanced parentheses.
1381 if (PipelineStack.size() == 1)
1382 return None;
1383
1384 PipelineStack.pop_back();
1385 } while (Text.consume_front(")"));
1386
1387 // Check if we've finished parsing.
1388 if (Text.empty())
1389 break;
1390
1391 // Otherwise, the end of an inner pipeline always has to be followed by
1392 // a comma, and then we can continue.
1393 if (!Text.consume_front(","))
1394 return None;
1395 }
1396
1397 if (PipelineStack.size() > 1)
1398 // Unbalanced paretheses.
1399 return None;
1400
1401 assert(PipelineStack.back() == &ResultPipeline &&
1402 "Wrong pipeline at the bottom of the stack!");
1403 return {std::move(ResultPipeline)};
1404}
1405
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001406Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1407 const PipelineElement &E,
1408 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001409 auto &Name = E.Name;
1410 auto &InnerPipeline = E.InnerPipeline;
1411
1412 // First handle complex passes like the pass managers which carry pipelines.
1413 if (!InnerPipeline.empty()) {
1414 if (Name == "module") {
1415 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001416 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1417 VerifyEachPass, DebugLogging))
1418 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001419 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001420 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001421 }
1422 if (Name == "cgscc") {
1423 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001424 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1425 DebugLogging))
1426 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001427 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001428 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001429 }
1430 if (Name == "function") {
1431 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001432 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1433 VerifyEachPass, DebugLogging))
1434 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001435 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001436 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001437 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001438 if (auto Count = parseRepeatPassName(Name)) {
1439 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001440 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1441 VerifyEachPass, DebugLogging))
1442 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001443 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001444 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001445 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001446
1447 for (auto &C : ModulePipelineParsingCallbacks)
1448 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001449 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001450
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001451 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001452 return make_error<StringError>(
1453 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1454 inconvertibleErrorCode());
1455 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001456 }
1457
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001458 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001459 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001460 SmallVector<StringRef, 3> Matches;
1461 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001462 return make_error<StringError>(
1463 formatv("unknown default pipeline alias '{0}'", Name).str(),
1464 inconvertibleErrorCode());
1465
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001466 assert(Matches.size() == 3 && "Must capture two matched strings!");
1467
Jordan Rosef85a95f2016-07-25 18:34:51 +00001468 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001469 .Case("O0", O0)
1470 .Case("O1", O1)
1471 .Case("O2", O2)
1472 .Case("O3", O3)
1473 .Case("Os", Os)
1474 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001475 if (L == O0)
1476 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001477 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001478
1479 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001480 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001481 } else if (Matches[1] == "thinlto-pre-link") {
1482 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1483 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001484 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001485 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001486 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001487 } else {
1488 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001489 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001490 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001491 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001492 }
1493
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001494 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001495#define MODULE_PASS(NAME, CREATE_PASS) \
1496 if (Name == NAME) { \
1497 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001498 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001499 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001500#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1501 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001502 MPM.addPass( \
1503 RequireAnalysisPass< \
1504 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001505 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001506 } \
1507 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001508 MPM.addPass(InvalidateAnalysisPass< \
1509 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001510 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001511 }
1512#include "PassRegistry.def"
1513
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001514 for (auto &C : ModulePipelineParsingCallbacks)
1515 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001516 return Error::success();
1517 return make_error<StringError>(
1518 formatv("unknown module pass '{0}'", Name).str(),
1519 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001520}
1521
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001522Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1523 const PipelineElement &E, bool VerifyEachPass,
1524 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001525 auto &Name = E.Name;
1526 auto &InnerPipeline = E.InnerPipeline;
1527
1528 // First handle complex passes like the pass managers which carry pipelines.
1529 if (!InnerPipeline.empty()) {
1530 if (Name == "cgscc") {
1531 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001532 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1533 VerifyEachPass, DebugLogging))
1534 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001535 // Add the nested pass manager with the appropriate adaptor.
1536 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001537 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001538 }
1539 if (Name == "function") {
1540 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001541 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1542 VerifyEachPass, DebugLogging))
1543 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001544 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001545 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001546 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001547 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001548 if (auto Count = parseRepeatPassName(Name)) {
1549 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001550 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1551 VerifyEachPass, DebugLogging))
1552 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001553 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001554 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001555 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001556 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1557 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001558 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1559 VerifyEachPass, DebugLogging))
1560 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001561 CGPM.addPass(
1562 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001563 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001564 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001565
1566 for (auto &C : CGSCCPipelineParsingCallbacks)
1567 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001568 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001569
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001570 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001571 return make_error<StringError>(
1572 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1573 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001574 }
1575
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001576// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001577#define CGSCC_PASS(NAME, CREATE_PASS) \
1578 if (Name == NAME) { \
1579 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001580 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001581 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001582#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1583 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001584 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001585 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001586 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1587 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001588 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001589 } \
1590 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001591 CGPM.addPass(InvalidateAnalysisPass< \
1592 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001593 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001594 }
1595#include "PassRegistry.def"
1596
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001597 for (auto &C : CGSCCPipelineParsingCallbacks)
1598 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001599 return Error::success();
1600 return make_error<StringError>(
1601 formatv("unknown cgscc pass '{0}'", Name).str(),
1602 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001603}
1604
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001605Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1606 const PipelineElement &E,
1607 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001608 auto &Name = E.Name;
1609 auto &InnerPipeline = E.InnerPipeline;
1610
1611 // First handle complex passes like the pass managers which carry pipelines.
1612 if (!InnerPipeline.empty()) {
1613 if (Name == "function") {
1614 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001615 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1616 VerifyEachPass, DebugLogging))
1617 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001618 // Add the nested pass manager with the appropriate adaptor.
1619 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001620 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001621 }
1622 if (Name == "loop") {
1623 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001624 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1625 DebugLogging))
1626 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001627 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001628 FPM.addPass(
1629 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001630 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001631 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001632 if (auto Count = parseRepeatPassName(Name)) {
1633 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001634 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1635 VerifyEachPass, DebugLogging))
1636 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001637 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001638 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001639 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001640
1641 for (auto &C : FunctionPipelineParsingCallbacks)
1642 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001643 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001644
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001645 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001646 return make_error<StringError>(
1647 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1648 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001649 }
1650
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001651// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001652#define FUNCTION_PASS(NAME, CREATE_PASS) \
1653 if (Name == NAME) { \
1654 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001655 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001656 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001657#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1658 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001659 FPM.addPass( \
1660 RequireAnalysisPass< \
1661 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001662 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001663 } \
1664 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001665 FPM.addPass(InvalidateAnalysisPass< \
1666 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001667 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001668 }
1669#include "PassRegistry.def"
1670
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001671 for (auto &C : FunctionPipelineParsingCallbacks)
1672 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001673 return Error::success();
1674 return make_error<StringError>(
1675 formatv("unknown function pass '{0}'", Name).str(),
1676 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001677}
1678
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001679Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1680 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001681 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001682 auto &InnerPipeline = E.InnerPipeline;
1683
1684 // First handle complex passes like the pass managers which carry pipelines.
1685 if (!InnerPipeline.empty()) {
1686 if (Name == "loop") {
1687 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001688 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1689 VerifyEachPass, DebugLogging))
1690 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001691 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001692 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001693 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001694 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001695 if (auto Count = parseRepeatPassName(Name)) {
1696 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001697 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1698 VerifyEachPass, DebugLogging))
1699 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001700 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001701 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001702 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001703
1704 for (auto &C : LoopPipelineParsingCallbacks)
1705 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001706 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001707
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001708 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001709 return make_error<StringError>(
1710 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1711 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001712 }
1713
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001714// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001715#define LOOP_PASS(NAME, CREATE_PASS) \
1716 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001717 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001718 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001719 }
1720#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1721 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001722 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001723 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1724 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1725 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001726 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001727 } \
1728 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001729 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001730 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001731 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001732 }
1733#include "PassRegistry.def"
1734
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001735 for (auto &C : LoopPipelineParsingCallbacks)
1736 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001737 return Error::success();
1738 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1739 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001740}
1741
Chandler Carruthedf59962016-02-18 09:45:17 +00001742bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001743#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1744 if (Name == NAME) { \
1745 AA.registerModuleAnalysis< \
1746 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1747 return true; \
1748 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001749#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1750 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001751 AA.registerFunctionAnalysis< \
1752 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001753 return true; \
1754 }
1755#include "PassRegistry.def"
1756
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001757 for (auto &C : AAParsingCallbacks)
1758 if (C(Name, AA))
1759 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001760 return false;
1761}
1762
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001763Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001764 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001765 bool VerifyEachPass,
1766 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001767 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001768 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1769 return Err;
1770 // FIXME: No verifier support for Loop passes!
1771 }
1772 return Error::success();
1773}
1774
1775Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1776 ArrayRef<PipelineElement> Pipeline,
1777 bool VerifyEachPass,
1778 bool DebugLogging) {
1779 for (const auto &Element : Pipeline) {
1780 if (auto Err =
1781 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1782 return Err;
1783 if (VerifyEachPass)
1784 FPM.addPass(VerifierPass());
1785 }
1786 return Error::success();
1787}
1788
1789Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1790 ArrayRef<PipelineElement> Pipeline,
1791 bool VerifyEachPass,
1792 bool DebugLogging) {
1793 for (const auto &Element : Pipeline) {
1794 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1795 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001796 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001797 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001798 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00001799}
1800
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001801void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1802 FunctionAnalysisManager &FAM,
1803 CGSCCAnalysisManager &CGAM,
1804 ModuleAnalysisManager &MAM) {
1805 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1806 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001807 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1808 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1809 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1810 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1811 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1812}
1813
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001814Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1815 ArrayRef<PipelineElement> Pipeline,
1816 bool VerifyEachPass,
1817 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001818 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001819 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1820 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001821 if (VerifyEachPass)
1822 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001823 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001824 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001825}
1826
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001827// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00001828// FIXME: Should this routine accept a TargetMachine or require the caller to
1829// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001830Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1831 StringRef PipelineText,
1832 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001833 auto Pipeline = parsePipelineText(PipelineText);
1834 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001835 return make_error<StringError>(
1836 formatv("invalid pipeline '{0}'", PipelineText).str(),
1837 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001838
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001839 // If the first name isn't at the module layer, wrap the pipeline up
1840 // automatically.
1841 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00001842
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001843 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1844 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001845 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001846 } else if (isFunctionPassName(FirstName,
1847 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001848 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001849 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001850 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001851 } else {
1852 for (auto &C : TopLevelPipelineParsingCallbacks)
1853 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001854 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001855
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001856 // Unknown pass or pipeline name!
1857 auto &InnerPipeline = Pipeline->front().InnerPipeline;
1858 return make_error<StringError>(
1859 formatv("unknown {0} name '{1}'",
1860 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1861 .str(),
1862 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001863 }
Chandler Carruth572e3402014-04-21 11:12:00 +00001864 }
1865
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001866 if (auto Err =
1867 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1868 return Err;
1869 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001870}
Chandler Carruthedf59962016-02-18 09:45:17 +00001871
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001872// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001873Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1874 StringRef PipelineText,
1875 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001876 auto Pipeline = parsePipelineText(PipelineText);
1877 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001878 return make_error<StringError>(
1879 formatv("invalid pipeline '{0}'", PipelineText).str(),
1880 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001881
1882 StringRef FirstName = Pipeline->front().Name;
1883 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001884 return make_error<StringError>(
1885 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
1886 PipelineText)
1887 .str(),
1888 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001889
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001890 if (auto Err =
1891 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
1892 return Err;
1893 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001894}
1895
1896// Primary pass pipeline description parsing routine for a \c
1897// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001898Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
1899 StringRef PipelineText,
1900 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001901 auto Pipeline = parsePipelineText(PipelineText);
1902 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001903 return make_error<StringError>(
1904 formatv("invalid pipeline '{0}'", PipelineText).str(),
1905 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001906
1907 StringRef FirstName = Pipeline->front().Name;
1908 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001909 return make_error<StringError>(
1910 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
1911 PipelineText)
1912 .str(),
1913 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001914
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001915 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
1916 DebugLogging))
1917 return Err;
1918 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001919}
1920
1921// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001922Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
1923 StringRef PipelineText,
1924 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001925 auto Pipeline = parsePipelineText(PipelineText);
1926 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001927 return make_error<StringError>(
1928 formatv("invalid pipeline '{0}'", PipelineText).str(),
1929 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001930
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001931 if (auto Err =
1932 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
1933 return Err;
1934
1935 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001936}
1937
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001938Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00001939 // If the pipeline just consists of the word 'default' just replace the AA
1940 // manager with our default one.
1941 if (PipelineText == "default") {
1942 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001943 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00001944 }
1945
Chandler Carruthedf59962016-02-18 09:45:17 +00001946 while (!PipelineText.empty()) {
1947 StringRef Name;
1948 std::tie(Name, PipelineText) = PipelineText.split(',');
1949 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001950 return make_error<StringError>(
1951 formatv("unknown alias analysis name '{0}'", Name).str(),
1952 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00001953 }
1954
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001955 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00001956}