blob: 576393533aac06959cc0176ee2ccf1dfd5c35f71 [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"
David Blaikie4fe1fe12018-03-23 22:11:06 +000098#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Justin Bogner19b67992015-10-30 23:13:18 +000099#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000100#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000101#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000102#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000103#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000104#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000105#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000106#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000107#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000108#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000109#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000110#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000111#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000112#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000113#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000114#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000115#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000116#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000117#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000118#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000119#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000120#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000121#include "llvm/Transforms/Scalar/LoopDistribute.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000122#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000123#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000124#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000125#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000126#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000127#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000128#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000129#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000130#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000131#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000132#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000133#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000134#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000135#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000136#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000137#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000138#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000139#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000140#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000141#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000142#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000143#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000144#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000145#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000146#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000147#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000148#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000149#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000150#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000151#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000152#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000153#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000154#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000155#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000156#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000157#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000158#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000159#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000160#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000161#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000162#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000163#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000164#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000165#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000166#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000167#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000168
Chandler Carruth66445382014-01-11 08:16:35 +0000169using namespace llvm;
170
Chandler Carruth719ffe12017-02-12 05:38:04 +0000171static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
172 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000173static cl::opt<bool>
174 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
175 cl::Hidden, cl::ZeroOrMore,
176 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000177
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000178static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000179 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000180 cl::Hidden, cl::ZeroOrMore,
181 cl::desc("Run NewGVN instead of GVN"));
182
Geoff Berry3cca1da2017-06-10 15:20:03 +0000183static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000184 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
185 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000186
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000187static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000188 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
189 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000190
Davide Italianobe1b6a92017-06-03 23:18:29 +0000191static cl::opt<bool> EnableGVNSink(
192 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
193 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
194
David Green963401d2018-07-01 12:47:30 +0000195static cl::opt<bool> EnableUnrollAndJam(
196 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
197 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
198
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000199static cl::opt<bool> EnableSyntheticCounts(
200 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
201 cl::desc("Run synthetic function entry count generation "
202 "pass"));
203
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000204static Regex DefaultAliasRegex(
205 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000206
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000207static cl::opt<bool>
208 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
209 cl::desc("Enable control height reduction optimization (CHR)"));
210
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000211extern cl::opt<bool> EnableHotColdSplit;
212
Chandler Carruthe3f50642016-12-22 06:59:15 +0000213static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
214 switch (Level) {
215 case PassBuilder::O0:
216 case PassBuilder::O1:
217 case PassBuilder::O2:
218 case PassBuilder::O3:
219 return false;
220
221 case PassBuilder::Os:
222 case PassBuilder::Oz:
223 return true;
224 }
225 llvm_unreachable("Invalid optimization level!");
226}
227
Chandler Carruth66445382014-01-11 08:16:35 +0000228namespace {
229
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000230/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000231struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000232 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000233 return PreservedAnalyses::all();
234 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000235 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000236};
237
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000238/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000239class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
240 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000241 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000242
243public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000244 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000245 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000246 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000247};
248
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000249/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000250struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000251 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
252 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000253 return PreservedAnalyses::all();
254 }
255 static StringRef name() { return "NoOpCGSCCPass"; }
256};
257
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000258/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000259class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
260 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000261 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000262
263public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000264 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000265 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000266 return Result();
267 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000268 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000269};
270
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000271/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000272struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000273 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000274 return PreservedAnalyses::all();
275 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000276 static StringRef name() { return "NoOpFunctionPass"; }
277};
278
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000279/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000280class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
281 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000282 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000283
284public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000285 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000286 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000287 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000288};
289
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000290/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000291struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000292 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
293 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000294 return PreservedAnalyses::all();
295 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000296 static StringRef name() { return "NoOpLoopPass"; }
297};
298
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000299/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000300class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
301 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000302 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000303
304public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000305 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000306 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
307 return Result();
308 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000309 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000310};
311
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000312AnalysisKey NoOpModuleAnalysis::Key;
313AnalysisKey NoOpCGSCCAnalysis::Key;
314AnalysisKey NoOpFunctionAnalysis::Key;
315AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000316
Chandler Carruth66445382014-01-11 08:16:35 +0000317} // End anonymous namespace.
318
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000319void PassBuilder::invokePeepholeEPCallbacks(
320 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
321 for (auto &C : PeepholeEPCallbacks)
322 C(FPM, Level);
323}
324
Chandler Carruth1ff77242015-03-07 09:02:36 +0000325void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000326#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000327 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000328#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000329
330 for (auto &C : ModuleAnalysisRegistrationCallbacks)
331 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000332}
333
Chandler Carruth1ff77242015-03-07 09:02:36 +0000334void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000335#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000336 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000337#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000338
339 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
340 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000341}
342
Chandler Carruth1ff77242015-03-07 09:02:36 +0000343void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000344#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000345 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000346#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000347
348 for (auto &C : FunctionAnalysisRegistrationCallbacks)
349 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000350}
351
Justin Bognereecc3c82016-02-25 07:23:08 +0000352void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000353#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000354 LAM.registerPass([&] { return CREATE_PASS; });
355#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000356
357 for (auto &C : LoopAnalysisRegistrationCallbacks)
358 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000359}
360
Chandler Carruthe3f50642016-12-22 06:59:15 +0000361FunctionPassManager
362PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000363 ThinLTOPhase Phase,
364 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000365 assert(Level != O0 && "Must request optimizations!");
366 FunctionPassManager FPM(DebugLogging);
367
368 // Form SSA out of local memory accesses after breaking apart aggregates into
369 // scalars.
370 FPM.addPass(SROA());
371
372 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000373 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000374
Davide Italianoc3688312017-06-01 23:08:14 +0000375 // Hoisting of scalars and load expressions.
376 if (EnableGVNHoist)
377 FPM.addPass(GVNHoistPass());
378
Davide Italianobe1b6a92017-06-03 23:18:29 +0000379 // Global value numbering based sinking.
380 if (EnableGVNSink) {
381 FPM.addPass(GVNSinkPass());
382 FPM.addPass(SimplifyCFGPass());
383 }
384
Chandler Carruthe3f50642016-12-22 06:59:15 +0000385 // Speculative execution if the target has divergent branches; otherwise nop.
386 FPM.addPass(SpeculativeExecutionPass());
387
388 // Optimize based on known information about branches, and cleanup afterward.
389 FPM.addPass(JumpThreadingPass());
390 FPM.addPass(CorrelatedValuePropagationPass());
391 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000392 if (Level == O3)
393 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000394 FPM.addPass(InstCombinePass());
395
396 if (!isOptimizingForSize(Level))
397 FPM.addPass(LibCallsShrinkWrapPass());
398
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000399 invokePeepholeEPCallbacks(FPM, Level);
400
Rong Xue1f42452017-10-23 22:21:29 +0000401 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
402 // using the size value profile. Don't perform this when optimizing for size.
403 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
404 !isOptimizingForSize(Level))
405 FPM.addPass(PGOMemOPSizeOpt());
406
Chandler Carruthe3f50642016-12-22 06:59:15 +0000407 FPM.addPass(TailCallElimPass());
408 FPM.addPass(SimplifyCFGPass());
409
410 // Form canonically associated expression trees, and simplify the trees using
411 // basic mathematical properties. For example, this will form (nearly)
412 // minimal multiplication trees.
413 FPM.addPass(ReassociatePass());
414
415 // Add the primary loop simplification pipeline.
416 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000417 // some function passes in between them. These can and should be removed
418 // and/or replaced by scheduling the loop pass equivalents in the correct
419 // positions. But those equivalent passes aren't powerful enough yet.
420 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
421 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
422 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
423 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000424 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
425
Chandler Carruth71fd2702018-05-30 02:46:45 +0000426 // Simplify the loop body. We do this initially to clean up after other loop
427 // passes run, either when iterating on a loop or on inner loops with
428 // implications on the outer loop.
429 LPM1.addPass(LoopInstSimplifyPass());
430 LPM1.addPass(LoopSimplifyCFGPass());
431
Chandler Carruthe3f50642016-12-22 06:59:15 +0000432 // Rotate Loop - disable header duplication at -Oz
433 LPM1.addPass(LoopRotatePass(Level != Oz));
434 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000435 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000436 LPM2.addPass(IndVarSimplifyPass());
437 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000438
439 for (auto &C : LateLoopOptimizationsEPCallbacks)
440 C(LPM2, Level);
441
Chandler Carruth79b733b2017-01-26 23:21:17 +0000442 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000443 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000444 // because it changes IR to makes profile annotation in back compile
445 // inaccurate.
Dehao Chen95f00302017-07-30 04:55:39 +0000446 if (Phase != ThinLTOPhase::PreLink ||
447 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnsonecd90132017-08-02 20:35:29 +0000448 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000449
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000450 for (auto &C : LoopOptimizerEndEPCallbacks)
451 C(LPM2, Level);
452
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000453 // We provide the opt remark emitter pass for LICM to use. We only need to do
454 // this once as it is immutable.
455 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000456 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000457 FPM.addPass(SimplifyCFGPass());
458 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000459 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000460
461 // Eliminate redundancies.
462 if (Level != O1) {
463 // These passes add substantial compile time so skip them at O1.
464 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000465 if (RunNewGVN)
466 FPM.addPass(NewGVNPass());
467 else
468 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000469 }
470
471 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
472 FPM.addPass(MemCpyOptPass());
473
474 // Sparse conditional constant propagation.
475 // FIXME: It isn't clear why we do this *after* loop passes rather than
476 // before...
477 FPM.addPass(SCCPPass());
478
479 // Delete dead bit computations (instcombine runs after to fold away the dead
480 // computations, and then ADCE will run later to exploit any new DCE
481 // opportunities that creates).
482 FPM.addPass(BDCEPass());
483
484 // Run instcombine after redundancy and dead bit elimination to exploit
485 // opportunities opened up by them.
486 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000487 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000488
489 // Re-consider control flow based optimizations after redundancy elimination,
490 // redo DCE, etc.
491 FPM.addPass(JumpThreadingPass());
492 FPM.addPass(CorrelatedValuePropagationPass());
493 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000494 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000495
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000496 for (auto &C : ScalarOptimizerLateEPCallbacks)
497 C(FPM, Level);
498
Chandler Carruthe3f50642016-12-22 06:59:15 +0000499 // Finally, do an expensive DCE pass to catch all the dead code exposed by
500 // the simplifications and basic cleanup after all the simplifications.
501 FPM.addPass(ADCEPass());
502 FPM.addPass(SimplifyCFGPass());
503 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000504 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000505
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000506 if (EnableCHR && Level == O3 && PGOOpt &&
507 (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty()))
508 FPM.addPass(ControlHeightReductionPass());
509
Chandler Carruthe3f50642016-12-22 06:59:15 +0000510 return FPM;
511}
512
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000513void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
514 PassBuilder::OptimizationLevel Level,
515 bool RunProfileGen,
516 std::string ProfileGenFile,
Richard Smith6c676622018-10-10 23:13:47 +0000517 std::string ProfileUseFile,
518 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000519 // Generally running simplification passes and the inliner with an high
520 // threshold results in smaller executables, but there may be cases where
521 // the size grows, so let's be conservative here and skip this simplification
522 // at -Os/Oz.
523 if (!isOptimizingForSize(Level)) {
524 InlineParams IP;
525
526 // In the old pass manager, this is a cl::opt. Should still this be one?
527 IP.DefaultThreshold = 75;
528
529 // FIXME: The hint threshold has the same value used by the regular inliner.
530 // This should probably be lowered after performance testing.
531 // FIXME: this comment is cargo culted from the old pass manager, revisit).
532 IP.HintThreshold = 325;
533
534 CGSCCPassManager CGPipeline(DebugLogging);
535
536 CGPipeline.addPass(InlinerPass(IP));
537
538 FunctionPassManager FPM;
539 FPM.addPass(SROA());
540 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
541 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
542 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000543 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000544
Davide Italiano513dfaa2017-02-13 15:26:22 +0000545 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
546
547 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
548 }
549
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000550 // Delete anything that is now dead to make sure that we don't instrument
551 // dead code. Instrumentation can end up keeping dead code around and
552 // dramatically increase code size.
553 MPM.addPass(GlobalDCEPass());
554
Davide Italiano513dfaa2017-02-13 15:26:22 +0000555 if (RunProfileGen) {
556 MPM.addPass(PGOInstrumentationGen());
557
Xinliang David Lib67530e2017-06-25 00:26:43 +0000558 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000559 FPM.addPass(
560 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000561 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
562
Davide Italiano513dfaa2017-02-13 15:26:22 +0000563 // Add the profile lowering pass.
564 InstrProfOptions Options;
565 if (!ProfileGenFile.empty())
566 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000567 Options.DoCounterPromotion = true;
Davide Italiano513dfaa2017-02-13 15:26:22 +0000568 MPM.addPass(InstrProfiling(Options));
569 }
570
571 if (!ProfileUseFile.empty())
Richard Smith6c676622018-10-10 23:13:47 +0000572 MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000573}
574
Easwaran Raman8249fac2017-06-28 13:33:49 +0000575static InlineParams
576getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
577 auto O3 = PassBuilder::O3;
578 unsigned OptLevel = Level > O3 ? 2 : Level;
579 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
580 return getInlineParams(OptLevel, SizeLevel);
581}
582
Chandler Carruthe3f50642016-12-22 06:59:15 +0000583ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000584PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000585 ThinLTOPhase Phase,
586 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000587 ModulePassManager MPM(DebugLogging);
588
Chandler Carruthe3f50642016-12-22 06:59:15 +0000589 // Do basic inference of function attributes from known properties of system
590 // libraries and other oracles.
591 MPM.addPass(InferFunctionAttrsPass());
592
593 // Create an early function pass manager to cleanup the output of the
594 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000595 FunctionPassManager EarlyFPM(DebugLogging);
596 EarlyFPM.addPass(SimplifyCFGPass());
597 EarlyFPM.addPass(SROA());
598 EarlyFPM.addPass(EarlyCSEPass());
599 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000600 if (Level == O3)
601 EarlyFPM.addPass(CallSiteSplittingPass());
602
Dehao Chen08f88312017-08-07 20:23:20 +0000603 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
604 // to convert bitcast to direct calls so that they can be inlined during the
605 // profile annotation prepration step.
606 // More details about SamplePGO design can be found in:
607 // https://research.google.com/pubs/pub45290.html
608 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
609 if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
610 Phase == ThinLTOPhase::PostLink)
611 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000612 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000613
Dehao Chen08f88312017-08-07 20:23:20 +0000614 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
615 // Annotate sample profile right after early FPM to ensure freshness of
616 // the debug info.
Dehao Chend26dae02017-10-01 05:24:51 +0000617 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000618 PGOOpt->ProfileRemappingFile,
Dehao Chend26dae02017-10-01 05:24:51 +0000619 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000620 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
621 // for the profile annotation to be accurate in the ThinLTO backend.
622 if (Phase != ThinLTOPhase::PreLink)
623 // We perform early indirect call promotion here, before globalopt.
624 // This is important for the ThinLTO backend phase because otherwise
625 // imported available_externally functions look unreferenced and are
626 // removed.
627 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
628 true));
629 }
630
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000631 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000632 // and prior to optimizing globals.
633 // FIXME: This position in the pipeline hasn't been carefully considered in
634 // years, it should be re-analyzed.
635 MPM.addPass(IPSCCPPass());
636
Matthew Simpsoncb585582017-10-25 13:40:08 +0000637 // Attach metadata to indirect call sites indicating the set of functions
638 // they may target at run-time. This should follow IPSCCP.
639 MPM.addPass(CalledValuePropagationPass());
640
Chandler Carruthe3f50642016-12-22 06:59:15 +0000641 // Optimize globals to try and fold them into constants.
642 MPM.addPass(GlobalOptPass());
643
644 // Promote any localized globals to SSA registers.
645 // FIXME: Should this instead by a run of SROA?
646 // FIXME: We should probably run instcombine and simplify-cfg afterward to
647 // delete control flows that are dead once globals have been folded to
648 // constants.
649 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
650
651 // Remove any dead arguments exposed by cleanups and constand folding
652 // globals.
653 MPM.addPass(DeadArgumentEliminationPass());
654
655 // Create a small function pass pipeline to cleanup after all the global
656 // optimizations.
657 FunctionPassManager GlobalCleanupPM(DebugLogging);
658 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000659 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
660
Chandler Carruthe3f50642016-12-22 06:59:15 +0000661 GlobalCleanupPM.addPass(SimplifyCFGPass());
662 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
663
Dehao Chen89d32262017-08-02 01:28:31 +0000664 // Add all the requested passes for instrumentation PGO, if requested.
665 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
666 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
667 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
Richard Smith6c676622018-10-10 23:13:47 +0000668 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
669 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000670 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000671 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000672
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000673 // Synthesize function entry counts for non-PGO compilation.
674 if (EnableSyntheticCounts && !PGOOpt)
675 MPM.addPass(SyntheticCountsPropagation());
676
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000677 // Require the GlobalsAA analysis for the module so we can query it within
678 // the CGSCC pipeline.
679 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000680
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000681 // Require the ProfileSummaryAnalysis for the module so we can query it within
682 // the inliner pass.
683 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
684
Chandler Carruthe3f50642016-12-22 06:59:15 +0000685 // Now begin the main postorder CGSCC pipeline.
686 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
687 // manager and trying to emulate its precise behavior. Much of this doesn't
688 // make a lot of sense and we should revisit the core CGSCC structure.
689 CGSCCPassManager MainCGPipeline(DebugLogging);
690
691 // Note: historically, the PruneEH pass was run first to deduce nounwind and
692 // generally clean up exception handling overhead. It isn't clear this is
693 // valuable as the inliner doesn't currently care whether it is inlining an
694 // invoke or a call.
695
696 // Run the inliner first. The theory is that we are walking bottom-up and so
697 // the callees have already been fully optimized, and we want to inline them
698 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000699 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000700 // because it makes profile annotation in the backend inaccurate.
701 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000702 if (Phase == ThinLTOPhase::PreLink &&
703 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000704 IP.HotCallSiteThreshold = 0;
705 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000706
707 // Now deduce any function attributes based in the current code.
708 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
709
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000710 // When at O3 add argument promotion to the pass pipeline.
711 // FIXME: It isn't at all clear why this should be limited to O3.
712 if (Level == O3)
713 MainCGPipeline.addPass(ArgumentPromotionPass());
714
Chandler Carruthe3f50642016-12-22 06:59:15 +0000715 // Lastly, add the core function simplification pipeline nested inside the
716 // CGSCC walk.
717 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000718 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000719
Teresa Johnsond7253352018-10-23 22:57:40 +0000720 // We only want to do hot cold splitting once for ThinLTO, during the
721 // post-link ThinLTO.
722 if (EnableHotColdSplit && Phase != ThinLTOPhase::PreLink)
Aditya Kumard9e2e382018-10-21 18:11:56 +0000723 MPM.addPass(HotColdSplittingPass());
724
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000725 for (auto &C : CGSCCOptimizerLateEPCallbacks)
726 C(MainCGPipeline, Level);
727
Chandler Carruth719ffe12017-02-12 05:38:04 +0000728 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
729 // to detect when we devirtualize indirect calls and iterate the SCC passes
730 // in that case to try and catch knock-on inlining or function attrs
731 // opportunities. Then we add it to the module pipeline by walking the SCCs
732 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000733 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000734 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000735 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000736
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000737 return MPM;
738}
739
740ModulePassManager
741PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
742 bool DebugLogging) {
743 ModulePassManager MPM(DebugLogging);
744
745 // Optimize globals now that the module is fully simplified.
746 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000747 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000748
Xinliang David Li126157c2017-05-22 16:41:57 +0000749 // Run partial inlining pass to partially inline functions that have
750 // large bodies.
751 if (RunPartialInlining)
752 MPM.addPass(PartialInlinerPass());
753
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000754 // Remove avail extern fns and globals definitions since we aren't compiling
755 // an object file for later LTO. For LTO we want to preserve these so they
756 // are eligible for inlining at link-time. Note if they are unreferenced they
757 // will be removed by GlobalDCE later, so this only impacts referenced
758 // available externally globals. Eventually they will be suppressed during
759 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
760 // may make globals referenced by available external functions dead and saves
761 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000762 MPM.addPass(EliminateAvailableExternallyPass());
763
764 // Do RPO function attribute inference across the module to forward-propagate
765 // attributes where applicable.
766 // FIXME: Is this really an optimization rather than a canonicalization?
767 MPM.addPass(ReversePostOrderFunctionAttrsPass());
768
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000769 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000770 // useful as the above will have inlined, DCE'ed, and function-attr
771 // propagated everything. We should at this point have a reasonably minimal
772 // and richly annotated call graph. By computing aliasing and mod/ref
773 // information for all local globals here, the late loop passes and notably
774 // the vectorizer will be able to use them to help recognize vectorizable
775 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000776 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000777
778 FunctionPassManager OptimizePM(DebugLogging);
779 OptimizePM.addPass(Float2IntPass());
780 // FIXME: We need to run some loop optimizations to re-rotate loops after
781 // simplify-cfg and others undo their rotation.
782
783 // Optimize the loop execution. These passes operate on entire loop nests
784 // rather than on each loop in an inside-out manner, and so they are actually
785 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000786
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000787 for (auto &C : VectorizerStartEPCallbacks)
788 C(OptimizePM, Level);
789
Chandler Carrutha95ff382017-01-27 00:50:21 +0000790 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000791 OptimizePM.addPass(
792 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000793
794 // Distribute loops to allow partial vectorization. I.e. isolate dependences
795 // into separate loop that would otherwise inhibit vectorization. This is
796 // currently only performed for loops marked with the metadata
797 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000798 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000799
800 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000801 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000802
Chandler Carruthbaabda92017-01-27 01:32:26 +0000803 // Eliminate loads by forwarding stores from the previous iteration to loads
804 // of the current iteration.
805 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000806
807 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000808 OptimizePM.addPass(InstCombinePass());
809
Chandler Carrutha95ff382017-01-27 00:50:21 +0000810 // Now that we've formed fast to execute loop structures, we do further
811 // optimizations. These are run afterward as they might block doing complex
812 // analyses and transforms such as what are needed for loop vectorization.
813
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000814 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
815 // GVN, loop transforms, and others have already run, so it's now better to
816 // convert to more optimized IR using more aggressive simplify CFG options.
817 // The extra sinking transform can create larger basic blocks, so do this
818 // before SLP vectorization.
819 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
820 forwardSwitchCondToPhi(true).
821 convertSwitchToLookupTable(true).
822 needCanonicalLoops(false).
823 sinkCommonInsts(true)));
824
Chandler Carruthe3f50642016-12-22 06:59:15 +0000825 // Optimize parallel scalar instruction chains into SIMD instructions.
826 OptimizePM.addPass(SLPVectorizerPass());
827
Chandler Carruthe3f50642016-12-22 06:59:15 +0000828 OptimizePM.addPass(InstCombinePass());
829
830 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000831 // execution resources of an out-of-order processor. We also then need to
832 // clean up redundancies and loop invariant code.
833 // FIXME: It would be really good to use a loop-integrated instruction
834 // combiner for cleanup here so that the unrolling and LICM can be pipelined
835 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000836 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
837 if (EnableUnrollAndJam) {
838 OptimizePM.addPass(
839 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
840 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000841 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000842 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000843 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000844 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000845 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000846
847 // Now that we've vectorized and unrolled loops, we may have more refined
848 // alignment information, try to re-derive it here.
849 OptimizePM.addPass(AlignmentFromAssumptionsPass());
850
Chandler Carrutha95ff382017-01-27 00:50:21 +0000851 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
852 // canonicalization pass that enables other optimizations. As a result,
853 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
854 // result too early.
855 OptimizePM.addPass(LoopSinkPass());
856
857 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000858 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000859
Sanjay Patel6fd43912017-09-09 13:38:18 +0000860 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
861 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
862 // flattening of blocks.
863 OptimizePM.addPass(DivRemPairsPass());
864
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000865 // LoopSink (and other loop passes since the last simplifyCFG) might have
866 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
867 OptimizePM.addPass(SimplifyCFGPass());
868
Chandler Carruthc34f7892017-11-28 11:32:31 +0000869 // Optimize PHIs by speculating around them when profitable. Note that this
870 // pass needs to be run after any PRE or similar pass as it is essentially
871 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
872 OptimizePM.addPass(SpeculateAroundPHIsPass());
873
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000874 for (auto &C : OptimizerLastEPCallbacks)
875 C(OptimizePM, Level);
876
Chandler Carrutha95ff382017-01-27 00:50:21 +0000877 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000878 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
879
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000880 MPM.addPass(CGProfilePass());
881
Chandler Carruthe3f50642016-12-22 06:59:15 +0000882 // Now we need to do some global optimization transforms.
883 // FIXME: It would seem like these should come first in the optimization
884 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
885 // ordering here.
886 MPM.addPass(GlobalDCEPass());
887 MPM.addPass(ConstantMergePass());
888
889 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000890}
891
Chandler Carruthe3f50642016-12-22 06:59:15 +0000892ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000893PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
894 bool DebugLogging) {
895 assert(Level != O0 && "Must request optimizations for the default pipeline!");
896
897 ModulePassManager MPM(DebugLogging);
898
899 // Force any function attributes we want the rest of the pipeline to observe.
900 MPM.addPass(ForceFunctionAttrsPass());
901
David Blaikie0c64f5a2018-01-23 01:25:20 +0000902 // Apply module pipeline start EP callback.
903 for (auto &C : PipelineStartEPCallbacks)
904 C(MPM);
905
Dehao Chen08f88312017-08-07 20:23:20 +0000906 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000907 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
908
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000909 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000910 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
911 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000912
913 // Now add the optimization pipeline.
914 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
915
916 return MPM;
917}
918
919ModulePassManager
920PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
921 bool DebugLogging) {
922 assert(Level != O0 && "Must request optimizations for the default pipeline!");
923
924 ModulePassManager MPM(DebugLogging);
925
926 // Force any function attributes we want the rest of the pipeline to observe.
927 MPM.addPass(ForceFunctionAttrsPass());
928
Dehao Chen08f88312017-08-07 20:23:20 +0000929 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000930 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
931
David Blaikie0c64f5a2018-01-23 01:25:20 +0000932 // Apply module pipeline start EP callback.
933 for (auto &C : PipelineStartEPCallbacks)
934 C(MPM);
935
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000936 // If we are planning to perform ThinLTO later, we don't bloat the code with
937 // unrolling/vectorization/... now. Just simplify the module as much as we
938 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000939 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
940 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000941
942 // Run partial inlining pass to partially inline functions that have
943 // large bodies.
944 // FIXME: It isn't clear whether this is really the right place to run this
945 // in ThinLTO. Because there is another canonicalization and simplification
946 // phase that will run after the thin link, running this here ends up with
947 // less information than will be available later and it may grow functions in
948 // ways that aren't beneficial.
949 if (RunPartialInlining)
950 MPM.addPass(PartialInlinerPass());
951
952 // Reduce the size of the IR as much as possible.
953 MPM.addPass(GlobalOptPass());
954
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000955 return MPM;
956}
957
Teresa Johnson28023db2018-07-19 14:51:32 +0000958ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
959 OptimizationLevel Level, bool DebugLogging,
960 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000961 ModulePassManager MPM(DebugLogging);
962
Teresa Johnson28023db2018-07-19 14:51:32 +0000963 if (ImportSummary) {
964 // These passes import type identifier resolutions for whole-program
965 // devirtualization and CFI. They must run early because other passes may
966 // disturb the specific instruction patterns that these passes look for,
967 // creating dependencies on resolutions that may not appear in the summary.
968 //
969 // For example, GVN may transform the pattern assume(type.test) appearing in
970 // two basic blocks into assume(phi(type.test, type.test)), which would
971 // transform a dependency on a WPD resolution into a dependency on a type
972 // identifier resolution for CFI.
973 //
974 // Also, WPD has access to more precise information than ICP and can
975 // devirtualize more effectively, so it should operate on the IR first.
976 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
977 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
978 }
979
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000980 // Force any function attributes we want the rest of the pipeline to observe.
981 MPM.addPass(ForceFunctionAttrsPass());
982
983 // During the ThinLTO backend phase we perform early indirect call promotion
984 // here, before globalopt. Otherwise imported available_externally functions
985 // look unreferenced and are removed.
Dehao Chen08f88312017-08-07 20:23:20 +0000986 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
987 // with SamplePGO.
Dehao Chen2f4e2e22017-08-10 05:10:32 +0000988 if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
Dehao Chen08f88312017-08-07 20:23:20 +0000989 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
990 false /* SamplePGO */));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000991
992 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000993 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
994 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000995
996 // Now add the optimization pipeline.
997 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
998
999 return MPM;
1000}
1001
1002ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001003PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1004 bool DebugLogging) {
1005 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001006 // FIXME: We should use a customized pre-link pipeline!
Chandler Carruthe3f50642016-12-22 06:59:15 +00001007 return buildPerModuleDefaultPipeline(Level, DebugLogging);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001008}
1009
Teresa Johnson28023db2018-07-19 14:51:32 +00001010ModulePassManager
1011PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1012 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001013 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1014 ModulePassManager MPM(DebugLogging);
1015
Xin Tong642c8d32018-11-15 18:06:42 +00001016 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
1017 // Load sample profile before running the LTO optimization pipeline.
1018 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
1019 PGOOpt->ProfileRemappingFile,
1020 false /* ThinLTOPhase::PreLink */));
1021 }
1022
Davide Italiano089a9122017-01-24 00:57:39 +00001023 // Remove unused virtual tables to improve the quality of code generated by
1024 // whole-program devirtualization and bitset lowering.
1025 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001026
Davide Italiano089a9122017-01-24 00:57:39 +00001027 // Force any function attributes we want the rest of the pipeline to observe.
1028 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001029
Davide Italiano089a9122017-01-24 00:57:39 +00001030 // Do basic inference of function attributes from known properties of system
1031 // libraries and other oracles.
1032 MPM.addPass(InferFunctionAttrsPass());
1033
1034 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001035 FunctionPassManager EarlyFPM(DebugLogging);
1036 EarlyFPM.addPass(CallSiteSplittingPass());
1037 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1038
Davide Italiano089a9122017-01-24 00:57:39 +00001039 // Indirect call promotion. This should promote all the targets that are
1040 // left by the earlier promotion pass that promotes intra-module targets.
1041 // This two-step promotion is to save the compile time. For LTO, it should
1042 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001043 MPM.addPass(PGOIndirectCallPromotion(
1044 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +00001045 // Propagate constants at call sites into the functions they call. This
1046 // opens opportunities for globalopt (and inlining) by substituting function
1047 // pointers passed as arguments to direct uses of functions.
1048 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001049
1050 // Attach metadata to indirect call sites indicating the set of functions
1051 // they may target at run-time. This should follow IPSCCP.
1052 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001053 }
1054
1055 // Now deduce any function attributes based in the current code.
1056 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1057 PostOrderFunctionAttrsPass()));
1058
1059 // Do RPO function attribute inference across the module to forward-propagate
1060 // attributes where applicable.
1061 // FIXME: Is this really an optimization rather than a canonicalization?
1062 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1063
1064 // Use inragne annotations on GEP indices to split globals where beneficial.
1065 MPM.addPass(GlobalSplitPass());
1066
1067 // Run whole program optimization of virtual call when the list of callees
1068 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001069 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001070
1071 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001072 if (Level == 1) {
1073 // The LowerTypeTestsPass needs to run to lower type metadata and the
1074 // type.test intrinsics. The pass does nothing if CFI is disabled.
1075 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001076 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001077 }
Davide Italiano089a9122017-01-24 00:57:39 +00001078
1079 // Optimize globals to try and fold them into constants.
1080 MPM.addPass(GlobalOptPass());
1081
1082 // Promote any localized globals to SSA registers.
1083 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1084
1085 // Linking modules together can lead to duplicate global constant, only
1086 // keep one copy of each constant.
1087 MPM.addPass(ConstantMergePass());
1088
1089 // Remove unused arguments from functions.
1090 MPM.addPass(DeadArgumentEliminationPass());
1091
1092 // Reduce the code after globalopt and ipsccp. Both can open up significant
1093 // simplification opportunities, and both can propagate functions through
1094 // function pointers. When this happens, we often have to resolve varargs
1095 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001096 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001097 if (Level == O3)
1098 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001099 PeepholeFPM.addPass(InstCombinePass());
1100 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1101
1102 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001103
1104 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1105 // generally clean up exception handling overhead. It isn't clear this is
1106 // valuable as the inliner doesn't currently care whether it is inlining an
1107 // invoke or a call.
1108 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001109 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1110 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001111
1112 // Optimize globals again after we ran the inliner.
1113 MPM.addPass(GlobalOptPass());
1114
1115 // Garbage collect dead functions.
1116 // FIXME: Add ArgumentPromotion pass after once it's ported.
1117 MPM.addPass(GlobalDCEPass());
1118
1119 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001120 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001121 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001122 invokePeepholeEPCallbacks(FPM, Level);
1123
Davide Italiano089a9122017-01-24 00:57:39 +00001124 FPM.addPass(JumpThreadingPass());
1125
1126 // Break up allocas
1127 FPM.addPass(SROA());
1128
1129 // Run a few AA driver optimizations here and now to cleanup the code.
1130 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1131
1132 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1133 PostOrderFunctionAttrsPass()));
1134 // FIXME: here we run IP alias analysis in the legacy PM.
1135
1136 FunctionPassManager MainFPM;
1137
1138 // FIXME: once we fix LoopPass Manager, add LICM here.
1139 // FIXME: once we provide support for enabling MLSM, add it here.
1140 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001141 if (RunNewGVN)
1142 MainFPM.addPass(NewGVNPass());
1143 else
1144 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001145
1146 // Remove dead memcpy()'s.
1147 MainFPM.addPass(MemCpyOptPass());
1148
1149 // Nuke dead stores.
1150 MainFPM.addPass(DSEPass());
1151
1152 // FIXME: at this point, we run a bunch of loop passes:
1153 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1154 // loopVectorize. Enable them once the remaining issue with LPM
1155 // are sorted out.
1156
1157 MainFPM.addPass(InstCombinePass());
1158 MainFPM.addPass(SimplifyCFGPass());
1159 MainFPM.addPass(SCCPPass());
1160 MainFPM.addPass(InstCombinePass());
1161 MainFPM.addPass(BDCEPass());
1162
1163 // FIXME: We may want to run SLPVectorizer here.
1164 // After vectorization, assume intrinsics may tell us more
1165 // about pointer alignments.
1166#if 0
1167 MainFPM.add(AlignmentFromAssumptionsPass());
1168#endif
1169
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001170 // FIXME: Conditionally run LoadCombine here, after it's ported
1171 // (in case we still have this pass, given its questionable usefulness).
1172
Davide Italiano089a9122017-01-24 00:57:39 +00001173 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001174 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001175 MainFPM.addPass(JumpThreadingPass());
1176 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1177
1178 // Create a function that performs CFI checks for cross-DSO calls with
1179 // targets in the current module.
1180 MPM.addPass(CrossDSOCFIPass());
1181
1182 // Lower type metadata and the type.test intrinsic. This pass supports
1183 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1184 // to be run at link time if CFI is enabled. This pass does nothing if
1185 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001186 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001187
1188 // Add late LTO optimization passes.
1189 // Delete basic blocks, which optimization passes may have killed.
1190 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1191
1192 // Drop bodies of available eternally objects to improve GlobalDCE.
1193 MPM.addPass(EliminateAvailableExternallyPass());
1194
1195 // Now that we have optimized the program, discard unreachable functions.
1196 MPM.addPass(GlobalDCEPass());
1197
1198 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001199 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001200}
1201
Chandler Carruth060ad612016-12-23 20:38:19 +00001202AAManager PassBuilder::buildDefaultAAPipeline() {
1203 AAManager AA;
1204
1205 // The order in which these are registered determines their priority when
1206 // being queried.
1207
1208 // First we register the basic alias analysis that provides the majority of
1209 // per-function local AA logic. This is a stateless, on-demand local set of
1210 // AA techniques.
1211 AA.registerFunctionAnalysis<BasicAA>();
1212
1213 // Next we query fast, specialized alias analyses that wrap IR-embedded
1214 // information about aliasing.
1215 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1216 AA.registerFunctionAnalysis<TypeBasedAA>();
1217
1218 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001219 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1220 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001221 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001222 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001223
1224 return AA;
1225}
1226
Chandler Carruth241bf242016-08-03 07:44:48 +00001227static Optional<int> parseRepeatPassName(StringRef Name) {
1228 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1229 return None;
1230 int Count;
1231 if (Name.getAsInteger(0, Count) || Count <= 0)
1232 return None;
1233 return Count;
1234}
1235
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001236static Optional<int> parseDevirtPassName(StringRef Name) {
1237 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1238 return None;
1239 int Count;
1240 if (Name.getAsInteger(0, Count) || Count <= 0)
1241 return None;
1242 return Count;
1243}
1244
Fedor Sergeevb7871402019-01-10 10:01:53 +00001245static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1246 if (!Name.consume_front(PassName))
1247 return false;
1248 // normal pass name w/o parameters == default parameters
1249 if (Name.empty())
1250 return true;
1251 return Name.startswith("<") && Name.endswith(">");
1252}
1253
1254namespace {
1255
1256/// This performs customized parsing of pass name with parameters.
1257///
1258/// We do not need parametrization of passes in textual pipeline very often,
1259/// yet on a rare occasion ability to specify parameters right there can be
1260/// useful.
1261///
1262/// \p Name - parameterized specification of a pass from a textual pipeline
1263/// is a string in a form of :
1264/// PassName '<' parameter-list '>'
1265///
1266/// Parameter list is being parsed by the parser callable argument, \p Parser,
1267/// It takes a string-ref of parameters and returns either StringError or a
1268/// parameter list in a form of a custom parameters type, all wrapped into
1269/// Expected<> template class.
1270///
1271template <typename ParametersParseCallableT>
1272auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1273 StringRef PassName) -> decltype(Parser(StringRef{})) {
1274 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1275
1276 StringRef Params = Name;
1277 if (!Params.consume_front(PassName)) {
1278 assert(false &&
1279 "unable to strip pass name from parametrized pass specification");
1280 }
1281 if (Params.empty())
1282 return ParametersT{};
1283 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1284 assert(false && "invalid format for parametrized pass name");
1285 }
1286
1287 Expected<ParametersT> Result = Parser(Params);
1288 assert((Result || Result.template errorIsA<StringError>()) &&
1289 "Pass parameter parser can only return StringErrors.");
1290 return std::move(Result);
1291}
1292
1293/// Parser of parameters for LoopUnroll pass.
1294Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1295 LoopUnrollOptions UnrollOpts;
1296 while (!Params.empty()) {
1297 StringRef ParamName;
1298 std::tie(ParamName, Params) = Params.split(';');
1299 int OptLevel = StringSwitch<int>(ParamName)
1300 .Case("O0", 0)
1301 .Case("O1", 1)
1302 .Case("O2", 2)
1303 .Case("O3", 3)
1304 .Default(-1);
1305 if (OptLevel >= 0) {
1306 UnrollOpts.setOptLevel(OptLevel);
1307 continue;
1308 }
1309
1310 bool Enable = !ParamName.consume_front("no-");
1311 if (ParamName == "partial") {
1312 UnrollOpts.setPartial(Enable);
1313 } else if (ParamName == "peeling") {
1314 UnrollOpts.setPeeling(Enable);
1315 } else if (ParamName == "runtime") {
1316 UnrollOpts.setRuntime(Enable);
1317 } else if (ParamName == "upperbound") {
1318 UnrollOpts.setUpperBound(Enable);
1319 } else {
1320 return make_error<StringError>(
1321 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1322 inconvertibleErrorCode());
1323 }
1324 }
1325 return UnrollOpts;
1326}
1327
1328} // namespace
1329
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001330/// Tests whether a pass name starts with a valid prefix for a default pipeline
1331/// alias.
1332static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1333 return Name.startswith("default") || Name.startswith("thinlto") ||
1334 Name.startswith("lto");
1335}
1336
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001337/// Tests whether registered callbacks will accept a given pass name.
1338///
1339/// When parsing a pipeline text, the type of the outermost pipeline may be
1340/// omitted, in which case the type is automatically determined from the first
1341/// pass name in the text. This may be a name that is handled through one of the
1342/// callbacks. We check this through the oridinary parsing callbacks by setting
1343/// up a dummy PassManager in order to not force the client to also handle this
1344/// type of query.
1345template <typename PassManagerT, typename CallbacksT>
1346static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1347 if (!Callbacks.empty()) {
1348 PassManagerT DummyPM;
1349 for (auto &CB : Callbacks)
1350 if (CB(Name, DummyPM, {}))
1351 return true;
1352 }
1353 return false;
1354}
1355
1356template <typename CallbacksT>
1357static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001358 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001359 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001360 return DefaultAliasRegex.match(Name);
1361
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001362 // Explicitly handle pass manager names.
1363 if (Name == "module")
1364 return true;
1365 if (Name == "cgscc")
1366 return true;
1367 if (Name == "function")
1368 return true;
1369
Chandler Carruth241bf242016-08-03 07:44:48 +00001370 // Explicitly handle custom-parsed pass names.
1371 if (parseRepeatPassName(Name))
1372 return true;
1373
Chandler Carruth74a8a222016-06-17 07:15:29 +00001374#define MODULE_PASS(NAME, CREATE_PASS) \
1375 if (Name == NAME) \
1376 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001377#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001378 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001379 return true;
1380#include "PassRegistry.def"
1381
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001382 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001383}
1384
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001385template <typename CallbacksT>
1386static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001387 // Explicitly handle pass manager names.
1388 if (Name == "cgscc")
1389 return true;
1390 if (Name == "function")
1391 return true;
1392
Chandler Carruth241bf242016-08-03 07:44:48 +00001393 // Explicitly handle custom-parsed pass names.
1394 if (parseRepeatPassName(Name))
1395 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001396 if (parseDevirtPassName(Name))
1397 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001398
Chandler Carruth74a8a222016-06-17 07:15:29 +00001399#define CGSCC_PASS(NAME, CREATE_PASS) \
1400 if (Name == NAME) \
1401 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001402#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001403 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001404 return true;
1405#include "PassRegistry.def"
1406
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001407 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001408}
1409
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001410template <typename CallbacksT>
1411static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001412 // Explicitly handle pass manager names.
1413 if (Name == "function")
1414 return true;
1415 if (Name == "loop")
1416 return true;
1417
Chandler Carruth241bf242016-08-03 07:44:48 +00001418 // Explicitly handle custom-parsed pass names.
1419 if (parseRepeatPassName(Name))
1420 return true;
1421
Chandler Carruth74a8a222016-06-17 07:15:29 +00001422#define FUNCTION_PASS(NAME, CREATE_PASS) \
1423 if (Name == NAME) \
1424 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001425#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1426 if (checkParametrizedPassName(Name, NAME)) \
1427 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001428#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001429 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001430 return true;
1431#include "PassRegistry.def"
1432
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001433 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001434}
1435
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001436template <typename CallbacksT>
1437static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001438 // Explicitly handle pass manager names.
1439 if (Name == "loop")
1440 return true;
1441
Chandler Carruth241bf242016-08-03 07:44:48 +00001442 // Explicitly handle custom-parsed pass names.
1443 if (parseRepeatPassName(Name))
1444 return true;
1445
Chandler Carruth74a8a222016-06-17 07:15:29 +00001446#define LOOP_PASS(NAME, CREATE_PASS) \
1447 if (Name == NAME) \
1448 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001449#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1450 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1451 return true;
1452#include "PassRegistry.def"
1453
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001454 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001455}
1456
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001457Optional<std::vector<PassBuilder::PipelineElement>>
1458PassBuilder::parsePipelineText(StringRef Text) {
1459 std::vector<PipelineElement> ResultPipeline;
1460
1461 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1462 &ResultPipeline};
1463 for (;;) {
1464 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1465 size_t Pos = Text.find_first_of(",()");
1466 Pipeline.push_back({Text.substr(0, Pos), {}});
1467
1468 // If we have a single terminating name, we're done.
1469 if (Pos == Text.npos)
1470 break;
1471
1472 char Sep = Text[Pos];
1473 Text = Text.substr(Pos + 1);
1474 if (Sep == ',')
1475 // Just a name ending in a comma, continue.
1476 continue;
1477
1478 if (Sep == '(') {
1479 // Push the inner pipeline onto the stack to continue processing.
1480 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1481 continue;
1482 }
1483
1484 assert(Sep == ')' && "Bogus separator!");
1485 // When handling the close parenthesis, we greedily consume them to avoid
1486 // empty strings in the pipeline.
1487 do {
1488 // If we try to pop the outer pipeline we have unbalanced parentheses.
1489 if (PipelineStack.size() == 1)
1490 return None;
1491
1492 PipelineStack.pop_back();
1493 } while (Text.consume_front(")"));
1494
1495 // Check if we've finished parsing.
1496 if (Text.empty())
1497 break;
1498
1499 // Otherwise, the end of an inner pipeline always has to be followed by
1500 // a comma, and then we can continue.
1501 if (!Text.consume_front(","))
1502 return None;
1503 }
1504
1505 if (PipelineStack.size() > 1)
1506 // Unbalanced paretheses.
1507 return None;
1508
1509 assert(PipelineStack.back() == &ResultPipeline &&
1510 "Wrong pipeline at the bottom of the stack!");
1511 return {std::move(ResultPipeline)};
1512}
1513
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001514Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1515 const PipelineElement &E,
1516 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001517 auto &Name = E.Name;
1518 auto &InnerPipeline = E.InnerPipeline;
1519
1520 // First handle complex passes like the pass managers which carry pipelines.
1521 if (!InnerPipeline.empty()) {
1522 if (Name == "module") {
1523 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001524 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1525 VerifyEachPass, DebugLogging))
1526 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001527 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001528 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001529 }
1530 if (Name == "cgscc") {
1531 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001532 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1533 DebugLogging))
1534 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001535 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001536 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001537 }
1538 if (Name == "function") {
1539 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001540 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1541 VerifyEachPass, DebugLogging))
1542 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001543 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001544 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001545 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001546 if (auto Count = parseRepeatPassName(Name)) {
1547 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001548 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1549 VerifyEachPass, DebugLogging))
1550 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001551 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001552 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001553 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001554
1555 for (auto &C : ModulePipelineParsingCallbacks)
1556 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001557 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001558
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001559 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001560 return make_error<StringError>(
1561 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1562 inconvertibleErrorCode());
1563 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001564 }
1565
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001566 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001567 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001568 SmallVector<StringRef, 3> Matches;
1569 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001570 return make_error<StringError>(
1571 formatv("unknown default pipeline alias '{0}'", Name).str(),
1572 inconvertibleErrorCode());
1573
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001574 assert(Matches.size() == 3 && "Must capture two matched strings!");
1575
Jordan Rosef85a95f2016-07-25 18:34:51 +00001576 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001577 .Case("O0", O0)
1578 .Case("O1", O1)
1579 .Case("O2", O2)
1580 .Case("O3", O3)
1581 .Case("Os", Os)
1582 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001583 if (L == O0)
1584 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001585 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001586
1587 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001588 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001589 } else if (Matches[1] == "thinlto-pre-link") {
1590 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1591 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001592 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001593 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001594 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001595 } else {
1596 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001597 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001598 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001599 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001600 }
1601
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001602 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001603#define MODULE_PASS(NAME, CREATE_PASS) \
1604 if (Name == NAME) { \
1605 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001606 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001607 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001608#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1609 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001610 MPM.addPass( \
1611 RequireAnalysisPass< \
1612 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001613 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001614 } \
1615 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001616 MPM.addPass(InvalidateAnalysisPass< \
1617 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001618 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001619 }
1620#include "PassRegistry.def"
1621
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001622 for (auto &C : ModulePipelineParsingCallbacks)
1623 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001624 return Error::success();
1625 return make_error<StringError>(
1626 formatv("unknown module pass '{0}'", Name).str(),
1627 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001628}
1629
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001630Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1631 const PipelineElement &E, bool VerifyEachPass,
1632 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001633 auto &Name = E.Name;
1634 auto &InnerPipeline = E.InnerPipeline;
1635
1636 // First handle complex passes like the pass managers which carry pipelines.
1637 if (!InnerPipeline.empty()) {
1638 if (Name == "cgscc") {
1639 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001640 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1641 VerifyEachPass, DebugLogging))
1642 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001643 // Add the nested pass manager with the appropriate adaptor.
1644 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001645 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001646 }
1647 if (Name == "function") {
1648 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001649 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1650 VerifyEachPass, DebugLogging))
1651 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001652 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001653 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001654 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001655 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001656 if (auto Count = parseRepeatPassName(Name)) {
1657 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001658 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1659 VerifyEachPass, DebugLogging))
1660 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001661 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001662 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001663 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001664 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1665 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001666 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1667 VerifyEachPass, DebugLogging))
1668 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001669 CGPM.addPass(
1670 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001671 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001672 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001673
1674 for (auto &C : CGSCCPipelineParsingCallbacks)
1675 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001676 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001677
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001678 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001679 return make_error<StringError>(
1680 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1681 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001682 }
1683
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001684// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001685#define CGSCC_PASS(NAME, CREATE_PASS) \
1686 if (Name == NAME) { \
1687 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001688 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001689 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001690#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1691 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001692 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001693 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001694 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1695 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001696 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001697 } \
1698 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001699 CGPM.addPass(InvalidateAnalysisPass< \
1700 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001701 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001702 }
1703#include "PassRegistry.def"
1704
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001705 for (auto &C : CGSCCPipelineParsingCallbacks)
1706 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001707 return Error::success();
1708 return make_error<StringError>(
1709 formatv("unknown cgscc pass '{0}'", Name).str(),
1710 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001711}
1712
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001713Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1714 const PipelineElement &E,
1715 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001716 auto &Name = E.Name;
1717 auto &InnerPipeline = E.InnerPipeline;
1718
1719 // First handle complex passes like the pass managers which carry pipelines.
1720 if (!InnerPipeline.empty()) {
1721 if (Name == "function") {
1722 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001723 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1724 VerifyEachPass, DebugLogging))
1725 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001726 // Add the nested pass manager with the appropriate adaptor.
1727 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001728 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001729 }
1730 if (Name == "loop") {
1731 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001732 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1733 DebugLogging))
1734 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001735 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001736 FPM.addPass(
1737 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001738 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001739 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001740 if (auto Count = parseRepeatPassName(Name)) {
1741 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001742 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1743 VerifyEachPass, DebugLogging))
1744 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001745 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001746 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001747 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001748
1749 for (auto &C : FunctionPipelineParsingCallbacks)
1750 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001751 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001752
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001753 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001754 return make_error<StringError>(
1755 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1756 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001757 }
1758
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001759// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001760#define FUNCTION_PASS(NAME, CREATE_PASS) \
1761 if (Name == NAME) { \
1762 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001763 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001764 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001765#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1766 if (checkParametrizedPassName(Name, NAME)) { \
1767 auto Params = parsePassParameters(PARSER, Name, NAME); \
1768 if (!Params) \
1769 return Params.takeError(); \
1770 FPM.addPass(CREATE_PASS(Params.get())); \
1771 return Error::success(); \
1772 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001773#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1774 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001775 FPM.addPass( \
1776 RequireAnalysisPass< \
1777 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001778 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001779 } \
1780 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001781 FPM.addPass(InvalidateAnalysisPass< \
1782 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001783 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001784 }
1785#include "PassRegistry.def"
1786
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001787 for (auto &C : FunctionPipelineParsingCallbacks)
1788 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001789 return Error::success();
1790 return make_error<StringError>(
1791 formatv("unknown function pass '{0}'", Name).str(),
1792 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001793}
1794
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001795Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1796 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001797 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001798 auto &InnerPipeline = E.InnerPipeline;
1799
1800 // First handle complex passes like the pass managers which carry pipelines.
1801 if (!InnerPipeline.empty()) {
1802 if (Name == "loop") {
1803 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001804 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1805 VerifyEachPass, DebugLogging))
1806 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001807 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001808 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001809 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001810 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001811 if (auto Count = parseRepeatPassName(Name)) {
1812 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001813 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1814 VerifyEachPass, DebugLogging))
1815 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001816 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001817 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001818 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001819
1820 for (auto &C : LoopPipelineParsingCallbacks)
1821 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001822 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001823
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001824 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001825 return make_error<StringError>(
1826 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1827 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001828 }
1829
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001830// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001831#define LOOP_PASS(NAME, CREATE_PASS) \
1832 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001833 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001834 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001835 }
1836#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1837 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001838 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001839 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1840 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1841 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001842 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001843 } \
1844 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001845 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001846 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001847 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001848 }
1849#include "PassRegistry.def"
1850
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001851 for (auto &C : LoopPipelineParsingCallbacks)
1852 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001853 return Error::success();
1854 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1855 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001856}
1857
Chandler Carruthedf59962016-02-18 09:45:17 +00001858bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001859#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1860 if (Name == NAME) { \
1861 AA.registerModuleAnalysis< \
1862 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1863 return true; \
1864 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001865#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1866 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001867 AA.registerFunctionAnalysis< \
1868 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001869 return true; \
1870 }
1871#include "PassRegistry.def"
1872
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001873 for (auto &C : AAParsingCallbacks)
1874 if (C(Name, AA))
1875 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001876 return false;
1877}
1878
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001879Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001880 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001881 bool VerifyEachPass,
1882 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001883 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001884 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1885 return Err;
1886 // FIXME: No verifier support for Loop passes!
1887 }
1888 return Error::success();
1889}
1890
1891Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1892 ArrayRef<PipelineElement> Pipeline,
1893 bool VerifyEachPass,
1894 bool DebugLogging) {
1895 for (const auto &Element : Pipeline) {
1896 if (auto Err =
1897 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1898 return Err;
1899 if (VerifyEachPass)
1900 FPM.addPass(VerifierPass());
1901 }
1902 return Error::success();
1903}
1904
1905Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1906 ArrayRef<PipelineElement> Pipeline,
1907 bool VerifyEachPass,
1908 bool DebugLogging) {
1909 for (const auto &Element : Pipeline) {
1910 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1911 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001912 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001913 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001914 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00001915}
1916
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001917void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1918 FunctionAnalysisManager &FAM,
1919 CGSCCAnalysisManager &CGAM,
1920 ModuleAnalysisManager &MAM) {
1921 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1922 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001923 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1924 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1925 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1926 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1927 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1928}
1929
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001930Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1931 ArrayRef<PipelineElement> Pipeline,
1932 bool VerifyEachPass,
1933 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001934 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001935 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1936 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001937 if (VerifyEachPass)
1938 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001939 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001940 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001941}
1942
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001943// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00001944// FIXME: Should this routine accept a TargetMachine or require the caller to
1945// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001946Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1947 StringRef PipelineText,
1948 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001949 auto Pipeline = parsePipelineText(PipelineText);
1950 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001951 return make_error<StringError>(
1952 formatv("invalid pipeline '{0}'", PipelineText).str(),
1953 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001954
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001955 // If the first name isn't at the module layer, wrap the pipeline up
1956 // automatically.
1957 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00001958
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001959 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1960 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001961 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001962 } else if (isFunctionPassName(FirstName,
1963 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001964 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001965 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001966 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001967 } else {
1968 for (auto &C : TopLevelPipelineParsingCallbacks)
1969 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001970 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001971
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001972 // Unknown pass or pipeline name!
1973 auto &InnerPipeline = Pipeline->front().InnerPipeline;
1974 return make_error<StringError>(
1975 formatv("unknown {0} name '{1}'",
1976 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1977 .str(),
1978 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001979 }
Chandler Carruth572e3402014-04-21 11:12:00 +00001980 }
1981
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001982 if (auto Err =
1983 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1984 return Err;
1985 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001986}
Chandler Carruthedf59962016-02-18 09:45:17 +00001987
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001988// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001989Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1990 StringRef PipelineText,
1991 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001992 auto Pipeline = parsePipelineText(PipelineText);
1993 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001994 return make_error<StringError>(
1995 formatv("invalid pipeline '{0}'", PipelineText).str(),
1996 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001997
1998 StringRef FirstName = Pipeline->front().Name;
1999 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002000 return make_error<StringError>(
2001 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2002 PipelineText)
2003 .str(),
2004 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002005
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002006 if (auto Err =
2007 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2008 return Err;
2009 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002010}
2011
2012// Primary pass pipeline description parsing routine for a \c
2013// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002014Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2015 StringRef PipelineText,
2016 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002017 auto Pipeline = parsePipelineText(PipelineText);
2018 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002019 return make_error<StringError>(
2020 formatv("invalid pipeline '{0}'", PipelineText).str(),
2021 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002022
2023 StringRef FirstName = Pipeline->front().Name;
2024 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002025 return make_error<StringError>(
2026 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2027 PipelineText)
2028 .str(),
2029 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002030
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002031 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2032 DebugLogging))
2033 return Err;
2034 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002035}
2036
2037// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002038Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2039 StringRef PipelineText,
2040 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002041 auto Pipeline = parsePipelineText(PipelineText);
2042 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002043 return make_error<StringError>(
2044 formatv("invalid pipeline '{0}'", PipelineText).str(),
2045 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002046
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002047 if (auto Err =
2048 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2049 return Err;
2050
2051 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002052}
2053
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002054Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002055 // If the pipeline just consists of the word 'default' just replace the AA
2056 // manager with our default one.
2057 if (PipelineText == "default") {
2058 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002059 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002060 }
2061
Chandler Carruthedf59962016-02-18 09:45:17 +00002062 while (!PipelineText.empty()) {
2063 StringRef Name;
2064 std::tie(Name, PipelineText) = PipelineText.split(',');
2065 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002066 return make_error<StringError>(
2067 formatv("unknown alias analysis name '{0}'", Name).str(),
2068 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002069 }
2070
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002071 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002072}