blob: e56c2d4c8fb36dc7056d19fddc6a7f99ade668d8 [file] [log] [blame]
Chandler Carruth1ff77242015-03-07 09:02:36 +00001//===- Parsing, selection, and construction of pass pipelines -------------===//
Chandler Carruth66445382014-01-11 08:16:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10///
Chandler Carruth1ff77242015-03-07 09:02:36 +000011/// This file provides the implementation of the PassBuilder based on our
12/// static pass registry as well as related functionality. It also provides
13/// helpers to aid in analyzing, debugging, and testing passes and pass
14/// pipelines.
Chandler Carruth66445382014-01-11 08:16:35 +000015///
16//===----------------------------------------------------------------------===//
17
Chandler Carruth1ff77242015-03-07 09:02:36 +000018#include "llvm/Passes/PassBuilder.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000019#include "llvm/ADT/StringSwitch.h"
Chandler Carruth6f5770b102016-02-13 23:32:00 +000020#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth4f846a52016-02-20 03:46:03 +000021#include "llvm/Analysis/AliasAnalysisEvaluator.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000022#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthbece8d52016-02-13 23:46:24 +000023#include "llvm/Analysis/BasicAliasAnalysis.h"
Xinliang David Li28a93272016-05-05 21:13:27 +000024#include "llvm/Analysis/BlockFrequencyInfo.h"
Xinliang David Li6e5dd412016-05-05 02:59:57 +000025#include "llvm/Analysis/BranchProbabilityInfo.h"
Mehdi Amini27d23792016-09-16 16:56:30 +000026#include "llvm/Analysis/CFGPrinter.h"
George Burgess IVbfa401e2016-07-06 00:26:41 +000027#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
28#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
Chandler Carruth572e3402014-04-21 11:12:00 +000029#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruth4c660f72016-03-10 11:24:11 +000030#include "llvm/Analysis/CallGraph.h"
Michael Kupersteinde16b442016-04-18 23:55:01 +000031#include "llvm/Analysis/DemandedBits.h"
Chandler Carruth49c22192016-05-12 22:19:39 +000032#include "llvm/Analysis/DependenceAnalysis.h"
Hongbin Zheng751337f2016-02-25 17:54:15 +000033#include "llvm/Analysis/DominanceFrontier.h"
Chandler Carruth45a9c202016-03-11 09:15:11 +000034#include "llvm/Analysis/GlobalsModRef.h"
Dehao Chen1a444522016-07-16 22:51:33 +000035#include "llvm/Analysis/IVUsers.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000036#include "llvm/Analysis/LazyCallGraph.h"
Sean Silva687019f2016-06-13 22:01:25 +000037#include "llvm/Analysis/LazyValueInfo.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000038#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000039#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth61440d22016-03-10 00:55:30 +000040#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000041#include "llvm/Analysis/MemorySSA.h"
Teresa Johnsonf93b2462016-08-12 13:53:02 +000042#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000043#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawnbdbbd832018-06-28 14:13:06 +000044#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng3f978402016-02-25 17:54:07 +000045#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000046#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000047#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000048#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000049#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000050#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000051#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000052#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000053#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000054#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000055#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000056#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000057#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000058#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000059#include "llvm/IR/PassManager.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000060#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000061#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000062#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000063#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000064#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000065#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000066#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000067#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000068#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000069#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000070#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000071#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000072#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000073#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000074#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000075#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000076#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000077#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000078#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000079#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000080#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000081#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000082#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000083#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000084#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000085#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000086#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000087#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000088#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000089#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000090#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000091#include "llvm/Transforms/Instrumentation.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000092#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000093#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000094#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000095#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
96#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000097#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
Philip Pfaffe685c76d2019-01-16 09:28:01 +000098#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +000099#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000100#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000101#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000102#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000103#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000104#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000105#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000106#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000107#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000108#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000109#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000110#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000111#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000112#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000113#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000114#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000115#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000116#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000117#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000118#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000119#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000120#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000121#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000122#include "llvm/Transforms/Scalar/LoopDistribute.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000123#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000124#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000125#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000126#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000127#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000128#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000129#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000130#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000131#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000132#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000133#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000134#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000135#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000136#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000137#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000138#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000139#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000140#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000141#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000142#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000143#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000144#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000145#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000146#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000147#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000148#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000149#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000150#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000151#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000152#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000153#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000154#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000155#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000156#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000157#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000158#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000159#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000160#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000161#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000162#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000163#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000164#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000165#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000166#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000167#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000168#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000169
Chandler Carruth66445382014-01-11 08:16:35 +0000170using namespace llvm;
171
Chandler Carruth719ffe12017-02-12 05:38:04 +0000172static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
173 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000174static cl::opt<bool>
175 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
176 cl::Hidden, cl::ZeroOrMore,
177 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000178
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000179static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000180 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000181 cl::Hidden, cl::ZeroOrMore,
182 cl::desc("Run NewGVN instead of GVN"));
183
Geoff Berry3cca1da2017-06-10 15:20:03 +0000184static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000185 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
186 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000187
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000188static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000189 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
190 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000191
Davide Italianobe1b6a92017-06-03 23:18:29 +0000192static cl::opt<bool> EnableGVNSink(
193 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
194 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
195
David Green963401d2018-07-01 12:47:30 +0000196static cl::opt<bool> EnableUnrollAndJam(
197 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
198 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
199
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000200static cl::opt<bool> EnableSyntheticCounts(
201 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
202 cl::desc("Run synthetic function entry count generation "
203 "pass"));
204
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000205static Regex DefaultAliasRegex(
206 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000207
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000208static cl::opt<bool>
209 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
210 cl::desc("Enable control height reduction optimization (CHR)"));
211
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000212extern cl::opt<bool> EnableHotColdSplit;
213
Wei Mi3bcccdf2019-01-17 20:48:34 +0000214extern cl::opt<bool> FlattenedProfileUsed;
215
Chandler Carruthe3f50642016-12-22 06:59:15 +0000216static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
217 switch (Level) {
218 case PassBuilder::O0:
219 case PassBuilder::O1:
220 case PassBuilder::O2:
221 case PassBuilder::O3:
222 return false;
223
224 case PassBuilder::Os:
225 case PassBuilder::Oz:
226 return true;
227 }
228 llvm_unreachable("Invalid optimization level!");
229}
230
Chandler Carruth66445382014-01-11 08:16:35 +0000231namespace {
232
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000233/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000234struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000235 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000236 return PreservedAnalyses::all();
237 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000238 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000239};
240
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000241/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000242class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
243 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000244 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000245
246public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000247 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000248 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000249 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000250};
251
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000252/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000253struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000254 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
255 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000256 return PreservedAnalyses::all();
257 }
258 static StringRef name() { return "NoOpCGSCCPass"; }
259};
260
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000261/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000262class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
263 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000264 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000265
266public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000267 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000268 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000269 return Result();
270 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000271 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000272};
273
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000274/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000275struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000276 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000277 return PreservedAnalyses::all();
278 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000279 static StringRef name() { return "NoOpFunctionPass"; }
280};
281
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000282/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000283class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
284 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000285 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000286
287public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000288 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000289 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000290 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000291};
292
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000293/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000294struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000295 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
296 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000297 return PreservedAnalyses::all();
298 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000299 static StringRef name() { return "NoOpLoopPass"; }
300};
301
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000302/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000303class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
304 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000305 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000306
307public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000308 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000309 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
310 return Result();
311 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000312 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000313};
314
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000315AnalysisKey NoOpModuleAnalysis::Key;
316AnalysisKey NoOpCGSCCAnalysis::Key;
317AnalysisKey NoOpFunctionAnalysis::Key;
318AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000319
Chandler Carruth66445382014-01-11 08:16:35 +0000320} // End anonymous namespace.
321
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000322void PassBuilder::invokePeepholeEPCallbacks(
323 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
324 for (auto &C : PeepholeEPCallbacks)
325 C(FPM, Level);
326}
327
Chandler Carruth1ff77242015-03-07 09:02:36 +0000328void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000329#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000330 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000331#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000332
333 for (auto &C : ModuleAnalysisRegistrationCallbacks)
334 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000335}
336
Chandler Carruth1ff77242015-03-07 09:02:36 +0000337void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000338#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000339 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000340#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000341
342 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
343 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000344}
345
Chandler Carruth1ff77242015-03-07 09:02:36 +0000346void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000347#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000348 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000349#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000350
351 for (auto &C : FunctionAnalysisRegistrationCallbacks)
352 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000353}
354
Justin Bognereecc3c82016-02-25 07:23:08 +0000355void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000356#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000357 LAM.registerPass([&] { return CREATE_PASS; });
358#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000359
360 for (auto &C : LoopAnalysisRegistrationCallbacks)
361 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000362}
363
Chandler Carruthe3f50642016-12-22 06:59:15 +0000364FunctionPassManager
365PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000366 ThinLTOPhase Phase,
367 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000368 assert(Level != O0 && "Must request optimizations!");
369 FunctionPassManager FPM(DebugLogging);
370
371 // Form SSA out of local memory accesses after breaking apart aggregates into
372 // scalars.
373 FPM.addPass(SROA());
374
375 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000376 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000377
Davide Italianoc3688312017-06-01 23:08:14 +0000378 // Hoisting of scalars and load expressions.
379 if (EnableGVNHoist)
380 FPM.addPass(GVNHoistPass());
381
Davide Italianobe1b6a92017-06-03 23:18:29 +0000382 // Global value numbering based sinking.
383 if (EnableGVNSink) {
384 FPM.addPass(GVNSinkPass());
385 FPM.addPass(SimplifyCFGPass());
386 }
387
Chandler Carruthe3f50642016-12-22 06:59:15 +0000388 // Speculative execution if the target has divergent branches; otherwise nop.
389 FPM.addPass(SpeculativeExecutionPass());
390
391 // Optimize based on known information about branches, and cleanup afterward.
392 FPM.addPass(JumpThreadingPass());
393 FPM.addPass(CorrelatedValuePropagationPass());
394 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000395 if (Level == O3)
396 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000397 FPM.addPass(InstCombinePass());
398
399 if (!isOptimizingForSize(Level))
400 FPM.addPass(LibCallsShrinkWrapPass());
401
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000402 invokePeepholeEPCallbacks(FPM, Level);
403
Rong Xue1f42452017-10-23 22:21:29 +0000404 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
405 // using the size value profile. Don't perform this when optimizing for size.
406 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
407 !isOptimizingForSize(Level))
408 FPM.addPass(PGOMemOPSizeOpt());
409
Chandler Carruthe3f50642016-12-22 06:59:15 +0000410 FPM.addPass(TailCallElimPass());
411 FPM.addPass(SimplifyCFGPass());
412
413 // Form canonically associated expression trees, and simplify the trees using
414 // basic mathematical properties. For example, this will form (nearly)
415 // minimal multiplication trees.
416 FPM.addPass(ReassociatePass());
417
418 // Add the primary loop simplification pipeline.
419 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000420 // some function passes in between them. These can and should be removed
421 // and/or replaced by scheduling the loop pass equivalents in the correct
422 // positions. But those equivalent passes aren't powerful enough yet.
423 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
424 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
425 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
426 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000427 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
428
Chandler Carruth71fd2702018-05-30 02:46:45 +0000429 // Simplify the loop body. We do this initially to clean up after other loop
430 // passes run, either when iterating on a loop or on inner loops with
431 // implications on the outer loop.
432 LPM1.addPass(LoopInstSimplifyPass());
433 LPM1.addPass(LoopSimplifyCFGPass());
434
Chandler Carruthe3f50642016-12-22 06:59:15 +0000435 // Rotate Loop - disable header duplication at -Oz
436 LPM1.addPass(LoopRotatePass(Level != Oz));
437 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000438 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000439 LPM2.addPass(IndVarSimplifyPass());
440 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000441
442 for (auto &C : LateLoopOptimizationsEPCallbacks)
443 C(LPM2, Level);
444
Chandler Carruth79b733b2017-01-26 23:21:17 +0000445 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000446 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000447 // because it changes IR to makes profile annotation in back compile
448 // inaccurate.
Dehao Chen95f00302017-07-30 04:55:39 +0000449 if (Phase != ThinLTOPhase::PreLink ||
450 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnsonecd90132017-08-02 20:35:29 +0000451 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000452
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000453 for (auto &C : LoopOptimizerEndEPCallbacks)
454 C(LPM2, Level);
455
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000456 // We provide the opt remark emitter pass for LICM to use. We only need to do
457 // this once as it is immutable.
458 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000459 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000460 FPM.addPass(SimplifyCFGPass());
461 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000462 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000463
464 // Eliminate redundancies.
465 if (Level != O1) {
466 // These passes add substantial compile time so skip them at O1.
467 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000468 if (RunNewGVN)
469 FPM.addPass(NewGVNPass());
470 else
471 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000472 }
473
474 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
475 FPM.addPass(MemCpyOptPass());
476
477 // Sparse conditional constant propagation.
478 // FIXME: It isn't clear why we do this *after* loop passes rather than
479 // before...
480 FPM.addPass(SCCPPass());
481
482 // Delete dead bit computations (instcombine runs after to fold away the dead
483 // computations, and then ADCE will run later to exploit any new DCE
484 // opportunities that creates).
485 FPM.addPass(BDCEPass());
486
487 // Run instcombine after redundancy and dead bit elimination to exploit
488 // opportunities opened up by them.
489 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000490 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000491
492 // Re-consider control flow based optimizations after redundancy elimination,
493 // redo DCE, etc.
494 FPM.addPass(JumpThreadingPass());
495 FPM.addPass(CorrelatedValuePropagationPass());
496 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000497 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000498
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000499 for (auto &C : ScalarOptimizerLateEPCallbacks)
500 C(FPM, Level);
501
Chandler Carruthe3f50642016-12-22 06:59:15 +0000502 // Finally, do an expensive DCE pass to catch all the dead code exposed by
503 // the simplifications and basic cleanup after all the simplifications.
504 FPM.addPass(ADCEPass());
505 FPM.addPass(SimplifyCFGPass());
506 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000507 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000508
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000509 if (EnableCHR && Level == O3 && PGOOpt &&
510 (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty()))
511 FPM.addPass(ControlHeightReductionPass());
512
Chandler Carruthe3f50642016-12-22 06:59:15 +0000513 return FPM;
514}
515
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000516void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
517 PassBuilder::OptimizationLevel Level,
518 bool RunProfileGen,
519 std::string ProfileGenFile,
Richard Smith6c676622018-10-10 23:13:47 +0000520 std::string ProfileUseFile,
521 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000522 // Generally running simplification passes and the inliner with an high
523 // threshold results in smaller executables, but there may be cases where
524 // the size grows, so let's be conservative here and skip this simplification
525 // at -Os/Oz.
526 if (!isOptimizingForSize(Level)) {
527 InlineParams IP;
528
529 // In the old pass manager, this is a cl::opt. Should still this be one?
530 IP.DefaultThreshold = 75;
531
532 // FIXME: The hint threshold has the same value used by the regular inliner.
533 // This should probably be lowered after performance testing.
534 // FIXME: this comment is cargo culted from the old pass manager, revisit).
535 IP.HintThreshold = 325;
536
537 CGSCCPassManager CGPipeline(DebugLogging);
538
539 CGPipeline.addPass(InlinerPass(IP));
540
541 FunctionPassManager FPM;
542 FPM.addPass(SROA());
543 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
544 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
545 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000546 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000547
Davide Italiano513dfaa2017-02-13 15:26:22 +0000548 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
549
550 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
551 }
552
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000553 // Delete anything that is now dead to make sure that we don't instrument
554 // dead code. Instrumentation can end up keeping dead code around and
555 // dramatically increase code size.
556 MPM.addPass(GlobalDCEPass());
557
Davide Italiano513dfaa2017-02-13 15:26:22 +0000558 if (RunProfileGen) {
559 MPM.addPass(PGOInstrumentationGen());
560
Xinliang David Lib67530e2017-06-25 00:26:43 +0000561 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000562 FPM.addPass(
563 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000564 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
565
Davide Italiano513dfaa2017-02-13 15:26:22 +0000566 // Add the profile lowering pass.
567 InstrProfOptions Options;
568 if (!ProfileGenFile.empty())
569 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000570 Options.DoCounterPromotion = true;
Davide Italiano513dfaa2017-02-13 15:26:22 +0000571 MPM.addPass(InstrProfiling(Options));
572 }
573
574 if (!ProfileUseFile.empty())
Richard Smith6c676622018-10-10 23:13:47 +0000575 MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000576}
577
Easwaran Raman8249fac2017-06-28 13:33:49 +0000578static InlineParams
579getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
580 auto O3 = PassBuilder::O3;
581 unsigned OptLevel = Level > O3 ? 2 : Level;
582 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
583 return getInlineParams(OptLevel, SizeLevel);
584}
585
Chandler Carruthe3f50642016-12-22 06:59:15 +0000586ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000587PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000588 ThinLTOPhase Phase,
589 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000590 ModulePassManager MPM(DebugLogging);
591
Chandler Carruthe3f50642016-12-22 06:59:15 +0000592 // Do basic inference of function attributes from known properties of system
593 // libraries and other oracles.
594 MPM.addPass(InferFunctionAttrsPass());
595
596 // Create an early function pass manager to cleanup the output of the
597 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000598 FunctionPassManager EarlyFPM(DebugLogging);
599 EarlyFPM.addPass(SimplifyCFGPass());
600 EarlyFPM.addPass(SROA());
601 EarlyFPM.addPass(EarlyCSEPass());
602 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000603 if (Level == O3)
604 EarlyFPM.addPass(CallSiteSplittingPass());
605
Dehao Chen08f88312017-08-07 20:23:20 +0000606 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
607 // to convert bitcast to direct calls so that they can be inlined during the
608 // profile annotation prepration step.
609 // More details about SamplePGO design can be found in:
610 // https://research.google.com/pubs/pub45290.html
611 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
612 if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
613 Phase == ThinLTOPhase::PostLink)
614 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000615 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000616
Dehao Chen08f88312017-08-07 20:23:20 +0000617 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
618 // Annotate sample profile right after early FPM to ensure freshness of
619 // the debug info.
Wei Mi3bcccdf2019-01-17 20:48:34 +0000620 // In ThinLTO mode, when flattened profile is used, all the available
621 // profile information will be annotated in PreLink phase so there is
622 // no need to load the profile again in PostLink.
623 if (!(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink))
624 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
625 PGOOpt->ProfileRemappingFile,
626 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000627 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
628 // for the profile annotation to be accurate in the ThinLTO backend.
629 if (Phase != ThinLTOPhase::PreLink)
630 // We perform early indirect call promotion here, before globalopt.
631 // This is important for the ThinLTO backend phase because otherwise
632 // imported available_externally functions look unreferenced and are
633 // removed.
634 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
635 true));
636 }
637
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000638 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000639 // and prior to optimizing globals.
640 // FIXME: This position in the pipeline hasn't been carefully considered in
641 // years, it should be re-analyzed.
642 MPM.addPass(IPSCCPPass());
643
Matthew Simpsoncb585582017-10-25 13:40:08 +0000644 // Attach metadata to indirect call sites indicating the set of functions
645 // they may target at run-time. This should follow IPSCCP.
646 MPM.addPass(CalledValuePropagationPass());
647
Chandler Carruthe3f50642016-12-22 06:59:15 +0000648 // Optimize globals to try and fold them into constants.
649 MPM.addPass(GlobalOptPass());
650
651 // Promote any localized globals to SSA registers.
652 // FIXME: Should this instead by a run of SROA?
653 // FIXME: We should probably run instcombine and simplify-cfg afterward to
654 // delete control flows that are dead once globals have been folded to
655 // constants.
656 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
657
658 // Remove any dead arguments exposed by cleanups and constand folding
659 // globals.
660 MPM.addPass(DeadArgumentEliminationPass());
661
662 // Create a small function pass pipeline to cleanup after all the global
663 // optimizations.
664 FunctionPassManager GlobalCleanupPM(DebugLogging);
665 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000666 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
667
Chandler Carruthe3f50642016-12-22 06:59:15 +0000668 GlobalCleanupPM.addPass(SimplifyCFGPass());
669 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
670
Dehao Chen89d32262017-08-02 01:28:31 +0000671 // Add all the requested passes for instrumentation PGO, if requested.
672 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
673 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
674 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
Richard Smith6c676622018-10-10 23:13:47 +0000675 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
676 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000677 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000678 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000679
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000680 // Synthesize function entry counts for non-PGO compilation.
681 if (EnableSyntheticCounts && !PGOOpt)
682 MPM.addPass(SyntheticCountsPropagation());
683
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000684 // Require the GlobalsAA analysis for the module so we can query it within
685 // the CGSCC pipeline.
686 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000687
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000688 // Require the ProfileSummaryAnalysis for the module so we can query it within
689 // the inliner pass.
690 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
691
Chandler Carruthe3f50642016-12-22 06:59:15 +0000692 // Now begin the main postorder CGSCC pipeline.
693 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
694 // manager and trying to emulate its precise behavior. Much of this doesn't
695 // make a lot of sense and we should revisit the core CGSCC structure.
696 CGSCCPassManager MainCGPipeline(DebugLogging);
697
698 // Note: historically, the PruneEH pass was run first to deduce nounwind and
699 // generally clean up exception handling overhead. It isn't clear this is
700 // valuable as the inliner doesn't currently care whether it is inlining an
701 // invoke or a call.
702
703 // Run the inliner first. The theory is that we are walking bottom-up and so
704 // the callees have already been fully optimized, and we want to inline them
705 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000706 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000707 // because it makes profile annotation in the backend inaccurate.
708 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000709 if (Phase == ThinLTOPhase::PreLink &&
710 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000711 IP.HotCallSiteThreshold = 0;
712 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000713
714 // Now deduce any function attributes based in the current code.
715 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
716
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000717 // When at O3 add argument promotion to the pass pipeline.
718 // FIXME: It isn't at all clear why this should be limited to O3.
719 if (Level == O3)
720 MainCGPipeline.addPass(ArgumentPromotionPass());
721
Chandler Carruthe3f50642016-12-22 06:59:15 +0000722 // Lastly, add the core function simplification pipeline nested inside the
723 // CGSCC walk.
724 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000725 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000726
Teresa Johnsond7253352018-10-23 22:57:40 +0000727 // We only want to do hot cold splitting once for ThinLTO, during the
728 // post-link ThinLTO.
729 if (EnableHotColdSplit && Phase != ThinLTOPhase::PreLink)
Aditya Kumard9e2e382018-10-21 18:11:56 +0000730 MPM.addPass(HotColdSplittingPass());
731
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000732 for (auto &C : CGSCCOptimizerLateEPCallbacks)
733 C(MainCGPipeline, Level);
734
Chandler Carruth719ffe12017-02-12 05:38:04 +0000735 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
736 // to detect when we devirtualize indirect calls and iterate the SCC passes
737 // in that case to try and catch knock-on inlining or function attrs
738 // opportunities. Then we add it to the module pipeline by walking the SCCs
739 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000740 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000741 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000742 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000743
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000744 return MPM;
745}
746
747ModulePassManager
748PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
749 bool DebugLogging) {
750 ModulePassManager MPM(DebugLogging);
751
752 // Optimize globals now that the module is fully simplified.
753 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000754 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000755
Xinliang David Li126157c2017-05-22 16:41:57 +0000756 // Run partial inlining pass to partially inline functions that have
757 // large bodies.
758 if (RunPartialInlining)
759 MPM.addPass(PartialInlinerPass());
760
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000761 // Remove avail extern fns and globals definitions since we aren't compiling
762 // an object file for later LTO. For LTO we want to preserve these so they
763 // are eligible for inlining at link-time. Note if they are unreferenced they
764 // will be removed by GlobalDCE later, so this only impacts referenced
765 // available externally globals. Eventually they will be suppressed during
766 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
767 // may make globals referenced by available external functions dead and saves
768 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000769 MPM.addPass(EliminateAvailableExternallyPass());
770
771 // Do RPO function attribute inference across the module to forward-propagate
772 // attributes where applicable.
773 // FIXME: Is this really an optimization rather than a canonicalization?
774 MPM.addPass(ReversePostOrderFunctionAttrsPass());
775
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000776 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000777 // useful as the above will have inlined, DCE'ed, and function-attr
778 // propagated everything. We should at this point have a reasonably minimal
779 // and richly annotated call graph. By computing aliasing and mod/ref
780 // information for all local globals here, the late loop passes and notably
781 // the vectorizer will be able to use them to help recognize vectorizable
782 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000783 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000784
785 FunctionPassManager OptimizePM(DebugLogging);
786 OptimizePM.addPass(Float2IntPass());
787 // FIXME: We need to run some loop optimizations to re-rotate loops after
788 // simplify-cfg and others undo their rotation.
789
790 // Optimize the loop execution. These passes operate on entire loop nests
791 // rather than on each loop in an inside-out manner, and so they are actually
792 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000793
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000794 for (auto &C : VectorizerStartEPCallbacks)
795 C(OptimizePM, Level);
796
Chandler Carrutha95ff382017-01-27 00:50:21 +0000797 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000798 OptimizePM.addPass(
799 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000800
801 // Distribute loops to allow partial vectorization. I.e. isolate dependences
802 // into separate loop that would otherwise inhibit vectorization. This is
803 // currently only performed for loops marked with the metadata
804 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000805 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000806
807 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000808 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000809
Chandler Carruthbaabda92017-01-27 01:32:26 +0000810 // Eliminate loads by forwarding stores from the previous iteration to loads
811 // of the current iteration.
812 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000813
814 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000815 OptimizePM.addPass(InstCombinePass());
816
Chandler Carrutha95ff382017-01-27 00:50:21 +0000817 // Now that we've formed fast to execute loop structures, we do further
818 // optimizations. These are run afterward as they might block doing complex
819 // analyses and transforms such as what are needed for loop vectorization.
820
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000821 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
822 // GVN, loop transforms, and others have already run, so it's now better to
823 // convert to more optimized IR using more aggressive simplify CFG options.
824 // The extra sinking transform can create larger basic blocks, so do this
825 // before SLP vectorization.
826 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
827 forwardSwitchCondToPhi(true).
828 convertSwitchToLookupTable(true).
829 needCanonicalLoops(false).
830 sinkCommonInsts(true)));
831
Chandler Carruthe3f50642016-12-22 06:59:15 +0000832 // Optimize parallel scalar instruction chains into SIMD instructions.
833 OptimizePM.addPass(SLPVectorizerPass());
834
Chandler Carruthe3f50642016-12-22 06:59:15 +0000835 OptimizePM.addPass(InstCombinePass());
836
837 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000838 // execution resources of an out-of-order processor. We also then need to
839 // clean up redundancies and loop invariant code.
840 // FIXME: It would be really good to use a loop-integrated instruction
841 // combiner for cleanup here so that the unrolling and LICM can be pipelined
842 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000843 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
844 if (EnableUnrollAndJam) {
845 OptimizePM.addPass(
846 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
847 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000848 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000849 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000850 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000851 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000852 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000853
854 // Now that we've vectorized and unrolled loops, we may have more refined
855 // alignment information, try to re-derive it here.
856 OptimizePM.addPass(AlignmentFromAssumptionsPass());
857
Chandler Carrutha95ff382017-01-27 00:50:21 +0000858 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
859 // canonicalization pass that enables other optimizations. As a result,
860 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
861 // result too early.
862 OptimizePM.addPass(LoopSinkPass());
863
864 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000865 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000866
Sanjay Patel6fd43912017-09-09 13:38:18 +0000867 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
868 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
869 // flattening of blocks.
870 OptimizePM.addPass(DivRemPairsPass());
871
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000872 // LoopSink (and other loop passes since the last simplifyCFG) might have
873 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
874 OptimizePM.addPass(SimplifyCFGPass());
875
Chandler Carruthc34f7892017-11-28 11:32:31 +0000876 // Optimize PHIs by speculating around them when profitable. Note that this
877 // pass needs to be run after any PRE or similar pass as it is essentially
878 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
879 OptimizePM.addPass(SpeculateAroundPHIsPass());
880
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000881 for (auto &C : OptimizerLastEPCallbacks)
882 C(OptimizePM, Level);
883
Chandler Carrutha95ff382017-01-27 00:50:21 +0000884 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000885 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
886
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000887 MPM.addPass(CGProfilePass());
888
Chandler Carruthe3f50642016-12-22 06:59:15 +0000889 // Now we need to do some global optimization transforms.
890 // FIXME: It would seem like these should come first in the optimization
891 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
892 // ordering here.
893 MPM.addPass(GlobalDCEPass());
894 MPM.addPass(ConstantMergePass());
895
896 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000897}
898
Chandler Carruthe3f50642016-12-22 06:59:15 +0000899ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000900PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
901 bool DebugLogging) {
902 assert(Level != O0 && "Must request optimizations for the default pipeline!");
903
904 ModulePassManager MPM(DebugLogging);
905
906 // Force any function attributes we want the rest of the pipeline to observe.
907 MPM.addPass(ForceFunctionAttrsPass());
908
David Blaikie0c64f5a2018-01-23 01:25:20 +0000909 // Apply module pipeline start EP callback.
910 for (auto &C : PipelineStartEPCallbacks)
911 C(MPM);
912
Dehao Chen08f88312017-08-07 20:23:20 +0000913 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000914 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
915
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000916 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000917 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
918 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000919
920 // Now add the optimization pipeline.
921 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
922
923 return MPM;
924}
925
926ModulePassManager
927PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
928 bool DebugLogging) {
929 assert(Level != O0 && "Must request optimizations for the default pipeline!");
930
931 ModulePassManager MPM(DebugLogging);
932
933 // Force any function attributes we want the rest of the pipeline to observe.
934 MPM.addPass(ForceFunctionAttrsPass());
935
Dehao Chen08f88312017-08-07 20:23:20 +0000936 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000937 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
938
David Blaikie0c64f5a2018-01-23 01:25:20 +0000939 // Apply module pipeline start EP callback.
940 for (auto &C : PipelineStartEPCallbacks)
941 C(MPM);
942
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000943 // If we are planning to perform ThinLTO later, we don't bloat the code with
944 // unrolling/vectorization/... now. Just simplify the module as much as we
945 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000946 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
947 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000948
949 // Run partial inlining pass to partially inline functions that have
950 // large bodies.
951 // FIXME: It isn't clear whether this is really the right place to run this
952 // in ThinLTO. Because there is another canonicalization and simplification
953 // phase that will run after the thin link, running this here ends up with
954 // less information than will be available later and it may grow functions in
955 // ways that aren't beneficial.
956 if (RunPartialInlining)
957 MPM.addPass(PartialInlinerPass());
958
959 // Reduce the size of the IR as much as possible.
960 MPM.addPass(GlobalOptPass());
961
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000962 return MPM;
963}
964
Teresa Johnson28023db2018-07-19 14:51:32 +0000965ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
966 OptimizationLevel Level, bool DebugLogging,
967 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000968 ModulePassManager MPM(DebugLogging);
969
Teresa Johnson28023db2018-07-19 14:51:32 +0000970 if (ImportSummary) {
971 // These passes import type identifier resolutions for whole-program
972 // devirtualization and CFI. They must run early because other passes may
973 // disturb the specific instruction patterns that these passes look for,
974 // creating dependencies on resolutions that may not appear in the summary.
975 //
976 // For example, GVN may transform the pattern assume(type.test) appearing in
977 // two basic blocks into assume(phi(type.test, type.test)), which would
978 // transform a dependency on a WPD resolution into a dependency on a type
979 // identifier resolution for CFI.
980 //
981 // Also, WPD has access to more precise information than ICP and can
982 // devirtualize more effectively, so it should operate on the IR first.
983 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
984 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
985 }
986
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000987 // Force any function attributes we want the rest of the pipeline to observe.
988 MPM.addPass(ForceFunctionAttrsPass());
989
990 // During the ThinLTO backend phase we perform early indirect call promotion
991 // here, before globalopt. Otherwise imported available_externally functions
992 // look unreferenced and are removed.
Dehao Chen08f88312017-08-07 20:23:20 +0000993 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
994 // with SamplePGO.
Dehao Chen2f4e2e22017-08-10 05:10:32 +0000995 if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
Dehao Chen08f88312017-08-07 20:23:20 +0000996 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
997 false /* SamplePGO */));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000998
999 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001000 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1001 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001002
1003 // Now add the optimization pipeline.
1004 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1005
1006 return MPM;
1007}
1008
1009ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001010PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1011 bool DebugLogging) {
1012 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001013 // FIXME: We should use a customized pre-link pipeline!
Chandler Carruthe3f50642016-12-22 06:59:15 +00001014 return buildPerModuleDefaultPipeline(Level, DebugLogging);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001015}
1016
Teresa Johnson28023db2018-07-19 14:51:32 +00001017ModulePassManager
1018PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1019 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001020 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1021 ModulePassManager MPM(DebugLogging);
1022
Xin Tong642c8d32018-11-15 18:06:42 +00001023 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
1024 // Load sample profile before running the LTO optimization pipeline.
1025 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
1026 PGOOpt->ProfileRemappingFile,
1027 false /* ThinLTOPhase::PreLink */));
1028 }
1029
Davide Italiano089a9122017-01-24 00:57:39 +00001030 // Remove unused virtual tables to improve the quality of code generated by
1031 // whole-program devirtualization and bitset lowering.
1032 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001033
Davide Italiano089a9122017-01-24 00:57:39 +00001034 // Force any function attributes we want the rest of the pipeline to observe.
1035 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001036
Davide Italiano089a9122017-01-24 00:57:39 +00001037 // Do basic inference of function attributes from known properties of system
1038 // libraries and other oracles.
1039 MPM.addPass(InferFunctionAttrsPass());
1040
1041 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001042 FunctionPassManager EarlyFPM(DebugLogging);
1043 EarlyFPM.addPass(CallSiteSplittingPass());
1044 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1045
Davide Italiano089a9122017-01-24 00:57:39 +00001046 // Indirect call promotion. This should promote all the targets that are
1047 // left by the earlier promotion pass that promotes intra-module targets.
1048 // This two-step promotion is to save the compile time. For LTO, it should
1049 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001050 MPM.addPass(PGOIndirectCallPromotion(
1051 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +00001052 // Propagate constants at call sites into the functions they call. This
1053 // opens opportunities for globalopt (and inlining) by substituting function
1054 // pointers passed as arguments to direct uses of functions.
1055 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001056
1057 // Attach metadata to indirect call sites indicating the set of functions
1058 // they may target at run-time. This should follow IPSCCP.
1059 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001060 }
1061
1062 // Now deduce any function attributes based in the current code.
1063 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1064 PostOrderFunctionAttrsPass()));
1065
1066 // Do RPO function attribute inference across the module to forward-propagate
1067 // attributes where applicable.
1068 // FIXME: Is this really an optimization rather than a canonicalization?
1069 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1070
1071 // Use inragne annotations on GEP indices to split globals where beneficial.
1072 MPM.addPass(GlobalSplitPass());
1073
1074 // Run whole program optimization of virtual call when the list of callees
1075 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001076 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001077
1078 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001079 if (Level == 1) {
1080 // The LowerTypeTestsPass needs to run to lower type metadata and the
1081 // type.test intrinsics. The pass does nothing if CFI is disabled.
1082 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001083 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001084 }
Davide Italiano089a9122017-01-24 00:57:39 +00001085
1086 // Optimize globals to try and fold them into constants.
1087 MPM.addPass(GlobalOptPass());
1088
1089 // Promote any localized globals to SSA registers.
1090 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1091
1092 // Linking modules together can lead to duplicate global constant, only
1093 // keep one copy of each constant.
1094 MPM.addPass(ConstantMergePass());
1095
1096 // Remove unused arguments from functions.
1097 MPM.addPass(DeadArgumentEliminationPass());
1098
1099 // Reduce the code after globalopt and ipsccp. Both can open up significant
1100 // simplification opportunities, and both can propagate functions through
1101 // function pointers. When this happens, we often have to resolve varargs
1102 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001103 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001104 if (Level == O3)
1105 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001106 PeepholeFPM.addPass(InstCombinePass());
1107 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1108
1109 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001110
1111 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1112 // generally clean up exception handling overhead. It isn't clear this is
1113 // valuable as the inliner doesn't currently care whether it is inlining an
1114 // invoke or a call.
1115 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001116 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1117 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001118
1119 // Optimize globals again after we ran the inliner.
1120 MPM.addPass(GlobalOptPass());
1121
1122 // Garbage collect dead functions.
1123 // FIXME: Add ArgumentPromotion pass after once it's ported.
1124 MPM.addPass(GlobalDCEPass());
1125
1126 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001127 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001128 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001129 invokePeepholeEPCallbacks(FPM, Level);
1130
Davide Italiano089a9122017-01-24 00:57:39 +00001131 FPM.addPass(JumpThreadingPass());
1132
1133 // Break up allocas
1134 FPM.addPass(SROA());
1135
1136 // Run a few AA driver optimizations here and now to cleanup the code.
1137 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1138
1139 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1140 PostOrderFunctionAttrsPass()));
1141 // FIXME: here we run IP alias analysis in the legacy PM.
1142
1143 FunctionPassManager MainFPM;
1144
1145 // FIXME: once we fix LoopPass Manager, add LICM here.
1146 // FIXME: once we provide support for enabling MLSM, add it here.
1147 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001148 if (RunNewGVN)
1149 MainFPM.addPass(NewGVNPass());
1150 else
1151 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001152
1153 // Remove dead memcpy()'s.
1154 MainFPM.addPass(MemCpyOptPass());
1155
1156 // Nuke dead stores.
1157 MainFPM.addPass(DSEPass());
1158
1159 // FIXME: at this point, we run a bunch of loop passes:
1160 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1161 // loopVectorize. Enable them once the remaining issue with LPM
1162 // are sorted out.
1163
1164 MainFPM.addPass(InstCombinePass());
1165 MainFPM.addPass(SimplifyCFGPass());
1166 MainFPM.addPass(SCCPPass());
1167 MainFPM.addPass(InstCombinePass());
1168 MainFPM.addPass(BDCEPass());
1169
1170 // FIXME: We may want to run SLPVectorizer here.
1171 // After vectorization, assume intrinsics may tell us more
1172 // about pointer alignments.
1173#if 0
1174 MainFPM.add(AlignmentFromAssumptionsPass());
1175#endif
1176
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001177 // FIXME: Conditionally run LoadCombine here, after it's ported
1178 // (in case we still have this pass, given its questionable usefulness).
1179
Davide Italiano089a9122017-01-24 00:57:39 +00001180 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001181 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001182 MainFPM.addPass(JumpThreadingPass());
1183 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1184
1185 // Create a function that performs CFI checks for cross-DSO calls with
1186 // targets in the current module.
1187 MPM.addPass(CrossDSOCFIPass());
1188
1189 // Lower type metadata and the type.test intrinsic. This pass supports
1190 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1191 // to be run at link time if CFI is enabled. This pass does nothing if
1192 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001193 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001194
1195 // Add late LTO optimization passes.
1196 // Delete basic blocks, which optimization passes may have killed.
1197 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1198
1199 // Drop bodies of available eternally objects to improve GlobalDCE.
1200 MPM.addPass(EliminateAvailableExternallyPass());
1201
1202 // Now that we have optimized the program, discard unreachable functions.
1203 MPM.addPass(GlobalDCEPass());
1204
1205 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001206 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001207}
1208
Chandler Carruth060ad612016-12-23 20:38:19 +00001209AAManager PassBuilder::buildDefaultAAPipeline() {
1210 AAManager AA;
1211
1212 // The order in which these are registered determines their priority when
1213 // being queried.
1214
1215 // First we register the basic alias analysis that provides the majority of
1216 // per-function local AA logic. This is a stateless, on-demand local set of
1217 // AA techniques.
1218 AA.registerFunctionAnalysis<BasicAA>();
1219
1220 // Next we query fast, specialized alias analyses that wrap IR-embedded
1221 // information about aliasing.
1222 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1223 AA.registerFunctionAnalysis<TypeBasedAA>();
1224
1225 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001226 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1227 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001228 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001229 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001230
1231 return AA;
1232}
1233
Chandler Carruth241bf242016-08-03 07:44:48 +00001234static Optional<int> parseRepeatPassName(StringRef Name) {
1235 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1236 return None;
1237 int Count;
1238 if (Name.getAsInteger(0, Count) || Count <= 0)
1239 return None;
1240 return Count;
1241}
1242
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001243static Optional<int> parseDevirtPassName(StringRef Name) {
1244 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1245 return None;
1246 int Count;
1247 if (Name.getAsInteger(0, Count) || Count <= 0)
1248 return None;
1249 return Count;
1250}
1251
Fedor Sergeevb7871402019-01-10 10:01:53 +00001252static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1253 if (!Name.consume_front(PassName))
1254 return false;
1255 // normal pass name w/o parameters == default parameters
1256 if (Name.empty())
1257 return true;
1258 return Name.startswith("<") && Name.endswith(">");
1259}
1260
1261namespace {
1262
1263/// This performs customized parsing of pass name with parameters.
1264///
1265/// We do not need parametrization of passes in textual pipeline very often,
1266/// yet on a rare occasion ability to specify parameters right there can be
1267/// useful.
1268///
1269/// \p Name - parameterized specification of a pass from a textual pipeline
1270/// is a string in a form of :
1271/// PassName '<' parameter-list '>'
1272///
1273/// Parameter list is being parsed by the parser callable argument, \p Parser,
1274/// It takes a string-ref of parameters and returns either StringError or a
1275/// parameter list in a form of a custom parameters type, all wrapped into
1276/// Expected<> template class.
1277///
1278template <typename ParametersParseCallableT>
1279auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1280 StringRef PassName) -> decltype(Parser(StringRef{})) {
1281 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1282
1283 StringRef Params = Name;
1284 if (!Params.consume_front(PassName)) {
1285 assert(false &&
1286 "unable to strip pass name from parametrized pass specification");
1287 }
1288 if (Params.empty())
1289 return ParametersT{};
1290 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1291 assert(false && "invalid format for parametrized pass name");
1292 }
1293
1294 Expected<ParametersT> Result = Parser(Params);
1295 assert((Result || Result.template errorIsA<StringError>()) &&
1296 "Pass parameter parser can only return StringErrors.");
1297 return std::move(Result);
1298}
1299
1300/// Parser of parameters for LoopUnroll pass.
1301Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1302 LoopUnrollOptions UnrollOpts;
1303 while (!Params.empty()) {
1304 StringRef ParamName;
1305 std::tie(ParamName, Params) = Params.split(';');
1306 int OptLevel = StringSwitch<int>(ParamName)
1307 .Case("O0", 0)
1308 .Case("O1", 1)
1309 .Case("O2", 2)
1310 .Case("O3", 3)
1311 .Default(-1);
1312 if (OptLevel >= 0) {
1313 UnrollOpts.setOptLevel(OptLevel);
1314 continue;
1315 }
1316
1317 bool Enable = !ParamName.consume_front("no-");
1318 if (ParamName == "partial") {
1319 UnrollOpts.setPartial(Enable);
1320 } else if (ParamName == "peeling") {
1321 UnrollOpts.setPeeling(Enable);
1322 } else if (ParamName == "runtime") {
1323 UnrollOpts.setRuntime(Enable);
1324 } else if (ParamName == "upperbound") {
1325 UnrollOpts.setUpperBound(Enable);
1326 } else {
1327 return make_error<StringError>(
1328 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1329 inconvertibleErrorCode());
1330 }
1331 }
1332 return UnrollOpts;
1333}
1334
1335} // namespace
1336
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001337/// Tests whether a pass name starts with a valid prefix for a default pipeline
1338/// alias.
1339static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1340 return Name.startswith("default") || Name.startswith("thinlto") ||
1341 Name.startswith("lto");
1342}
1343
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001344/// Tests whether registered callbacks will accept a given pass name.
1345///
1346/// When parsing a pipeline text, the type of the outermost pipeline may be
1347/// omitted, in which case the type is automatically determined from the first
1348/// pass name in the text. This may be a name that is handled through one of the
1349/// callbacks. We check this through the oridinary parsing callbacks by setting
1350/// up a dummy PassManager in order to not force the client to also handle this
1351/// type of query.
1352template <typename PassManagerT, typename CallbacksT>
1353static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1354 if (!Callbacks.empty()) {
1355 PassManagerT DummyPM;
1356 for (auto &CB : Callbacks)
1357 if (CB(Name, DummyPM, {}))
1358 return true;
1359 }
1360 return false;
1361}
1362
1363template <typename CallbacksT>
1364static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001365 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001366 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001367 return DefaultAliasRegex.match(Name);
1368
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001369 // Explicitly handle pass manager names.
1370 if (Name == "module")
1371 return true;
1372 if (Name == "cgscc")
1373 return true;
1374 if (Name == "function")
1375 return true;
1376
Chandler Carruth241bf242016-08-03 07:44:48 +00001377 // Explicitly handle custom-parsed pass names.
1378 if (parseRepeatPassName(Name))
1379 return true;
1380
Chandler Carruth74a8a222016-06-17 07:15:29 +00001381#define MODULE_PASS(NAME, CREATE_PASS) \
1382 if (Name == NAME) \
1383 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001384#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001385 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001386 return true;
1387#include "PassRegistry.def"
1388
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001389 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001390}
1391
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001392template <typename CallbacksT>
1393static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001394 // Explicitly handle pass manager names.
1395 if (Name == "cgscc")
1396 return true;
1397 if (Name == "function")
1398 return true;
1399
Chandler Carruth241bf242016-08-03 07:44:48 +00001400 // Explicitly handle custom-parsed pass names.
1401 if (parseRepeatPassName(Name))
1402 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001403 if (parseDevirtPassName(Name))
1404 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001405
Chandler Carruth74a8a222016-06-17 07:15:29 +00001406#define CGSCC_PASS(NAME, CREATE_PASS) \
1407 if (Name == NAME) \
1408 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001409#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001410 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001411 return true;
1412#include "PassRegistry.def"
1413
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001414 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001415}
1416
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001417template <typename CallbacksT>
1418static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001419 // Explicitly handle pass manager names.
1420 if (Name == "function")
1421 return true;
1422 if (Name == "loop")
1423 return true;
1424
Chandler Carruth241bf242016-08-03 07:44:48 +00001425 // Explicitly handle custom-parsed pass names.
1426 if (parseRepeatPassName(Name))
1427 return true;
1428
Chandler Carruth74a8a222016-06-17 07:15:29 +00001429#define FUNCTION_PASS(NAME, CREATE_PASS) \
1430 if (Name == NAME) \
1431 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001432#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1433 if (checkParametrizedPassName(Name, NAME)) \
1434 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001435#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001436 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001437 return true;
1438#include "PassRegistry.def"
1439
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001440 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001441}
1442
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001443template <typename CallbacksT>
1444static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001445 // Explicitly handle pass manager names.
1446 if (Name == "loop")
1447 return true;
1448
Chandler Carruth241bf242016-08-03 07:44:48 +00001449 // Explicitly handle custom-parsed pass names.
1450 if (parseRepeatPassName(Name))
1451 return true;
1452
Chandler Carruth74a8a222016-06-17 07:15:29 +00001453#define LOOP_PASS(NAME, CREATE_PASS) \
1454 if (Name == NAME) \
1455 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001456#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1457 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1458 return true;
1459#include "PassRegistry.def"
1460
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001461 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001462}
1463
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001464Optional<std::vector<PassBuilder::PipelineElement>>
1465PassBuilder::parsePipelineText(StringRef Text) {
1466 std::vector<PipelineElement> ResultPipeline;
1467
1468 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1469 &ResultPipeline};
1470 for (;;) {
1471 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1472 size_t Pos = Text.find_first_of(",()");
1473 Pipeline.push_back({Text.substr(0, Pos), {}});
1474
1475 // If we have a single terminating name, we're done.
1476 if (Pos == Text.npos)
1477 break;
1478
1479 char Sep = Text[Pos];
1480 Text = Text.substr(Pos + 1);
1481 if (Sep == ',')
1482 // Just a name ending in a comma, continue.
1483 continue;
1484
1485 if (Sep == '(') {
1486 // Push the inner pipeline onto the stack to continue processing.
1487 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1488 continue;
1489 }
1490
1491 assert(Sep == ')' && "Bogus separator!");
1492 // When handling the close parenthesis, we greedily consume them to avoid
1493 // empty strings in the pipeline.
1494 do {
1495 // If we try to pop the outer pipeline we have unbalanced parentheses.
1496 if (PipelineStack.size() == 1)
1497 return None;
1498
1499 PipelineStack.pop_back();
1500 } while (Text.consume_front(")"));
1501
1502 // Check if we've finished parsing.
1503 if (Text.empty())
1504 break;
1505
1506 // Otherwise, the end of an inner pipeline always has to be followed by
1507 // a comma, and then we can continue.
1508 if (!Text.consume_front(","))
1509 return None;
1510 }
1511
1512 if (PipelineStack.size() > 1)
1513 // Unbalanced paretheses.
1514 return None;
1515
1516 assert(PipelineStack.back() == &ResultPipeline &&
1517 "Wrong pipeline at the bottom of the stack!");
1518 return {std::move(ResultPipeline)};
1519}
1520
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001521Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1522 const PipelineElement &E,
1523 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001524 auto &Name = E.Name;
1525 auto &InnerPipeline = E.InnerPipeline;
1526
1527 // First handle complex passes like the pass managers which carry pipelines.
1528 if (!InnerPipeline.empty()) {
1529 if (Name == "module") {
1530 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001531 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1532 VerifyEachPass, DebugLogging))
1533 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001534 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001535 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001536 }
1537 if (Name == "cgscc") {
1538 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001539 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1540 DebugLogging))
1541 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001542 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001543 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001544 }
1545 if (Name == "function") {
1546 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001547 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1548 VerifyEachPass, DebugLogging))
1549 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001550 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001551 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001552 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001553 if (auto Count = parseRepeatPassName(Name)) {
1554 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001555 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1556 VerifyEachPass, DebugLogging))
1557 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001558 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001559 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001560 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001561
1562 for (auto &C : ModulePipelineParsingCallbacks)
1563 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001564 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001565
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001566 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001567 return make_error<StringError>(
1568 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1569 inconvertibleErrorCode());
1570 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001571 }
1572
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001573 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001574 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001575 SmallVector<StringRef, 3> Matches;
1576 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001577 return make_error<StringError>(
1578 formatv("unknown default pipeline alias '{0}'", Name).str(),
1579 inconvertibleErrorCode());
1580
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001581 assert(Matches.size() == 3 && "Must capture two matched strings!");
1582
Jordan Rosef85a95f2016-07-25 18:34:51 +00001583 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001584 .Case("O0", O0)
1585 .Case("O1", O1)
1586 .Case("O2", O2)
1587 .Case("O3", O3)
1588 .Case("Os", Os)
1589 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001590 if (L == O0)
1591 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001592 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001593
1594 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001595 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001596 } else if (Matches[1] == "thinlto-pre-link") {
1597 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1598 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001599 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001600 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001601 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001602 } else {
1603 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001604 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001605 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001606 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001607 }
1608
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001609 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001610#define MODULE_PASS(NAME, CREATE_PASS) \
1611 if (Name == NAME) { \
1612 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001613 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001614 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001615#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1616 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001617 MPM.addPass( \
1618 RequireAnalysisPass< \
1619 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001620 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001621 } \
1622 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001623 MPM.addPass(InvalidateAnalysisPass< \
1624 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001625 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001626 }
1627#include "PassRegistry.def"
1628
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001629 for (auto &C : ModulePipelineParsingCallbacks)
1630 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001631 return Error::success();
1632 return make_error<StringError>(
1633 formatv("unknown module pass '{0}'", Name).str(),
1634 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001635}
1636
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001637Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1638 const PipelineElement &E, bool VerifyEachPass,
1639 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001640 auto &Name = E.Name;
1641 auto &InnerPipeline = E.InnerPipeline;
1642
1643 // First handle complex passes like the pass managers which carry pipelines.
1644 if (!InnerPipeline.empty()) {
1645 if (Name == "cgscc") {
1646 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001647 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1648 VerifyEachPass, DebugLogging))
1649 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001650 // Add the nested pass manager with the appropriate adaptor.
1651 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001652 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001653 }
1654 if (Name == "function") {
1655 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001656 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1657 VerifyEachPass, DebugLogging))
1658 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001659 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001660 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001661 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001662 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001663 if (auto Count = parseRepeatPassName(Name)) {
1664 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001665 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1666 VerifyEachPass, DebugLogging))
1667 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001668 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001669 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001670 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001671 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1672 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001673 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1674 VerifyEachPass, DebugLogging))
1675 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001676 CGPM.addPass(
1677 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001678 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001679 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001680
1681 for (auto &C : CGSCCPipelineParsingCallbacks)
1682 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001683 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001684
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001685 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001686 return make_error<StringError>(
1687 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1688 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001689 }
1690
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001691// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001692#define CGSCC_PASS(NAME, CREATE_PASS) \
1693 if (Name == NAME) { \
1694 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001695 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001696 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001697#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1698 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001699 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001700 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001701 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1702 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001703 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001704 } \
1705 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001706 CGPM.addPass(InvalidateAnalysisPass< \
1707 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001708 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001709 }
1710#include "PassRegistry.def"
1711
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001712 for (auto &C : CGSCCPipelineParsingCallbacks)
1713 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001714 return Error::success();
1715 return make_error<StringError>(
1716 formatv("unknown cgscc pass '{0}'", Name).str(),
1717 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001718}
1719
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001720Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1721 const PipelineElement &E,
1722 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001723 auto &Name = E.Name;
1724 auto &InnerPipeline = E.InnerPipeline;
1725
1726 // First handle complex passes like the pass managers which carry pipelines.
1727 if (!InnerPipeline.empty()) {
1728 if (Name == "function") {
1729 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001730 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1731 VerifyEachPass, DebugLogging))
1732 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001733 // Add the nested pass manager with the appropriate adaptor.
1734 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001735 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001736 }
1737 if (Name == "loop") {
1738 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001739 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1740 DebugLogging))
1741 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001742 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001743 FPM.addPass(
1744 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001745 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001746 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001747 if (auto Count = parseRepeatPassName(Name)) {
1748 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001749 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1750 VerifyEachPass, DebugLogging))
1751 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001752 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001753 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001754 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001755
1756 for (auto &C : FunctionPipelineParsingCallbacks)
1757 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001758 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001759
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001760 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001761 return make_error<StringError>(
1762 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1763 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001764 }
1765
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001766// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001767#define FUNCTION_PASS(NAME, CREATE_PASS) \
1768 if (Name == NAME) { \
1769 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001770 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001771 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001772#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1773 if (checkParametrizedPassName(Name, NAME)) { \
1774 auto Params = parsePassParameters(PARSER, Name, NAME); \
1775 if (!Params) \
1776 return Params.takeError(); \
1777 FPM.addPass(CREATE_PASS(Params.get())); \
1778 return Error::success(); \
1779 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001780#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1781 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001782 FPM.addPass( \
1783 RequireAnalysisPass< \
1784 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001785 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001786 } \
1787 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001788 FPM.addPass(InvalidateAnalysisPass< \
1789 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001790 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001791 }
1792#include "PassRegistry.def"
1793
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001794 for (auto &C : FunctionPipelineParsingCallbacks)
1795 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001796 return Error::success();
1797 return make_error<StringError>(
1798 formatv("unknown function pass '{0}'", Name).str(),
1799 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001800}
1801
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001802Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1803 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001804 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001805 auto &InnerPipeline = E.InnerPipeline;
1806
1807 // First handle complex passes like the pass managers which carry pipelines.
1808 if (!InnerPipeline.empty()) {
1809 if (Name == "loop") {
1810 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001811 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1812 VerifyEachPass, DebugLogging))
1813 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001814 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001815 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001816 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001817 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001818 if (auto Count = parseRepeatPassName(Name)) {
1819 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001820 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1821 VerifyEachPass, DebugLogging))
1822 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001823 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001824 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001825 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001826
1827 for (auto &C : LoopPipelineParsingCallbacks)
1828 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001829 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001830
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001831 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001832 return make_error<StringError>(
1833 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1834 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001835 }
1836
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001837// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001838#define LOOP_PASS(NAME, CREATE_PASS) \
1839 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001840 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001841 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001842 }
1843#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1844 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001845 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001846 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1847 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1848 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001849 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001850 } \
1851 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001852 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001853 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001854 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001855 }
1856#include "PassRegistry.def"
1857
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001858 for (auto &C : LoopPipelineParsingCallbacks)
1859 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001860 return Error::success();
1861 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1862 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001863}
1864
Chandler Carruthedf59962016-02-18 09:45:17 +00001865bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001866#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1867 if (Name == NAME) { \
1868 AA.registerModuleAnalysis< \
1869 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1870 return true; \
1871 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001872#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1873 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001874 AA.registerFunctionAnalysis< \
1875 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001876 return true; \
1877 }
1878#include "PassRegistry.def"
1879
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001880 for (auto &C : AAParsingCallbacks)
1881 if (C(Name, AA))
1882 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001883 return false;
1884}
1885
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001886Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001887 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001888 bool VerifyEachPass,
1889 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001890 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001891 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1892 return Err;
1893 // FIXME: No verifier support for Loop passes!
1894 }
1895 return Error::success();
1896}
1897
1898Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1899 ArrayRef<PipelineElement> Pipeline,
1900 bool VerifyEachPass,
1901 bool DebugLogging) {
1902 for (const auto &Element : Pipeline) {
1903 if (auto Err =
1904 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1905 return Err;
1906 if (VerifyEachPass)
1907 FPM.addPass(VerifierPass());
1908 }
1909 return Error::success();
1910}
1911
1912Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1913 ArrayRef<PipelineElement> Pipeline,
1914 bool VerifyEachPass,
1915 bool DebugLogging) {
1916 for (const auto &Element : Pipeline) {
1917 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1918 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001919 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001920 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001921 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00001922}
1923
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001924void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1925 FunctionAnalysisManager &FAM,
1926 CGSCCAnalysisManager &CGAM,
1927 ModuleAnalysisManager &MAM) {
1928 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1929 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001930 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1931 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1932 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1933 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1934 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1935}
1936
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001937Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1938 ArrayRef<PipelineElement> Pipeline,
1939 bool VerifyEachPass,
1940 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001941 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001942 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1943 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001944 if (VerifyEachPass)
1945 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001946 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001947 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001948}
1949
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001950// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00001951// FIXME: Should this routine accept a TargetMachine or require the caller to
1952// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001953Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1954 StringRef PipelineText,
1955 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001956 auto Pipeline = parsePipelineText(PipelineText);
1957 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001958 return make_error<StringError>(
1959 formatv("invalid pipeline '{0}'", PipelineText).str(),
1960 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001961
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001962 // If the first name isn't at the module layer, wrap the pipeline up
1963 // automatically.
1964 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00001965
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001966 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1967 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001968 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001969 } else if (isFunctionPassName(FirstName,
1970 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001971 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001972 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001973 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001974 } else {
1975 for (auto &C : TopLevelPipelineParsingCallbacks)
1976 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001977 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001978
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001979 // Unknown pass or pipeline name!
1980 auto &InnerPipeline = Pipeline->front().InnerPipeline;
1981 return make_error<StringError>(
1982 formatv("unknown {0} name '{1}'",
1983 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1984 .str(),
1985 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001986 }
Chandler Carruth572e3402014-04-21 11:12:00 +00001987 }
1988
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001989 if (auto Err =
1990 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1991 return Err;
1992 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001993}
Chandler Carruthedf59962016-02-18 09:45:17 +00001994
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001995// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001996Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1997 StringRef PipelineText,
1998 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001999 auto Pipeline = parsePipelineText(PipelineText);
2000 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002001 return make_error<StringError>(
2002 formatv("invalid pipeline '{0}'", PipelineText).str(),
2003 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002004
2005 StringRef FirstName = Pipeline->front().Name;
2006 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002007 return make_error<StringError>(
2008 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2009 PipelineText)
2010 .str(),
2011 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002012
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002013 if (auto Err =
2014 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2015 return Err;
2016 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002017}
2018
2019// Primary pass pipeline description parsing routine for a \c
2020// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002021Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2022 StringRef PipelineText,
2023 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002024 auto Pipeline = parsePipelineText(PipelineText);
2025 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002026 return make_error<StringError>(
2027 formatv("invalid pipeline '{0}'", PipelineText).str(),
2028 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002029
2030 StringRef FirstName = Pipeline->front().Name;
2031 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002032 return make_error<StringError>(
2033 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2034 PipelineText)
2035 .str(),
2036 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002037
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002038 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2039 DebugLogging))
2040 return Err;
2041 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002042}
2043
2044// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002045Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2046 StringRef PipelineText,
2047 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002048 auto Pipeline = parsePipelineText(PipelineText);
2049 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002050 return make_error<StringError>(
2051 formatv("invalid pipeline '{0}'", PipelineText).str(),
2052 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002053
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002054 if (auto Err =
2055 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2056 return Err;
2057
2058 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002059}
2060
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002061Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002062 // If the pipeline just consists of the word 'default' just replace the AA
2063 // manager with our default one.
2064 if (PipelineText == "default") {
2065 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002066 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002067 }
2068
Chandler Carruthedf59962016-02-18 09:45:17 +00002069 while (!PipelineText.empty()) {
2070 StringRef Name;
2071 std::tie(Name, PipelineText) = PipelineText.split(',');
2072 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002073 return make_error<StringError>(
2074 formatv("unknown alias analysis name '{0}'", Name).str(),
2075 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002076 }
2077
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002078 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002079}