blob: 4da8f549d9bf9c5d6c7fa8fbaee4606255e6bcd2 [file] [log] [blame]
Chandler Carruth1ff77242015-03-07 09:02:36 +00001//===- Parsing, selection, and construction of pass pipelines -------------===//
Chandler Carruth66445382014-01-11 08:16:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10///
Chandler Carruth1ff77242015-03-07 09:02:36 +000011/// This file provides the implementation of the PassBuilder based on our
12/// static pass registry as well as related functionality. It also provides
13/// helpers to aid in analyzing, debugging, and testing passes and pass
14/// pipelines.
Chandler Carruth66445382014-01-11 08:16:35 +000015///
16//===----------------------------------------------------------------------===//
17
Chandler Carruth1ff77242015-03-07 09:02:36 +000018#include "llvm/Passes/PassBuilder.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000019#include "llvm/ADT/StringSwitch.h"
Chandler Carruth6f5770b102016-02-13 23:32:00 +000020#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth4f846a52016-02-20 03:46:03 +000021#include "llvm/Analysis/AliasAnalysisEvaluator.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000022#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthbece8d52016-02-13 23:46:24 +000023#include "llvm/Analysis/BasicAliasAnalysis.h"
Xinliang David Li28a93272016-05-05 21:13:27 +000024#include "llvm/Analysis/BlockFrequencyInfo.h"
Xinliang David Li6e5dd412016-05-05 02:59:57 +000025#include "llvm/Analysis/BranchProbabilityInfo.h"
Mehdi Amini27d23792016-09-16 16:56:30 +000026#include "llvm/Analysis/CFGPrinter.h"
George Burgess IVbfa401e2016-07-06 00:26:41 +000027#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
28#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
Chandler Carruth572e3402014-04-21 11:12:00 +000029#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruth4c660f72016-03-10 11:24:11 +000030#include "llvm/Analysis/CallGraph.h"
Michael Kupersteinde16b442016-04-18 23:55:01 +000031#include "llvm/Analysis/DemandedBits.h"
Chandler Carruth49c22192016-05-12 22:19:39 +000032#include "llvm/Analysis/DependenceAnalysis.h"
Hongbin Zheng751337f2016-02-25 17:54:15 +000033#include "llvm/Analysis/DominanceFrontier.h"
Chandler Carruth45a9c202016-03-11 09:15:11 +000034#include "llvm/Analysis/GlobalsModRef.h"
Dehao Chen1a444522016-07-16 22:51:33 +000035#include "llvm/Analysis/IVUsers.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000036#include "llvm/Analysis/LazyCallGraph.h"
Sean Silva687019f2016-06-13 22:01:25 +000037#include "llvm/Analysis/LazyValueInfo.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000038#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000039#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth61440d22016-03-10 00:55:30 +000040#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000041#include "llvm/Analysis/MemorySSA.h"
Teresa Johnsonf93b2462016-08-12 13:53:02 +000042#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000043#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawnbdbbd832018-06-28 14:13:06 +000044#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng3f978402016-02-25 17:54:07 +000045#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000046#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000047#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000048#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000049#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000050#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000051#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000052#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000053#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000054#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000055#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000056#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000057#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000058#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000059#include "llvm/IR/PassManager.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000060#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000061#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000062#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000063#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000064#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000065#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000066#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000067#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000068#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000069#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000070#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000071#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000072#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000073#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000074#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000075#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000076#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000077#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000078#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000079#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000080#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000081#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000082#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000083#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000084#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000085#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000086#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000087#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000088#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000089#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000090#include "llvm/Transforms/InstCombine/InstCombine.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000091#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +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"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000134#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000135#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000136#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000137#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000138#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000139#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000140#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000141#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000142#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000143#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000144#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000145#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000146#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000147#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000148#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000149#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000150#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000151#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000152#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000153#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000154#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000155#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000156#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000157#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000158#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000159#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000160#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000161#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000162#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000163#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000164#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000165
Chandler Carruth66445382014-01-11 08:16:35 +0000166using namespace llvm;
167
Chandler Carruth719ffe12017-02-12 05:38:04 +0000168static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
169 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000170static cl::opt<bool>
171 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
172 cl::Hidden, cl::ZeroOrMore,
173 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000174
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000175static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000176 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000177 cl::Hidden, cl::ZeroOrMore,
178 cl::desc("Run NewGVN instead of GVN"));
179
Geoff Berry3cca1da2017-06-10 15:20:03 +0000180static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000181 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
182 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000183
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000184static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000185 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
186 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000187
Davide Italianobe1b6a92017-06-03 23:18:29 +0000188static cl::opt<bool> EnableGVNSink(
189 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
190 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
191
David Green963401d2018-07-01 12:47:30 +0000192static cl::opt<bool> EnableUnrollAndJam(
193 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
194 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
195
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000196static cl::opt<bool> EnableSyntheticCounts(
197 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
198 cl::desc("Run synthetic function entry count generation "
199 "pass"));
200
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000201static Regex DefaultAliasRegex(
202 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000203
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000204static cl::opt<bool>
205 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
206 cl::desc("Enable control height reduction optimization (CHR)"));
207
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000208extern cl::opt<bool> EnableHotColdSplit;
209
Chandler Carruthe3f50642016-12-22 06:59:15 +0000210static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
211 switch (Level) {
212 case PassBuilder::O0:
213 case PassBuilder::O1:
214 case PassBuilder::O2:
215 case PassBuilder::O3:
216 return false;
217
218 case PassBuilder::Os:
219 case PassBuilder::Oz:
220 return true;
221 }
222 llvm_unreachable("Invalid optimization level!");
223}
224
Chandler Carruth66445382014-01-11 08:16:35 +0000225namespace {
226
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000227/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000228struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000229 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000230 return PreservedAnalyses::all();
231 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000232 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000233};
234
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000235/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000236class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
237 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000238 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000239
240public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000241 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000242 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000243 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000244};
245
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000246/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000247struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000248 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
249 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000250 return PreservedAnalyses::all();
251 }
252 static StringRef name() { return "NoOpCGSCCPass"; }
253};
254
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000255/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000256class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
257 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000258 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000259
260public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000261 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000262 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000263 return Result();
264 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000265 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000266};
267
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000268/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000269struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000270 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000271 return PreservedAnalyses::all();
272 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000273 static StringRef name() { return "NoOpFunctionPass"; }
274};
275
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000276/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000277class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
278 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000279 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000280
281public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000282 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000283 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000284 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000285};
286
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000287/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000288struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000289 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
290 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000291 return PreservedAnalyses::all();
292 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000293 static StringRef name() { return "NoOpLoopPass"; }
294};
295
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000296/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000297class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
298 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000299 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000300
301public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000302 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000303 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
304 return Result();
305 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000306 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000307};
308
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000309AnalysisKey NoOpModuleAnalysis::Key;
310AnalysisKey NoOpCGSCCAnalysis::Key;
311AnalysisKey NoOpFunctionAnalysis::Key;
312AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000313
Chandler Carruth66445382014-01-11 08:16:35 +0000314} // End anonymous namespace.
315
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000316void PassBuilder::invokePeepholeEPCallbacks(
317 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
318 for (auto &C : PeepholeEPCallbacks)
319 C(FPM, Level);
320}
321
Chandler Carruth1ff77242015-03-07 09:02:36 +0000322void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000323#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000324 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000325#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000326
327 for (auto &C : ModuleAnalysisRegistrationCallbacks)
328 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000329}
330
Chandler Carruth1ff77242015-03-07 09:02:36 +0000331void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000332#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000333 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000334#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000335
336 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
337 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000338}
339
Chandler Carruth1ff77242015-03-07 09:02:36 +0000340void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000341#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000342 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000343#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000344
345 for (auto &C : FunctionAnalysisRegistrationCallbacks)
346 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000347}
348
Justin Bognereecc3c82016-02-25 07:23:08 +0000349void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000350#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000351 LAM.registerPass([&] { return CREATE_PASS; });
352#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000353
354 for (auto &C : LoopAnalysisRegistrationCallbacks)
355 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000356}
357
Chandler Carruthe3f50642016-12-22 06:59:15 +0000358FunctionPassManager
359PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000360 ThinLTOPhase Phase,
361 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000362 assert(Level != O0 && "Must request optimizations!");
363 FunctionPassManager FPM(DebugLogging);
364
365 // Form SSA out of local memory accesses after breaking apart aggregates into
366 // scalars.
367 FPM.addPass(SROA());
368
369 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000370 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000371
Davide Italianoc3688312017-06-01 23:08:14 +0000372 // Hoisting of scalars and load expressions.
373 if (EnableGVNHoist)
374 FPM.addPass(GVNHoistPass());
375
Davide Italianobe1b6a92017-06-03 23:18:29 +0000376 // Global value numbering based sinking.
377 if (EnableGVNSink) {
378 FPM.addPass(GVNSinkPass());
379 FPM.addPass(SimplifyCFGPass());
380 }
381
Chandler Carruthe3f50642016-12-22 06:59:15 +0000382 // Speculative execution if the target has divergent branches; otherwise nop.
383 FPM.addPass(SpeculativeExecutionPass());
384
385 // Optimize based on known information about branches, and cleanup afterward.
386 FPM.addPass(JumpThreadingPass());
387 FPM.addPass(CorrelatedValuePropagationPass());
388 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000389 if (Level == O3)
390 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000391 FPM.addPass(InstCombinePass());
392
393 if (!isOptimizingForSize(Level))
394 FPM.addPass(LibCallsShrinkWrapPass());
395
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000396 invokePeepholeEPCallbacks(FPM, Level);
397
Rong Xue1f42452017-10-23 22:21:29 +0000398 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
399 // using the size value profile. Don't perform this when optimizing for size.
400 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
401 !isOptimizingForSize(Level))
402 FPM.addPass(PGOMemOPSizeOpt());
403
Chandler Carruthe3f50642016-12-22 06:59:15 +0000404 FPM.addPass(TailCallElimPass());
405 FPM.addPass(SimplifyCFGPass());
406
407 // Form canonically associated expression trees, and simplify the trees using
408 // basic mathematical properties. For example, this will form (nearly)
409 // minimal multiplication trees.
410 FPM.addPass(ReassociatePass());
411
412 // Add the primary loop simplification pipeline.
413 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000414 // some function passes in between them. These can and should be removed
415 // and/or replaced by scheduling the loop pass equivalents in the correct
416 // positions. But those equivalent passes aren't powerful enough yet.
417 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
418 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
419 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
420 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000421 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
422
Chandler Carruth71fd2702018-05-30 02:46:45 +0000423 // Simplify the loop body. We do this initially to clean up after other loop
424 // passes run, either when iterating on a loop or on inner loops with
425 // implications on the outer loop.
426 LPM1.addPass(LoopInstSimplifyPass());
427 LPM1.addPass(LoopSimplifyCFGPass());
428
Chandler Carruthe3f50642016-12-22 06:59:15 +0000429 // Rotate Loop - disable header duplication at -Oz
430 LPM1.addPass(LoopRotatePass(Level != Oz));
431 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000432 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000433 LPM2.addPass(IndVarSimplifyPass());
434 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000435
436 for (auto &C : LateLoopOptimizationsEPCallbacks)
437 C(LPM2, Level);
438
Chandler Carruth79b733b2017-01-26 23:21:17 +0000439 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000440 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000441 // because it changes IR to makes profile annotation in back compile
442 // inaccurate.
Dehao Chen95f00302017-07-30 04:55:39 +0000443 if (Phase != ThinLTOPhase::PreLink ||
444 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnsonecd90132017-08-02 20:35:29 +0000445 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000446
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000447 for (auto &C : LoopOptimizerEndEPCallbacks)
448 C(LPM2, Level);
449
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000450 // We provide the opt remark emitter pass for LICM to use. We only need to do
451 // this once as it is immutable.
452 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000453 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000454 FPM.addPass(SimplifyCFGPass());
455 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000456 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000457
458 // Eliminate redundancies.
459 if (Level != O1) {
460 // These passes add substantial compile time so skip them at O1.
461 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000462 if (RunNewGVN)
463 FPM.addPass(NewGVNPass());
464 else
465 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000466 }
467
468 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
469 FPM.addPass(MemCpyOptPass());
470
471 // Sparse conditional constant propagation.
472 // FIXME: It isn't clear why we do this *after* loop passes rather than
473 // before...
474 FPM.addPass(SCCPPass());
475
476 // Delete dead bit computations (instcombine runs after to fold away the dead
477 // computations, and then ADCE will run later to exploit any new DCE
478 // opportunities that creates).
479 FPM.addPass(BDCEPass());
480
481 // Run instcombine after redundancy and dead bit elimination to exploit
482 // opportunities opened up by them.
483 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000484 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000485
486 // Re-consider control flow based optimizations after redundancy elimination,
487 // redo DCE, etc.
488 FPM.addPass(JumpThreadingPass());
489 FPM.addPass(CorrelatedValuePropagationPass());
490 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000491 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000492
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000493 for (auto &C : ScalarOptimizerLateEPCallbacks)
494 C(FPM, Level);
495
Chandler Carruthe3f50642016-12-22 06:59:15 +0000496 // Finally, do an expensive DCE pass to catch all the dead code exposed by
497 // the simplifications and basic cleanup after all the simplifications.
498 FPM.addPass(ADCEPass());
499 FPM.addPass(SimplifyCFGPass());
500 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000501 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000502
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000503 if (EnableCHR && Level == O3 && PGOOpt &&
504 (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty()))
505 FPM.addPass(ControlHeightReductionPass());
506
Chandler Carruthe3f50642016-12-22 06:59:15 +0000507 return FPM;
508}
509
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000510void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
511 PassBuilder::OptimizationLevel Level,
512 bool RunProfileGen,
513 std::string ProfileGenFile,
Richard Smith6c676622018-10-10 23:13:47 +0000514 std::string ProfileUseFile,
515 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000516 // Generally running simplification passes and the inliner with an high
517 // threshold results in smaller executables, but there may be cases where
518 // the size grows, so let's be conservative here and skip this simplification
519 // at -Os/Oz.
520 if (!isOptimizingForSize(Level)) {
521 InlineParams IP;
522
523 // In the old pass manager, this is a cl::opt. Should still this be one?
524 IP.DefaultThreshold = 75;
525
526 // FIXME: The hint threshold has the same value used by the regular inliner.
527 // This should probably be lowered after performance testing.
528 // FIXME: this comment is cargo culted from the old pass manager, revisit).
529 IP.HintThreshold = 325;
530
531 CGSCCPassManager CGPipeline(DebugLogging);
532
533 CGPipeline.addPass(InlinerPass(IP));
534
535 FunctionPassManager FPM;
536 FPM.addPass(SROA());
537 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
538 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
539 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000540 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000541
Davide Italiano513dfaa2017-02-13 15:26:22 +0000542 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
543
544 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
545 }
546
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000547 // Delete anything that is now dead to make sure that we don't instrument
548 // dead code. Instrumentation can end up keeping dead code around and
549 // dramatically increase code size.
550 MPM.addPass(GlobalDCEPass());
551
Davide Italiano513dfaa2017-02-13 15:26:22 +0000552 if (RunProfileGen) {
553 MPM.addPass(PGOInstrumentationGen());
554
Xinliang David Lib67530e2017-06-25 00:26:43 +0000555 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000556 FPM.addPass(
557 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000558 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
559
Davide Italiano513dfaa2017-02-13 15:26:22 +0000560 // Add the profile lowering pass.
561 InstrProfOptions Options;
562 if (!ProfileGenFile.empty())
563 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000564 Options.DoCounterPromotion = true;
Davide Italiano513dfaa2017-02-13 15:26:22 +0000565 MPM.addPass(InstrProfiling(Options));
566 }
567
568 if (!ProfileUseFile.empty())
Richard Smith6c676622018-10-10 23:13:47 +0000569 MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000570}
571
Easwaran Raman8249fac2017-06-28 13:33:49 +0000572static InlineParams
573getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
574 auto O3 = PassBuilder::O3;
575 unsigned OptLevel = Level > O3 ? 2 : Level;
576 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
577 return getInlineParams(OptLevel, SizeLevel);
578}
579
Chandler Carruthe3f50642016-12-22 06:59:15 +0000580ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000581PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000582 ThinLTOPhase Phase,
583 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000584 ModulePassManager MPM(DebugLogging);
585
Chandler Carruthe3f50642016-12-22 06:59:15 +0000586 // Do basic inference of function attributes from known properties of system
587 // libraries and other oracles.
588 MPM.addPass(InferFunctionAttrsPass());
589
590 // Create an early function pass manager to cleanup the output of the
591 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000592 FunctionPassManager EarlyFPM(DebugLogging);
593 EarlyFPM.addPass(SimplifyCFGPass());
594 EarlyFPM.addPass(SROA());
595 EarlyFPM.addPass(EarlyCSEPass());
596 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000597 if (Level == O3)
598 EarlyFPM.addPass(CallSiteSplittingPass());
599
Dehao Chen08f88312017-08-07 20:23:20 +0000600 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
601 // to convert bitcast to direct calls so that they can be inlined during the
602 // profile annotation prepration step.
603 // More details about SamplePGO design can be found in:
604 // https://research.google.com/pubs/pub45290.html
605 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
606 if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
607 Phase == ThinLTOPhase::PostLink)
608 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000609 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000610
Dehao Chen08f88312017-08-07 20:23:20 +0000611 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
612 // Annotate sample profile right after early FPM to ensure freshness of
613 // the debug info.
Dehao Chend26dae02017-10-01 05:24:51 +0000614 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000615 PGOOpt->ProfileRemappingFile,
Dehao Chend26dae02017-10-01 05:24:51 +0000616 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000617 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
618 // for the profile annotation to be accurate in the ThinLTO backend.
619 if (Phase != ThinLTOPhase::PreLink)
620 // We perform early indirect call promotion here, before globalopt.
621 // This is important for the ThinLTO backend phase because otherwise
622 // imported available_externally functions look unreferenced and are
623 // removed.
624 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
625 true));
626 }
627
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000628 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000629 // and prior to optimizing globals.
630 // FIXME: This position in the pipeline hasn't been carefully considered in
631 // years, it should be re-analyzed.
632 MPM.addPass(IPSCCPPass());
633
Matthew Simpsoncb585582017-10-25 13:40:08 +0000634 // Attach metadata to indirect call sites indicating the set of functions
635 // they may target at run-time. This should follow IPSCCP.
636 MPM.addPass(CalledValuePropagationPass());
637
Chandler Carruthe3f50642016-12-22 06:59:15 +0000638 // Optimize globals to try and fold them into constants.
639 MPM.addPass(GlobalOptPass());
640
641 // Promote any localized globals to SSA registers.
642 // FIXME: Should this instead by a run of SROA?
643 // FIXME: We should probably run instcombine and simplify-cfg afterward to
644 // delete control flows that are dead once globals have been folded to
645 // constants.
646 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
647
648 // Remove any dead arguments exposed by cleanups and constand folding
649 // globals.
650 MPM.addPass(DeadArgumentEliminationPass());
651
652 // Create a small function pass pipeline to cleanup after all the global
653 // optimizations.
654 FunctionPassManager GlobalCleanupPM(DebugLogging);
655 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000656 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
657
Chandler Carruthe3f50642016-12-22 06:59:15 +0000658 GlobalCleanupPM.addPass(SimplifyCFGPass());
659 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
660
Dehao Chen89d32262017-08-02 01:28:31 +0000661 // Add all the requested passes for instrumentation PGO, if requested.
662 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
663 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
664 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
Richard Smith6c676622018-10-10 23:13:47 +0000665 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
666 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000667 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000668 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000669
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000670 // Synthesize function entry counts for non-PGO compilation.
671 if (EnableSyntheticCounts && !PGOOpt)
672 MPM.addPass(SyntheticCountsPropagation());
673
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000674 // Require the GlobalsAA analysis for the module so we can query it within
675 // the CGSCC pipeline.
676 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000677
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000678 // Require the ProfileSummaryAnalysis for the module so we can query it within
679 // the inliner pass.
680 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
681
Chandler Carruthe3f50642016-12-22 06:59:15 +0000682 // Now begin the main postorder CGSCC pipeline.
683 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
684 // manager and trying to emulate its precise behavior. Much of this doesn't
685 // make a lot of sense and we should revisit the core CGSCC structure.
686 CGSCCPassManager MainCGPipeline(DebugLogging);
687
688 // Note: historically, the PruneEH pass was run first to deduce nounwind and
689 // generally clean up exception handling overhead. It isn't clear this is
690 // valuable as the inliner doesn't currently care whether it is inlining an
691 // invoke or a call.
692
693 // Run the inliner first. The theory is that we are walking bottom-up and so
694 // the callees have already been fully optimized, and we want to inline them
695 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000696 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000697 // because it makes profile annotation in the backend inaccurate.
698 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000699 if (Phase == ThinLTOPhase::PreLink &&
700 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000701 IP.HotCallSiteThreshold = 0;
702 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000703
704 // Now deduce any function attributes based in the current code.
705 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
706
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000707 // When at O3 add argument promotion to the pass pipeline.
708 // FIXME: It isn't at all clear why this should be limited to O3.
709 if (Level == O3)
710 MainCGPipeline.addPass(ArgumentPromotionPass());
711
Chandler Carruthe3f50642016-12-22 06:59:15 +0000712 // Lastly, add the core function simplification pipeline nested inside the
713 // CGSCC walk.
714 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000715 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000716
Teresa Johnsond7253352018-10-23 22:57:40 +0000717 // We only want to do hot cold splitting once for ThinLTO, during the
718 // post-link ThinLTO.
719 if (EnableHotColdSplit && Phase != ThinLTOPhase::PreLink)
Aditya Kumard9e2e382018-10-21 18:11:56 +0000720 MPM.addPass(HotColdSplittingPass());
721
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000722 for (auto &C : CGSCCOptimizerLateEPCallbacks)
723 C(MainCGPipeline, Level);
724
Chandler Carruth719ffe12017-02-12 05:38:04 +0000725 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
726 // to detect when we devirtualize indirect calls and iterate the SCC passes
727 // in that case to try and catch knock-on inlining or function attrs
728 // opportunities. Then we add it to the module pipeline by walking the SCCs
729 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000730 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000731 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000732 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000733
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000734 return MPM;
735}
736
737ModulePassManager
738PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
739 bool DebugLogging) {
740 ModulePassManager MPM(DebugLogging);
741
742 // Optimize globals now that the module is fully simplified.
743 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000744 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000745
Xinliang David Li126157c2017-05-22 16:41:57 +0000746 // Run partial inlining pass to partially inline functions that have
747 // large bodies.
748 if (RunPartialInlining)
749 MPM.addPass(PartialInlinerPass());
750
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000751 // Remove avail extern fns and globals definitions since we aren't compiling
752 // an object file for later LTO. For LTO we want to preserve these so they
753 // are eligible for inlining at link-time. Note if they are unreferenced they
754 // will be removed by GlobalDCE later, so this only impacts referenced
755 // available externally globals. Eventually they will be suppressed during
756 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
757 // may make globals referenced by available external functions dead and saves
758 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000759 MPM.addPass(EliminateAvailableExternallyPass());
760
761 // Do RPO function attribute inference across the module to forward-propagate
762 // attributes where applicable.
763 // FIXME: Is this really an optimization rather than a canonicalization?
764 MPM.addPass(ReversePostOrderFunctionAttrsPass());
765
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000766 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000767 // useful as the above will have inlined, DCE'ed, and function-attr
768 // propagated everything. We should at this point have a reasonably minimal
769 // and richly annotated call graph. By computing aliasing and mod/ref
770 // information for all local globals here, the late loop passes and notably
771 // the vectorizer will be able to use them to help recognize vectorizable
772 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000773 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000774
775 FunctionPassManager OptimizePM(DebugLogging);
776 OptimizePM.addPass(Float2IntPass());
777 // FIXME: We need to run some loop optimizations to re-rotate loops after
778 // simplify-cfg and others undo their rotation.
779
780 // Optimize the loop execution. These passes operate on entire loop nests
781 // rather than on each loop in an inside-out manner, and so they are actually
782 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000783
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000784 for (auto &C : VectorizerStartEPCallbacks)
785 C(OptimizePM, Level);
786
Chandler Carrutha95ff382017-01-27 00:50:21 +0000787 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000788 OptimizePM.addPass(
789 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000790
791 // Distribute loops to allow partial vectorization. I.e. isolate dependences
792 // into separate loop that would otherwise inhibit vectorization. This is
793 // currently only performed for loops marked with the metadata
794 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000795 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000796
797 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000798 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000799
Chandler Carruthbaabda92017-01-27 01:32:26 +0000800 // Eliminate loads by forwarding stores from the previous iteration to loads
801 // of the current iteration.
802 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000803
804 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000805 OptimizePM.addPass(InstCombinePass());
806
Chandler Carrutha95ff382017-01-27 00:50:21 +0000807 // Now that we've formed fast to execute loop structures, we do further
808 // optimizations. These are run afterward as they might block doing complex
809 // analyses and transforms such as what are needed for loop vectorization.
810
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000811 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
812 // GVN, loop transforms, and others have already run, so it's now better to
813 // convert to more optimized IR using more aggressive simplify CFG options.
814 // The extra sinking transform can create larger basic blocks, so do this
815 // before SLP vectorization.
816 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
817 forwardSwitchCondToPhi(true).
818 convertSwitchToLookupTable(true).
819 needCanonicalLoops(false).
820 sinkCommonInsts(true)));
821
Chandler Carruthe3f50642016-12-22 06:59:15 +0000822 // Optimize parallel scalar instruction chains into SIMD instructions.
823 OptimizePM.addPass(SLPVectorizerPass());
824
Chandler Carruthe3f50642016-12-22 06:59:15 +0000825 OptimizePM.addPass(InstCombinePass());
826
827 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000828 // execution resources of an out-of-order processor. We also then need to
829 // clean up redundancies and loop invariant code.
830 // FIXME: It would be really good to use a loop-integrated instruction
831 // combiner for cleanup here so that the unrolling and LICM can be pipelined
832 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000833 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
834 if (EnableUnrollAndJam) {
835 OptimizePM.addPass(
836 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
837 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000838 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000839 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000840 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000841 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000842 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000843
844 // Now that we've vectorized and unrolled loops, we may have more refined
845 // alignment information, try to re-derive it here.
846 OptimizePM.addPass(AlignmentFromAssumptionsPass());
847
Chandler Carrutha95ff382017-01-27 00:50:21 +0000848 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
849 // canonicalization pass that enables other optimizations. As a result,
850 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
851 // result too early.
852 OptimizePM.addPass(LoopSinkPass());
853
854 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000855 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000856
Sanjay Patel6fd43912017-09-09 13:38:18 +0000857 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
858 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
859 // flattening of blocks.
860 OptimizePM.addPass(DivRemPairsPass());
861
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000862 // LoopSink (and other loop passes since the last simplifyCFG) might have
863 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
864 OptimizePM.addPass(SimplifyCFGPass());
865
Chandler Carruthc34f7892017-11-28 11:32:31 +0000866 // Optimize PHIs by speculating around them when profitable. Note that this
867 // pass needs to be run after any PRE or similar pass as it is essentially
868 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
869 OptimizePM.addPass(SpeculateAroundPHIsPass());
870
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000871 for (auto &C : OptimizerLastEPCallbacks)
872 C(OptimizePM, Level);
873
Chandler Carrutha95ff382017-01-27 00:50:21 +0000874 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000875 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
876
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000877 MPM.addPass(CGProfilePass());
878
Chandler Carruthe3f50642016-12-22 06:59:15 +0000879 // Now we need to do some global optimization transforms.
880 // FIXME: It would seem like these should come first in the optimization
881 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
882 // ordering here.
883 MPM.addPass(GlobalDCEPass());
884 MPM.addPass(ConstantMergePass());
885
886 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000887}
888
Chandler Carruthe3f50642016-12-22 06:59:15 +0000889ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000890PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
891 bool DebugLogging) {
892 assert(Level != O0 && "Must request optimizations for the default pipeline!");
893
894 ModulePassManager MPM(DebugLogging);
895
896 // Force any function attributes we want the rest of the pipeline to observe.
897 MPM.addPass(ForceFunctionAttrsPass());
898
David Blaikie0c64f5a2018-01-23 01:25:20 +0000899 // Apply module pipeline start EP callback.
900 for (auto &C : PipelineStartEPCallbacks)
901 C(MPM);
902
Dehao Chen08f88312017-08-07 20:23:20 +0000903 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000904 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
905
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000906 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000907 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
908 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000909
910 // Now add the optimization pipeline.
911 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
912
913 return MPM;
914}
915
916ModulePassManager
917PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
918 bool DebugLogging) {
919 assert(Level != O0 && "Must request optimizations for the default pipeline!");
920
921 ModulePassManager MPM(DebugLogging);
922
923 // Force any function attributes we want the rest of the pipeline to observe.
924 MPM.addPass(ForceFunctionAttrsPass());
925
Dehao Chen08f88312017-08-07 20:23:20 +0000926 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000927 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
928
David Blaikie0c64f5a2018-01-23 01:25:20 +0000929 // Apply module pipeline start EP callback.
930 for (auto &C : PipelineStartEPCallbacks)
931 C(MPM);
932
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000933 // If we are planning to perform ThinLTO later, we don't bloat the code with
934 // unrolling/vectorization/... now. Just simplify the module as much as we
935 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000936 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
937 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000938
939 // Run partial inlining pass to partially inline functions that have
940 // large bodies.
941 // FIXME: It isn't clear whether this is really the right place to run this
942 // in ThinLTO. Because there is another canonicalization and simplification
943 // phase that will run after the thin link, running this here ends up with
944 // less information than will be available later and it may grow functions in
945 // ways that aren't beneficial.
946 if (RunPartialInlining)
947 MPM.addPass(PartialInlinerPass());
948
949 // Reduce the size of the IR as much as possible.
950 MPM.addPass(GlobalOptPass());
951
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000952 return MPM;
953}
954
Teresa Johnson28023db2018-07-19 14:51:32 +0000955ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
956 OptimizationLevel Level, bool DebugLogging,
957 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000958 ModulePassManager MPM(DebugLogging);
959
Teresa Johnson28023db2018-07-19 14:51:32 +0000960 if (ImportSummary) {
961 // These passes import type identifier resolutions for whole-program
962 // devirtualization and CFI. They must run early because other passes may
963 // disturb the specific instruction patterns that these passes look for,
964 // creating dependencies on resolutions that may not appear in the summary.
965 //
966 // For example, GVN may transform the pattern assume(type.test) appearing in
967 // two basic blocks into assume(phi(type.test, type.test)), which would
968 // transform a dependency on a WPD resolution into a dependency on a type
969 // identifier resolution for CFI.
970 //
971 // Also, WPD has access to more precise information than ICP and can
972 // devirtualize more effectively, so it should operate on the IR first.
973 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
974 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
975 }
976
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000977 // Force any function attributes we want the rest of the pipeline to observe.
978 MPM.addPass(ForceFunctionAttrsPass());
979
980 // During the ThinLTO backend phase we perform early indirect call promotion
981 // here, before globalopt. Otherwise imported available_externally functions
982 // look unreferenced and are removed.
Dehao Chen08f88312017-08-07 20:23:20 +0000983 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
984 // with SamplePGO.
Dehao Chen2f4e2e22017-08-10 05:10:32 +0000985 if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
Dehao Chen08f88312017-08-07 20:23:20 +0000986 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
987 false /* SamplePGO */));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000988
989 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000990 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
991 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000992
993 // Now add the optimization pipeline.
994 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
995
996 return MPM;
997}
998
999ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001000PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1001 bool DebugLogging) {
1002 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001003 // FIXME: We should use a customized pre-link pipeline!
Chandler Carruthe3f50642016-12-22 06:59:15 +00001004 return buildPerModuleDefaultPipeline(Level, DebugLogging);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001005}
1006
Teresa Johnson28023db2018-07-19 14:51:32 +00001007ModulePassManager
1008PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1009 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001010 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1011 ModulePassManager MPM(DebugLogging);
1012
Xin Tong642c8d32018-11-15 18:06:42 +00001013 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
1014 // Load sample profile before running the LTO optimization pipeline.
1015 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
1016 PGOOpt->ProfileRemappingFile,
1017 false /* ThinLTOPhase::PreLink */));
1018 }
1019
Davide Italiano089a9122017-01-24 00:57:39 +00001020 // Remove unused virtual tables to improve the quality of code generated by
1021 // whole-program devirtualization and bitset lowering.
1022 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001023
Davide Italiano089a9122017-01-24 00:57:39 +00001024 // Force any function attributes we want the rest of the pipeline to observe.
1025 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001026
Davide Italiano089a9122017-01-24 00:57:39 +00001027 // Do basic inference of function attributes from known properties of system
1028 // libraries and other oracles.
1029 MPM.addPass(InferFunctionAttrsPass());
1030
1031 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001032 FunctionPassManager EarlyFPM(DebugLogging);
1033 EarlyFPM.addPass(CallSiteSplittingPass());
1034 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1035
Davide Italiano089a9122017-01-24 00:57:39 +00001036 // Indirect call promotion. This should promote all the targets that are
1037 // left by the earlier promotion pass that promotes intra-module targets.
1038 // This two-step promotion is to save the compile time. For LTO, it should
1039 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001040 MPM.addPass(PGOIndirectCallPromotion(
1041 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +00001042 // Propagate constants at call sites into the functions they call. This
1043 // opens opportunities for globalopt (and inlining) by substituting function
1044 // pointers passed as arguments to direct uses of functions.
1045 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001046
1047 // Attach metadata to indirect call sites indicating the set of functions
1048 // they may target at run-time. This should follow IPSCCP.
1049 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001050 }
1051
1052 // Now deduce any function attributes based in the current code.
1053 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1054 PostOrderFunctionAttrsPass()));
1055
1056 // Do RPO function attribute inference across the module to forward-propagate
1057 // attributes where applicable.
1058 // FIXME: Is this really an optimization rather than a canonicalization?
1059 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1060
1061 // Use inragne annotations on GEP indices to split globals where beneficial.
1062 MPM.addPass(GlobalSplitPass());
1063
1064 // Run whole program optimization of virtual call when the list of callees
1065 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001066 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001067
1068 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001069 if (Level == 1) {
1070 // The LowerTypeTestsPass needs to run to lower type metadata and the
1071 // type.test intrinsics. The pass does nothing if CFI is disabled.
1072 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001073 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001074 }
Davide Italiano089a9122017-01-24 00:57:39 +00001075
1076 // Optimize globals to try and fold them into constants.
1077 MPM.addPass(GlobalOptPass());
1078
1079 // Promote any localized globals to SSA registers.
1080 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1081
1082 // Linking modules together can lead to duplicate global constant, only
1083 // keep one copy of each constant.
1084 MPM.addPass(ConstantMergePass());
1085
1086 // Remove unused arguments from functions.
1087 MPM.addPass(DeadArgumentEliminationPass());
1088
1089 // Reduce the code after globalopt and ipsccp. Both can open up significant
1090 // simplification opportunities, and both can propagate functions through
1091 // function pointers. When this happens, we often have to resolve varargs
1092 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001093 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001094 if (Level == O3)
1095 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001096 PeepholeFPM.addPass(InstCombinePass());
1097 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1098
1099 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001100
1101 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1102 // generally clean up exception handling overhead. It isn't clear this is
1103 // valuable as the inliner doesn't currently care whether it is inlining an
1104 // invoke or a call.
1105 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001106 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1107 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001108
1109 // Optimize globals again after we ran the inliner.
1110 MPM.addPass(GlobalOptPass());
1111
1112 // Garbage collect dead functions.
1113 // FIXME: Add ArgumentPromotion pass after once it's ported.
1114 MPM.addPass(GlobalDCEPass());
1115
1116 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001117 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001118 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001119 invokePeepholeEPCallbacks(FPM, Level);
1120
Davide Italiano089a9122017-01-24 00:57:39 +00001121 FPM.addPass(JumpThreadingPass());
1122
1123 // Break up allocas
1124 FPM.addPass(SROA());
1125
1126 // Run a few AA driver optimizations here and now to cleanup the code.
1127 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1128
1129 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1130 PostOrderFunctionAttrsPass()));
1131 // FIXME: here we run IP alias analysis in the legacy PM.
1132
1133 FunctionPassManager MainFPM;
1134
1135 // FIXME: once we fix LoopPass Manager, add LICM here.
1136 // FIXME: once we provide support for enabling MLSM, add it here.
1137 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001138 if (RunNewGVN)
1139 MainFPM.addPass(NewGVNPass());
1140 else
1141 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001142
1143 // Remove dead memcpy()'s.
1144 MainFPM.addPass(MemCpyOptPass());
1145
1146 // Nuke dead stores.
1147 MainFPM.addPass(DSEPass());
1148
1149 // FIXME: at this point, we run a bunch of loop passes:
1150 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1151 // loopVectorize. Enable them once the remaining issue with LPM
1152 // are sorted out.
1153
1154 MainFPM.addPass(InstCombinePass());
1155 MainFPM.addPass(SimplifyCFGPass());
1156 MainFPM.addPass(SCCPPass());
1157 MainFPM.addPass(InstCombinePass());
1158 MainFPM.addPass(BDCEPass());
1159
1160 // FIXME: We may want to run SLPVectorizer here.
1161 // After vectorization, assume intrinsics may tell us more
1162 // about pointer alignments.
1163#if 0
1164 MainFPM.add(AlignmentFromAssumptionsPass());
1165#endif
1166
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001167 // FIXME: Conditionally run LoadCombine here, after it's ported
1168 // (in case we still have this pass, given its questionable usefulness).
1169
Davide Italiano089a9122017-01-24 00:57:39 +00001170 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001171 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001172 MainFPM.addPass(JumpThreadingPass());
1173 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1174
1175 // Create a function that performs CFI checks for cross-DSO calls with
1176 // targets in the current module.
1177 MPM.addPass(CrossDSOCFIPass());
1178
1179 // Lower type metadata and the type.test intrinsic. This pass supports
1180 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1181 // to be run at link time if CFI is enabled. This pass does nothing if
1182 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001183 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001184
1185 // Add late LTO optimization passes.
1186 // Delete basic blocks, which optimization passes may have killed.
1187 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1188
1189 // Drop bodies of available eternally objects to improve GlobalDCE.
1190 MPM.addPass(EliminateAvailableExternallyPass());
1191
1192 // Now that we have optimized the program, discard unreachable functions.
1193 MPM.addPass(GlobalDCEPass());
1194
1195 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001196 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001197}
1198
Chandler Carruth060ad612016-12-23 20:38:19 +00001199AAManager PassBuilder::buildDefaultAAPipeline() {
1200 AAManager AA;
1201
1202 // The order in which these are registered determines their priority when
1203 // being queried.
1204
1205 // First we register the basic alias analysis that provides the majority of
1206 // per-function local AA logic. This is a stateless, on-demand local set of
1207 // AA techniques.
1208 AA.registerFunctionAnalysis<BasicAA>();
1209
1210 // Next we query fast, specialized alias analyses that wrap IR-embedded
1211 // information about aliasing.
1212 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1213 AA.registerFunctionAnalysis<TypeBasedAA>();
1214
1215 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001216 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1217 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001218 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001219 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001220
1221 return AA;
1222}
1223
Chandler Carruth241bf242016-08-03 07:44:48 +00001224static Optional<int> parseRepeatPassName(StringRef Name) {
1225 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1226 return None;
1227 int Count;
1228 if (Name.getAsInteger(0, Count) || Count <= 0)
1229 return None;
1230 return Count;
1231}
1232
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001233static Optional<int> parseDevirtPassName(StringRef Name) {
1234 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1235 return None;
1236 int Count;
1237 if (Name.getAsInteger(0, Count) || Count <= 0)
1238 return None;
1239 return Count;
1240}
1241
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001242/// Tests whether a pass name starts with a valid prefix for a default pipeline
1243/// alias.
1244static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1245 return Name.startswith("default") || Name.startswith("thinlto") ||
1246 Name.startswith("lto");
1247}
1248
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001249/// Tests whether registered callbacks will accept a given pass name.
1250///
1251/// When parsing a pipeline text, the type of the outermost pipeline may be
1252/// omitted, in which case the type is automatically determined from the first
1253/// pass name in the text. This may be a name that is handled through one of the
1254/// callbacks. We check this through the oridinary parsing callbacks by setting
1255/// up a dummy PassManager in order to not force the client to also handle this
1256/// type of query.
1257template <typename PassManagerT, typename CallbacksT>
1258static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1259 if (!Callbacks.empty()) {
1260 PassManagerT DummyPM;
1261 for (auto &CB : Callbacks)
1262 if (CB(Name, DummyPM, {}))
1263 return true;
1264 }
1265 return false;
1266}
1267
1268template <typename CallbacksT>
1269static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001270 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001271 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001272 return DefaultAliasRegex.match(Name);
1273
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001274 // Explicitly handle pass manager names.
1275 if (Name == "module")
1276 return true;
1277 if (Name == "cgscc")
1278 return true;
1279 if (Name == "function")
1280 return true;
1281
Chandler Carruth241bf242016-08-03 07:44:48 +00001282 // Explicitly handle custom-parsed pass names.
1283 if (parseRepeatPassName(Name))
1284 return true;
1285
Chandler Carruth74a8a222016-06-17 07:15:29 +00001286#define MODULE_PASS(NAME, CREATE_PASS) \
1287 if (Name == NAME) \
1288 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001289#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001290 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001291 return true;
1292#include "PassRegistry.def"
1293
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001294 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001295}
1296
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001297template <typename CallbacksT>
1298static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001299 // Explicitly handle pass manager names.
1300 if (Name == "cgscc")
1301 return true;
1302 if (Name == "function")
1303 return true;
1304
Chandler Carruth241bf242016-08-03 07:44:48 +00001305 // Explicitly handle custom-parsed pass names.
1306 if (parseRepeatPassName(Name))
1307 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001308 if (parseDevirtPassName(Name))
1309 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001310
Chandler Carruth74a8a222016-06-17 07:15:29 +00001311#define CGSCC_PASS(NAME, CREATE_PASS) \
1312 if (Name == NAME) \
1313 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001314#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001315 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001316 return true;
1317#include "PassRegistry.def"
1318
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001319 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001320}
1321
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001322template <typename CallbacksT>
1323static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001324 // Explicitly handle pass manager names.
1325 if (Name == "function")
1326 return true;
1327 if (Name == "loop")
1328 return true;
1329
Chandler Carruth241bf242016-08-03 07:44:48 +00001330 // Explicitly handle custom-parsed pass names.
1331 if (parseRepeatPassName(Name))
1332 return true;
1333
Chandler Carruth74a8a222016-06-17 07:15:29 +00001334#define FUNCTION_PASS(NAME, CREATE_PASS) \
1335 if (Name == NAME) \
1336 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001337#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001338 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001339 return true;
1340#include "PassRegistry.def"
1341
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001342 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001343}
1344
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001345template <typename CallbacksT>
1346static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001347 // Explicitly handle pass manager names.
1348 if (Name == "loop")
1349 return true;
1350
Chandler Carruth241bf242016-08-03 07:44:48 +00001351 // Explicitly handle custom-parsed pass names.
1352 if (parseRepeatPassName(Name))
1353 return true;
1354
Chandler Carruth74a8a222016-06-17 07:15:29 +00001355#define LOOP_PASS(NAME, CREATE_PASS) \
1356 if (Name == NAME) \
1357 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001358#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1359 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1360 return true;
1361#include "PassRegistry.def"
1362
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001363 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001364}
1365
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001366Optional<std::vector<PassBuilder::PipelineElement>>
1367PassBuilder::parsePipelineText(StringRef Text) {
1368 std::vector<PipelineElement> ResultPipeline;
1369
1370 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1371 &ResultPipeline};
1372 for (;;) {
1373 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1374 size_t Pos = Text.find_first_of(",()");
1375 Pipeline.push_back({Text.substr(0, Pos), {}});
1376
1377 // If we have a single terminating name, we're done.
1378 if (Pos == Text.npos)
1379 break;
1380
1381 char Sep = Text[Pos];
1382 Text = Text.substr(Pos + 1);
1383 if (Sep == ',')
1384 // Just a name ending in a comma, continue.
1385 continue;
1386
1387 if (Sep == '(') {
1388 // Push the inner pipeline onto the stack to continue processing.
1389 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1390 continue;
1391 }
1392
1393 assert(Sep == ')' && "Bogus separator!");
1394 // When handling the close parenthesis, we greedily consume them to avoid
1395 // empty strings in the pipeline.
1396 do {
1397 // If we try to pop the outer pipeline we have unbalanced parentheses.
1398 if (PipelineStack.size() == 1)
1399 return None;
1400
1401 PipelineStack.pop_back();
1402 } while (Text.consume_front(")"));
1403
1404 // Check if we've finished parsing.
1405 if (Text.empty())
1406 break;
1407
1408 // Otherwise, the end of an inner pipeline always has to be followed by
1409 // a comma, and then we can continue.
1410 if (!Text.consume_front(","))
1411 return None;
1412 }
1413
1414 if (PipelineStack.size() > 1)
1415 // Unbalanced paretheses.
1416 return None;
1417
1418 assert(PipelineStack.back() == &ResultPipeline &&
1419 "Wrong pipeline at the bottom of the stack!");
1420 return {std::move(ResultPipeline)};
1421}
1422
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001423Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1424 const PipelineElement &E,
1425 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001426 auto &Name = E.Name;
1427 auto &InnerPipeline = E.InnerPipeline;
1428
1429 // First handle complex passes like the pass managers which carry pipelines.
1430 if (!InnerPipeline.empty()) {
1431 if (Name == "module") {
1432 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001433 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1434 VerifyEachPass, DebugLogging))
1435 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001436 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001437 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001438 }
1439 if (Name == "cgscc") {
1440 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001441 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1442 DebugLogging))
1443 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001444 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001445 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001446 }
1447 if (Name == "function") {
1448 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001449 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1450 VerifyEachPass, DebugLogging))
1451 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001452 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001453 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001454 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001455 if (auto Count = parseRepeatPassName(Name)) {
1456 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001457 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1458 VerifyEachPass, DebugLogging))
1459 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001460 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001461 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001462 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001463
1464 for (auto &C : ModulePipelineParsingCallbacks)
1465 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001466 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001467
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001468 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001469 return make_error<StringError>(
1470 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1471 inconvertibleErrorCode());
1472 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001473 }
1474
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001475 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001476 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001477 SmallVector<StringRef, 3> Matches;
1478 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001479 return make_error<StringError>(
1480 formatv("unknown default pipeline alias '{0}'", Name).str(),
1481 inconvertibleErrorCode());
1482
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001483 assert(Matches.size() == 3 && "Must capture two matched strings!");
1484
Jordan Rosef85a95f2016-07-25 18:34:51 +00001485 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001486 .Case("O0", O0)
1487 .Case("O1", O1)
1488 .Case("O2", O2)
1489 .Case("O3", O3)
1490 .Case("Os", Os)
1491 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001492 if (L == O0)
1493 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001494 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001495
1496 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001497 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001498 } else if (Matches[1] == "thinlto-pre-link") {
1499 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1500 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001501 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001502 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001503 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001504 } else {
1505 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001506 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001507 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001508 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001509 }
1510
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001511 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001512#define MODULE_PASS(NAME, CREATE_PASS) \
1513 if (Name == NAME) { \
1514 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001515 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001516 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001517#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1518 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001519 MPM.addPass( \
1520 RequireAnalysisPass< \
1521 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001522 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001523 } \
1524 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001525 MPM.addPass(InvalidateAnalysisPass< \
1526 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001527 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001528 }
1529#include "PassRegistry.def"
1530
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001531 for (auto &C : ModulePipelineParsingCallbacks)
1532 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001533 return Error::success();
1534 return make_error<StringError>(
1535 formatv("unknown module pass '{0}'", Name).str(),
1536 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001537}
1538
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001539Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1540 const PipelineElement &E, bool VerifyEachPass,
1541 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001542 auto &Name = E.Name;
1543 auto &InnerPipeline = E.InnerPipeline;
1544
1545 // First handle complex passes like the pass managers which carry pipelines.
1546 if (!InnerPipeline.empty()) {
1547 if (Name == "cgscc") {
1548 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001549 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1550 VerifyEachPass, DebugLogging))
1551 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001552 // Add the nested pass manager with the appropriate adaptor.
1553 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001554 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001555 }
1556 if (Name == "function") {
1557 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001558 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1559 VerifyEachPass, DebugLogging))
1560 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001561 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001562 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001563 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001564 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001565 if (auto Count = parseRepeatPassName(Name)) {
1566 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001567 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1568 VerifyEachPass, DebugLogging))
1569 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001570 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001571 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001572 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001573 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1574 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001575 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1576 VerifyEachPass, DebugLogging))
1577 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001578 CGPM.addPass(
1579 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001580 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001581 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001582
1583 for (auto &C : CGSCCPipelineParsingCallbacks)
1584 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001585 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001586
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001587 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001588 return make_error<StringError>(
1589 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1590 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001591 }
1592
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001593// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001594#define CGSCC_PASS(NAME, CREATE_PASS) \
1595 if (Name == NAME) { \
1596 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001597 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001598 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001599#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1600 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001601 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001602 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001603 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1604 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001605 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001606 } \
1607 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001608 CGPM.addPass(InvalidateAnalysisPass< \
1609 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001610 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001611 }
1612#include "PassRegistry.def"
1613
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001614 for (auto &C : CGSCCPipelineParsingCallbacks)
1615 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001616 return Error::success();
1617 return make_error<StringError>(
1618 formatv("unknown cgscc pass '{0}'", Name).str(),
1619 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001620}
1621
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001622Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1623 const PipelineElement &E,
1624 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001625 auto &Name = E.Name;
1626 auto &InnerPipeline = E.InnerPipeline;
1627
1628 // First handle complex passes like the pass managers which carry pipelines.
1629 if (!InnerPipeline.empty()) {
1630 if (Name == "function") {
1631 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001632 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1633 VerifyEachPass, DebugLogging))
1634 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001635 // Add the nested pass manager with the appropriate adaptor.
1636 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001637 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001638 }
1639 if (Name == "loop") {
1640 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001641 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1642 DebugLogging))
1643 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001644 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001645 FPM.addPass(
1646 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001647 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001648 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001649 if (auto Count = parseRepeatPassName(Name)) {
1650 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001651 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1652 VerifyEachPass, DebugLogging))
1653 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001654 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001655 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001656 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001657
1658 for (auto &C : FunctionPipelineParsingCallbacks)
1659 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001660 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001661
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001662 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001663 return make_error<StringError>(
1664 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1665 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001666 }
1667
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001668// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001669#define FUNCTION_PASS(NAME, CREATE_PASS) \
1670 if (Name == NAME) { \
1671 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001672 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001673 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001674#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1675 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001676 FPM.addPass( \
1677 RequireAnalysisPass< \
1678 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001679 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001680 } \
1681 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001682 FPM.addPass(InvalidateAnalysisPass< \
1683 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001684 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001685 }
1686#include "PassRegistry.def"
1687
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001688 for (auto &C : FunctionPipelineParsingCallbacks)
1689 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001690 return Error::success();
1691 return make_error<StringError>(
1692 formatv("unknown function pass '{0}'", Name).str(),
1693 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001694}
1695
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001696Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1697 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001698 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001699 auto &InnerPipeline = E.InnerPipeline;
1700
1701 // First handle complex passes like the pass managers which carry pipelines.
1702 if (!InnerPipeline.empty()) {
1703 if (Name == "loop") {
1704 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001705 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1706 VerifyEachPass, DebugLogging))
1707 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001708 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001709 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001710 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001711 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001712 if (auto Count = parseRepeatPassName(Name)) {
1713 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001714 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1715 VerifyEachPass, DebugLogging))
1716 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001717 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001718 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001719 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001720
1721 for (auto &C : LoopPipelineParsingCallbacks)
1722 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001723 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001724
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001725 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001726 return make_error<StringError>(
1727 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1728 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001729 }
1730
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001731// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001732#define LOOP_PASS(NAME, CREATE_PASS) \
1733 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001734 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001735 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001736 }
1737#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1738 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001739 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001740 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1741 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1742 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001743 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001744 } \
1745 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001746 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001747 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001748 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001749 }
1750#include "PassRegistry.def"
1751
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001752 for (auto &C : LoopPipelineParsingCallbacks)
1753 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001754 return Error::success();
1755 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1756 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001757}
1758
Chandler Carruthedf59962016-02-18 09:45:17 +00001759bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001760#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1761 if (Name == NAME) { \
1762 AA.registerModuleAnalysis< \
1763 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1764 return true; \
1765 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001766#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1767 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001768 AA.registerFunctionAnalysis< \
1769 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001770 return true; \
1771 }
1772#include "PassRegistry.def"
1773
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001774 for (auto &C : AAParsingCallbacks)
1775 if (C(Name, AA))
1776 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001777 return false;
1778}
1779
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001780Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001781 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001782 bool VerifyEachPass,
1783 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001784 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001785 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1786 return Err;
1787 // FIXME: No verifier support for Loop passes!
1788 }
1789 return Error::success();
1790}
1791
1792Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1793 ArrayRef<PipelineElement> Pipeline,
1794 bool VerifyEachPass,
1795 bool DebugLogging) {
1796 for (const auto &Element : Pipeline) {
1797 if (auto Err =
1798 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1799 return Err;
1800 if (VerifyEachPass)
1801 FPM.addPass(VerifierPass());
1802 }
1803 return Error::success();
1804}
1805
1806Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1807 ArrayRef<PipelineElement> Pipeline,
1808 bool VerifyEachPass,
1809 bool DebugLogging) {
1810 for (const auto &Element : Pipeline) {
1811 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1812 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001813 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001814 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001815 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00001816}
1817
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001818void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1819 FunctionAnalysisManager &FAM,
1820 CGSCCAnalysisManager &CGAM,
1821 ModuleAnalysisManager &MAM) {
1822 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1823 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001824 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1825 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1826 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1827 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1828 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1829}
1830
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001831Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1832 ArrayRef<PipelineElement> Pipeline,
1833 bool VerifyEachPass,
1834 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001835 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001836 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1837 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001838 if (VerifyEachPass)
1839 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001840 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001841 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001842}
1843
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001844// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00001845// FIXME: Should this routine accept a TargetMachine or require the caller to
1846// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001847Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1848 StringRef PipelineText,
1849 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001850 auto Pipeline = parsePipelineText(PipelineText);
1851 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001852 return make_error<StringError>(
1853 formatv("invalid pipeline '{0}'", PipelineText).str(),
1854 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001855
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001856 // If the first name isn't at the module layer, wrap the pipeline up
1857 // automatically.
1858 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00001859
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001860 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1861 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001862 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001863 } else if (isFunctionPassName(FirstName,
1864 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001865 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001866 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001867 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001868 } else {
1869 for (auto &C : TopLevelPipelineParsingCallbacks)
1870 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001871 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001872
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001873 // Unknown pass or pipeline name!
1874 auto &InnerPipeline = Pipeline->front().InnerPipeline;
1875 return make_error<StringError>(
1876 formatv("unknown {0} name '{1}'",
1877 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1878 .str(),
1879 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001880 }
Chandler Carruth572e3402014-04-21 11:12:00 +00001881 }
1882
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001883 if (auto Err =
1884 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1885 return Err;
1886 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001887}
Chandler Carruthedf59962016-02-18 09:45:17 +00001888
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001889// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001890Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1891 StringRef PipelineText,
1892 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001893 auto Pipeline = parsePipelineText(PipelineText);
1894 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001895 return make_error<StringError>(
1896 formatv("invalid pipeline '{0}'", PipelineText).str(),
1897 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001898
1899 StringRef FirstName = Pipeline->front().Name;
1900 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001901 return make_error<StringError>(
1902 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
1903 PipelineText)
1904 .str(),
1905 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001906
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001907 if (auto Err =
1908 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
1909 return Err;
1910 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001911}
1912
1913// Primary pass pipeline description parsing routine for a \c
1914// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001915Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
1916 StringRef PipelineText,
1917 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001918 auto Pipeline = parsePipelineText(PipelineText);
1919 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001920 return make_error<StringError>(
1921 formatv("invalid pipeline '{0}'", PipelineText).str(),
1922 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001923
1924 StringRef FirstName = Pipeline->front().Name;
1925 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001926 return make_error<StringError>(
1927 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
1928 PipelineText)
1929 .str(),
1930 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001931
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001932 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
1933 DebugLogging))
1934 return Err;
1935 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001936}
1937
1938// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001939Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
1940 StringRef PipelineText,
1941 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001942 auto Pipeline = parsePipelineText(PipelineText);
1943 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001944 return make_error<StringError>(
1945 formatv("invalid pipeline '{0}'", PipelineText).str(),
1946 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001947
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001948 if (auto Err =
1949 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
1950 return Err;
1951
1952 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001953}
1954
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001955Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00001956 // If the pipeline just consists of the word 'default' just replace the AA
1957 // manager with our default one.
1958 if (PipelineText == "default") {
1959 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001960 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00001961 }
1962
Chandler Carruthedf59962016-02-18 09:45:17 +00001963 while (!PipelineText.empty()) {
1964 StringRef Name;
1965 std::tie(Name, PipelineText) = PipelineText.split(',');
1966 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001967 return make_error<StringError>(
1968 formatv("unknown alias analysis name '{0}'", Name).str(),
1969 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00001970 }
1971
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001972 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00001973}