blob: a84b9e85e6a748aceb0be07460185317a49bc0dd [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chandler Carruth66445382014-01-11 08:16:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
9///
Chandler Carruth1ff77242015-03-07 09:02:36 +000010/// This file provides the implementation of the PassBuilder based on our
11/// static pass registry as well as related functionality. It also provides
12/// helpers to aid in analyzing, debugging, and testing passes and pass
13/// pipelines.
Chandler Carruth66445382014-01-11 08:16:35 +000014///
15//===----------------------------------------------------------------------===//
16
Chandler Carruth1ff77242015-03-07 09:02:36 +000017#include "llvm/Passes/PassBuilder.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000018#include "llvm/ADT/StringSwitch.h"
Chandler Carruth6f5770b102016-02-13 23:32:00 +000019#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth4f846a52016-02-20 03:46:03 +000020#include "llvm/Analysis/AliasAnalysisEvaluator.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000021#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthbece8d52016-02-13 23:46:24 +000022#include "llvm/Analysis/BasicAliasAnalysis.h"
Xinliang David Li28a93272016-05-05 21:13:27 +000023#include "llvm/Analysis/BlockFrequencyInfo.h"
Xinliang David Li6e5dd412016-05-05 02:59:57 +000024#include "llvm/Analysis/BranchProbabilityInfo.h"
Mehdi Amini27d23792016-09-16 16:56:30 +000025#include "llvm/Analysis/CFGPrinter.h"
George Burgess IVbfa401e2016-07-06 00:26:41 +000026#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
27#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
Chandler Carruth572e3402014-04-21 11:12:00 +000028#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruth4c660f72016-03-10 11:24:11 +000029#include "llvm/Analysis/CallGraph.h"
Michael Kupersteinde16b442016-04-18 23:55:01 +000030#include "llvm/Analysis/DemandedBits.h"
Chandler Carruth49c22192016-05-12 22:19:39 +000031#include "llvm/Analysis/DependenceAnalysis.h"
Hongbin Zheng751337f2016-02-25 17:54:15 +000032#include "llvm/Analysis/DominanceFrontier.h"
Chandler Carruth45a9c202016-03-11 09:15:11 +000033#include "llvm/Analysis/GlobalsModRef.h"
Dehao Chen1a444522016-07-16 22:51:33 +000034#include "llvm/Analysis/IVUsers.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000035#include "llvm/Analysis/LazyCallGraph.h"
Sean Silva687019f2016-06-13 22:01:25 +000036#include "llvm/Analysis/LazyValueInfo.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000037#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000038#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth61440d22016-03-10 00:55:30 +000039#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000040#include "llvm/Analysis/MemorySSA.h"
Teresa Johnsonf93b2462016-08-12 13:53:02 +000041#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000042#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawnbdbbd832018-06-28 14:13:06 +000043#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng3f978402016-02-25 17:54:07 +000044#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000045#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000046#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000047#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000048#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000049#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000050#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000051#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000052#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000053#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000054#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000055#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000056#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000057#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000058#include "llvm/IR/PassManager.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000059#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000060#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000061#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000062#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000063#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000064#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000065#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000066#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000067#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000068#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000069#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000070#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000071#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000072#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000073#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000074#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000075#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000076#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000077#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000078#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000079#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000080#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000081#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000082#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000083#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000084#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000085#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000086#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000087#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000088#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000089#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000090#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000091#include "llvm/Transforms/Instrumentation/AddressSanitizer.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"
Manman Ren18295122019-02-28 20:13:38 +000096#include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000097#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000098#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +000099#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +0000100#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000101#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000102#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000103#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000104#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000105#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000106#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000107#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000108#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000109#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000110#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000111#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000112#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000113#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000114#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000115#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000116#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000117#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000118#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000119#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000120#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000121#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000122#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000123#include "llvm/Transforms/Scalar/LoopDistribute.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000124#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000125#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000126#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000127#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000128#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000129#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000130#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000131#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000132#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000133#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000134#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000135#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000136#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000137#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000138#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000139#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000140#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000141#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000142#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000143#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000144#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000145#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000146#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000147#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000148#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000149#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000150#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000151#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000152#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000153#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000154#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000155#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000156#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000157#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000158#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000159#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000160#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000161#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000162#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000163#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000164#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000165#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000166#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000167#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000168#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000169#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000170#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000171
Chandler Carruth66445382014-01-11 08:16:35 +0000172using namespace llvm;
173
Chandler Carruth719ffe12017-02-12 05:38:04 +0000174static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
175 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000176static cl::opt<bool>
177 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
178 cl::Hidden, cl::ZeroOrMore,
179 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000180
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000181static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000182 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000183 cl::Hidden, cl::ZeroOrMore,
184 cl::desc("Run NewGVN instead of GVN"));
185
Geoff Berry3cca1da2017-06-10 15:20:03 +0000186static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000187 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
188 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000189
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000190static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000191 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
192 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000193
Davide Italianobe1b6a92017-06-03 23:18:29 +0000194static cl::opt<bool> EnableGVNSink(
195 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
196 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
197
David Green963401d2018-07-01 12:47:30 +0000198static cl::opt<bool> EnableUnrollAndJam(
199 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
200 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
201
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000202static cl::opt<bool> EnableSyntheticCounts(
203 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
204 cl::desc("Run synthetic function entry count generation "
205 "pass"));
206
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000207static Regex DefaultAliasRegex(
208 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000209
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000210static cl::opt<bool>
211 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
212 cl::desc("Enable control height reduction optimization (CHR)"));
213
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000214extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000215extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000216
Wei Mi3bcccdf2019-01-17 20:48:34 +0000217extern cl::opt<bool> FlattenedProfileUsed;
218
Chandler Carruthe3f50642016-12-22 06:59:15 +0000219static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
220 switch (Level) {
221 case PassBuilder::O0:
222 case PassBuilder::O1:
223 case PassBuilder::O2:
224 case PassBuilder::O3:
225 return false;
226
227 case PassBuilder::Os:
228 case PassBuilder::Oz:
229 return true;
230 }
231 llvm_unreachable("Invalid optimization level!");
232}
233
Chandler Carruth66445382014-01-11 08:16:35 +0000234namespace {
235
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000236/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000237struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000238 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000239 return PreservedAnalyses::all();
240 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000241 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000242};
243
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000244/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000245class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
246 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000247 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000248
249public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000250 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000251 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000252 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000253};
254
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000255/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000256struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000257 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
258 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000259 return PreservedAnalyses::all();
260 }
261 static StringRef name() { return "NoOpCGSCCPass"; }
262};
263
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000264/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000265class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
266 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000267 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000268
269public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000270 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000271 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000272 return Result();
273 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000274 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000275};
276
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000277/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000278struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000279 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000280 return PreservedAnalyses::all();
281 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000282 static StringRef name() { return "NoOpFunctionPass"; }
283};
284
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000285/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000286class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
287 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000288 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000289
290public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000291 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000292 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000293 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000294};
295
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000296/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000297struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000298 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
299 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000300 return PreservedAnalyses::all();
301 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000302 static StringRef name() { return "NoOpLoopPass"; }
303};
304
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000305/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000306class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
307 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000308 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000309
310public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000311 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000312 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
313 return Result();
314 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000315 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000316};
317
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000318AnalysisKey NoOpModuleAnalysis::Key;
319AnalysisKey NoOpCGSCCAnalysis::Key;
320AnalysisKey NoOpFunctionAnalysis::Key;
321AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000322
Chandler Carruth66445382014-01-11 08:16:35 +0000323} // End anonymous namespace.
324
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000325void PassBuilder::invokePeepholeEPCallbacks(
326 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
327 for (auto &C : PeepholeEPCallbacks)
328 C(FPM, Level);
329}
330
Chandler Carruth1ff77242015-03-07 09:02:36 +0000331void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000332#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000333 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000334#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000335
336 for (auto &C : ModuleAnalysisRegistrationCallbacks)
337 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000338}
339
Chandler Carruth1ff77242015-03-07 09:02:36 +0000340void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000341#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000342 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000343#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000344
345 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
346 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000347}
348
Chandler Carruth1ff77242015-03-07 09:02:36 +0000349void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000350#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000351 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000352#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000353
354 for (auto &C : FunctionAnalysisRegistrationCallbacks)
355 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000356}
357
Justin Bognereecc3c82016-02-25 07:23:08 +0000358void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000359#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000360 LAM.registerPass([&] { return CREATE_PASS; });
361#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000362
363 for (auto &C : LoopAnalysisRegistrationCallbacks)
364 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000365}
366
Chandler Carruthe3f50642016-12-22 06:59:15 +0000367FunctionPassManager
368PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000369 ThinLTOPhase Phase,
370 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000371 assert(Level != O0 && "Must request optimizations!");
372 FunctionPassManager FPM(DebugLogging);
373
374 // Form SSA out of local memory accesses after breaking apart aggregates into
375 // scalars.
376 FPM.addPass(SROA());
377
378 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000379 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000380
Davide Italianoc3688312017-06-01 23:08:14 +0000381 // Hoisting of scalars and load expressions.
382 if (EnableGVNHoist)
383 FPM.addPass(GVNHoistPass());
384
Davide Italianobe1b6a92017-06-03 23:18:29 +0000385 // Global value numbering based sinking.
386 if (EnableGVNSink) {
387 FPM.addPass(GVNSinkPass());
388 FPM.addPass(SimplifyCFGPass());
389 }
390
Chandler Carruthe3f50642016-12-22 06:59:15 +0000391 // Speculative execution if the target has divergent branches; otherwise nop.
392 FPM.addPass(SpeculativeExecutionPass());
393
394 // Optimize based on known information about branches, and cleanup afterward.
395 FPM.addPass(JumpThreadingPass());
396 FPM.addPass(CorrelatedValuePropagationPass());
397 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000398 if (Level == O3)
399 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000400 FPM.addPass(InstCombinePass());
401
402 if (!isOptimizingForSize(Level))
403 FPM.addPass(LibCallsShrinkWrapPass());
404
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000405 invokePeepholeEPCallbacks(FPM, Level);
406
Rong Xue1f42452017-10-23 22:21:29 +0000407 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
408 // using the size value profile. Don't perform this when optimizing for size.
409 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
410 !isOptimizingForSize(Level))
411 FPM.addPass(PGOMemOPSizeOpt());
412
Chandler Carruthe3f50642016-12-22 06:59:15 +0000413 FPM.addPass(TailCallElimPass());
414 FPM.addPass(SimplifyCFGPass());
415
416 // Form canonically associated expression trees, and simplify the trees using
417 // basic mathematical properties. For example, this will form (nearly)
418 // minimal multiplication trees.
419 FPM.addPass(ReassociatePass());
420
421 // Add the primary loop simplification pipeline.
422 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000423 // some function passes in between them. These can and should be removed
424 // and/or replaced by scheduling the loop pass equivalents in the correct
425 // positions. But those equivalent passes aren't powerful enough yet.
426 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
427 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
428 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
429 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000430 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
431
Chandler Carruth71fd2702018-05-30 02:46:45 +0000432 // Simplify the loop body. We do this initially to clean up after other loop
433 // passes run, either when iterating on a loop or on inner loops with
434 // implications on the outer loop.
435 LPM1.addPass(LoopInstSimplifyPass());
436 LPM1.addPass(LoopSimplifyCFGPass());
437
Chandler Carruthe3f50642016-12-22 06:59:15 +0000438 // Rotate Loop - disable header duplication at -Oz
439 LPM1.addPass(LoopRotatePass(Level != Oz));
440 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000441 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000442 LPM2.addPass(IndVarSimplifyPass());
443 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000444
445 for (auto &C : LateLoopOptimizationsEPCallbacks)
446 C(LPM2, Level);
447
Chandler Carruth79b733b2017-01-26 23:21:17 +0000448 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000449 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000450 // because it changes IR to makes profile annotation in back compile
451 // inaccurate.
Dehao Chen95f00302017-07-30 04:55:39 +0000452 if (Phase != ThinLTOPhase::PreLink ||
453 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnsonecd90132017-08-02 20:35:29 +0000454 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000455
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000456 for (auto &C : LoopOptimizerEndEPCallbacks)
457 C(LPM2, Level);
458
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000459 // We provide the opt remark emitter pass for LICM to use. We only need to do
460 // this once as it is immutable.
461 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000462 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000463 FPM.addPass(SimplifyCFGPass());
464 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000465 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000466
467 // Eliminate redundancies.
468 if (Level != O1) {
469 // These passes add substantial compile time so skip them at O1.
470 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000471 if (RunNewGVN)
472 FPM.addPass(NewGVNPass());
473 else
474 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000475 }
476
477 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
478 FPM.addPass(MemCpyOptPass());
479
480 // Sparse conditional constant propagation.
481 // FIXME: It isn't clear why we do this *after* loop passes rather than
482 // before...
483 FPM.addPass(SCCPPass());
484
485 // Delete dead bit computations (instcombine runs after to fold away the dead
486 // computations, and then ADCE will run later to exploit any new DCE
487 // opportunities that creates).
488 FPM.addPass(BDCEPass());
489
490 // Run instcombine after redundancy and dead bit elimination to exploit
491 // opportunities opened up by them.
492 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000493 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000494
495 // Re-consider control flow based optimizations after redundancy elimination,
496 // redo DCE, etc.
497 FPM.addPass(JumpThreadingPass());
498 FPM.addPass(CorrelatedValuePropagationPass());
499 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000500 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000501
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000502 for (auto &C : ScalarOptimizerLateEPCallbacks)
503 C(FPM, Level);
504
Chandler Carruthe3f50642016-12-22 06:59:15 +0000505 // Finally, do an expensive DCE pass to catch all the dead code exposed by
506 // the simplifications and basic cleanup after all the simplifications.
507 FPM.addPass(ADCEPass());
508 FPM.addPass(SimplifyCFGPass());
509 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000510 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000511
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000512 if (EnableCHR && Level == O3 && PGOOpt &&
513 (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty()))
514 FPM.addPass(ControlHeightReductionPass());
515
Chandler Carruthe3f50642016-12-22 06:59:15 +0000516 return FPM;
517}
518
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000519void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
520 PassBuilder::OptimizationLevel Level,
521 bool RunProfileGen,
522 std::string ProfileGenFile,
Richard Smith6c676622018-10-10 23:13:47 +0000523 std::string ProfileUseFile,
524 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000525 // Generally running simplification passes and the inliner with an high
526 // threshold results in smaller executables, but there may be cases where
527 // the size grows, so let's be conservative here and skip this simplification
528 // at -Os/Oz.
529 if (!isOptimizingForSize(Level)) {
530 InlineParams IP;
531
532 // In the old pass manager, this is a cl::opt. Should still this be one?
533 IP.DefaultThreshold = 75;
534
535 // FIXME: The hint threshold has the same value used by the regular inliner.
536 // This should probably be lowered after performance testing.
537 // FIXME: this comment is cargo culted from the old pass manager, revisit).
538 IP.HintThreshold = 325;
539
540 CGSCCPassManager CGPipeline(DebugLogging);
541
542 CGPipeline.addPass(InlinerPass(IP));
543
544 FunctionPassManager FPM;
545 FPM.addPass(SROA());
546 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
547 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
548 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000549 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000550
Davide Italiano513dfaa2017-02-13 15:26:22 +0000551 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
552
553 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
554 }
555
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000556 // Delete anything that is now dead to make sure that we don't instrument
557 // dead code. Instrumentation can end up keeping dead code around and
558 // dramatically increase code size.
559 MPM.addPass(GlobalDCEPass());
560
Davide Italiano513dfaa2017-02-13 15:26:22 +0000561 if (RunProfileGen) {
562 MPM.addPass(PGOInstrumentationGen());
563
Xinliang David Lib67530e2017-06-25 00:26:43 +0000564 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000565 FPM.addPass(
566 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000567 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
568
Davide Italiano513dfaa2017-02-13 15:26:22 +0000569 // Add the profile lowering pass.
570 InstrProfOptions Options;
571 if (!ProfileGenFile.empty())
572 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000573 Options.DoCounterPromotion = true;
Rong Xu6cdf3d82019-02-27 17:24:33 +0000574 Options.UseBFIInPromotion = false;
575 MPM.addPass(InstrProfiling(Options, false));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000576 }
577
578 if (!ProfileUseFile.empty())
Richard Smith6c676622018-10-10 23:13:47 +0000579 MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000580}
581
Easwaran Raman8249fac2017-06-28 13:33:49 +0000582static InlineParams
583getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
584 auto O3 = PassBuilder::O3;
585 unsigned OptLevel = Level > O3 ? 2 : Level;
586 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
587 return getInlineParams(OptLevel, SizeLevel);
588}
589
Chandler Carruthe3f50642016-12-22 06:59:15 +0000590ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000591PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000592 ThinLTOPhase Phase,
593 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000594 ModulePassManager MPM(DebugLogging);
595
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000596 bool HasSampleProfile = PGOOpt && !PGOOpt->SampleProfileFile.empty();
597
598 // In ThinLTO mode, when flattened profile is used, all the available
599 // profile information will be annotated in PreLink phase so there is
600 // no need to load the profile again in PostLink.
601 bool LoadSampleProfile =
602 HasSampleProfile &&
603 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
604
605 // During the ThinLTO backend phase we perform early indirect call promotion
606 // here, before globalopt. Otherwise imported available_externally functions
607 // look unreferenced and are removed. If we are going to load the sample
608 // profile then defer until later.
609 // TODO: See if we can move later and consolidate with the location where
610 // we perform ICP when we are loading a sample profile.
611 // TODO: We pass HasSampleProfile (whether there was a sample profile file
612 // passed to the compile) to the SamplePGO flag of ICP. This is used to
613 // determine whether the new direct calls are annotated with prof metadata.
614 // Ideally this should be determined from whether the IR is annotated with
615 // sample profile, and not whether the a sample profile was provided on the
616 // command line. E.g. for flattened profiles where we will not be reloading
617 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
618 // provide the sample profile file.
619 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
620 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
621
Chandler Carruthe3f50642016-12-22 06:59:15 +0000622 // Do basic inference of function attributes from known properties of system
623 // libraries and other oracles.
624 MPM.addPass(InferFunctionAttrsPass());
625
626 // Create an early function pass manager to cleanup the output of the
627 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000628 FunctionPassManager EarlyFPM(DebugLogging);
629 EarlyFPM.addPass(SimplifyCFGPass());
630 EarlyFPM.addPass(SROA());
631 EarlyFPM.addPass(EarlyCSEPass());
632 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000633 if (Level == O3)
634 EarlyFPM.addPass(CallSiteSplittingPass());
635
Dehao Chen08f88312017-08-07 20:23:20 +0000636 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
637 // to convert bitcast to direct calls so that they can be inlined during the
638 // profile annotation prepration step.
639 // More details about SamplePGO design can be found in:
640 // https://research.google.com/pubs/pub45290.html
641 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000642 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000643 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000644 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000645
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000646 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000647 // Annotate sample profile right after early FPM to ensure freshness of
648 // the debug info.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000649 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
650 PGOOpt->ProfileRemappingFile,
651 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000652 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
653 // for the profile annotation to be accurate in the ThinLTO backend.
654 if (Phase != ThinLTOPhase::PreLink)
655 // We perform early indirect call promotion here, before globalopt.
656 // This is important for the ThinLTO backend phase because otherwise
657 // imported available_externally functions look unreferenced and are
658 // removed.
659 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000660 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000661 }
662
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000663 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000664 // and prior to optimizing globals.
665 // FIXME: This position in the pipeline hasn't been carefully considered in
666 // years, it should be re-analyzed.
667 MPM.addPass(IPSCCPPass());
668
Matthew Simpsoncb585582017-10-25 13:40:08 +0000669 // Attach metadata to indirect call sites indicating the set of functions
670 // they may target at run-time. This should follow IPSCCP.
671 MPM.addPass(CalledValuePropagationPass());
672
Chandler Carruthe3f50642016-12-22 06:59:15 +0000673 // Optimize globals to try and fold them into constants.
674 MPM.addPass(GlobalOptPass());
675
676 // Promote any localized globals to SSA registers.
677 // FIXME: Should this instead by a run of SROA?
678 // FIXME: We should probably run instcombine and simplify-cfg afterward to
679 // delete control flows that are dead once globals have been folded to
680 // constants.
681 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
682
683 // Remove any dead arguments exposed by cleanups and constand folding
684 // globals.
685 MPM.addPass(DeadArgumentEliminationPass());
686
687 // Create a small function pass pipeline to cleanup after all the global
688 // optimizations.
689 FunctionPassManager GlobalCleanupPM(DebugLogging);
690 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000691 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
692
Chandler Carruthe3f50642016-12-22 06:59:15 +0000693 GlobalCleanupPM.addPass(SimplifyCFGPass());
694 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
695
Dehao Chen89d32262017-08-02 01:28:31 +0000696 // Add all the requested passes for instrumentation PGO, if requested.
697 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
698 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
699 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
Richard Smith6c676622018-10-10 23:13:47 +0000700 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
701 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000702 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000703 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000704
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000705 // Synthesize function entry counts for non-PGO compilation.
706 if (EnableSyntheticCounts && !PGOOpt)
707 MPM.addPass(SyntheticCountsPropagation());
708
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000709 // Require the GlobalsAA analysis for the module so we can query it within
710 // the CGSCC pipeline.
711 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000712
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000713 // Require the ProfileSummaryAnalysis for the module so we can query it within
714 // the inliner pass.
715 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
716
Chandler Carruthe3f50642016-12-22 06:59:15 +0000717 // Now begin the main postorder CGSCC pipeline.
718 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
719 // manager and trying to emulate its precise behavior. Much of this doesn't
720 // make a lot of sense and we should revisit the core CGSCC structure.
721 CGSCCPassManager MainCGPipeline(DebugLogging);
722
723 // Note: historically, the PruneEH pass was run first to deduce nounwind and
724 // generally clean up exception handling overhead. It isn't clear this is
725 // valuable as the inliner doesn't currently care whether it is inlining an
726 // invoke or a call.
727
728 // Run the inliner first. The theory is that we are walking bottom-up and so
729 // the callees have already been fully optimized, and we want to inline them
730 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000731 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000732 // because it makes profile annotation in the backend inaccurate.
733 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000734 if (Phase == ThinLTOPhase::PreLink &&
735 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000736 IP.HotCallSiteThreshold = 0;
737 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000738
739 // Now deduce any function attributes based in the current code.
740 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
741
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000742 // When at O3 add argument promotion to the pass pipeline.
743 // FIXME: It isn't at all clear why this should be limited to O3.
744 if (Level == O3)
745 MainCGPipeline.addPass(ArgumentPromotionPass());
746
Chandler Carruthe3f50642016-12-22 06:59:15 +0000747 // Lastly, add the core function simplification pipeline nested inside the
748 // CGSCC walk.
749 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000750 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000751
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000752 for (auto &C : CGSCCOptimizerLateEPCallbacks)
753 C(MainCGPipeline, Level);
754
Chandler Carruth719ffe12017-02-12 05:38:04 +0000755 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
756 // to detect when we devirtualize indirect calls and iterate the SCC passes
757 // in that case to try and catch knock-on inlining or function attrs
758 // opportunities. Then we add it to the module pipeline by walking the SCCs
759 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000760 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000761 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000762 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000763
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000764 return MPM;
765}
766
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000767ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
768 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000769 ModulePassManager MPM(DebugLogging);
770
771 // Optimize globals now that the module is fully simplified.
772 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000773 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000774
Xinliang David Li126157c2017-05-22 16:41:57 +0000775 // Run partial inlining pass to partially inline functions that have
776 // large bodies.
777 if (RunPartialInlining)
778 MPM.addPass(PartialInlinerPass());
779
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000780 // Remove avail extern fns and globals definitions since we aren't compiling
781 // an object file for later LTO. For LTO we want to preserve these so they
782 // are eligible for inlining at link-time. Note if they are unreferenced they
783 // will be removed by GlobalDCE later, so this only impacts referenced
784 // available externally globals. Eventually they will be suppressed during
785 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
786 // may make globals referenced by available external functions dead and saves
787 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000788 MPM.addPass(EliminateAvailableExternallyPass());
789
Manman Ren18295122019-02-28 20:13:38 +0000790 if (EnableOrderFileInstrumentation)
791 MPM.addPass(InstrOrderFilePass());
792
Chandler Carruthe3f50642016-12-22 06:59:15 +0000793 // Do RPO function attribute inference across the module to forward-propagate
794 // attributes where applicable.
795 // FIXME: Is this really an optimization rather than a canonicalization?
796 MPM.addPass(ReversePostOrderFunctionAttrsPass());
797
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000798 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000799 // useful as the above will have inlined, DCE'ed, and function-attr
800 // propagated everything. We should at this point have a reasonably minimal
801 // and richly annotated call graph. By computing aliasing and mod/ref
802 // information for all local globals here, the late loop passes and notably
803 // the vectorizer will be able to use them to help recognize vectorizable
804 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000805 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000806
807 FunctionPassManager OptimizePM(DebugLogging);
808 OptimizePM.addPass(Float2IntPass());
809 // FIXME: We need to run some loop optimizations to re-rotate loops after
810 // simplify-cfg and others undo their rotation.
811
812 // Optimize the loop execution. These passes operate on entire loop nests
813 // rather than on each loop in an inside-out manner, and so they are actually
814 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000815
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000816 for (auto &C : VectorizerStartEPCallbacks)
817 C(OptimizePM, Level);
818
Chandler Carrutha95ff382017-01-27 00:50:21 +0000819 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000820 OptimizePM.addPass(
821 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000822
823 // Distribute loops to allow partial vectorization. I.e. isolate dependences
824 // into separate loop that would otherwise inhibit vectorization. This is
825 // currently only performed for loops marked with the metadata
826 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000827 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000828
829 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000830 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000831
Chandler Carruthbaabda92017-01-27 01:32:26 +0000832 // Eliminate loads by forwarding stores from the previous iteration to loads
833 // of the current iteration.
834 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000835
836 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000837 OptimizePM.addPass(InstCombinePass());
838
Chandler Carrutha95ff382017-01-27 00:50:21 +0000839 // Now that we've formed fast to execute loop structures, we do further
840 // optimizations. These are run afterward as they might block doing complex
841 // analyses and transforms such as what are needed for loop vectorization.
842
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000843 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
844 // GVN, loop transforms, and others have already run, so it's now better to
845 // convert to more optimized IR using more aggressive simplify CFG options.
846 // The extra sinking transform can create larger basic blocks, so do this
847 // before SLP vectorization.
848 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
849 forwardSwitchCondToPhi(true).
850 convertSwitchToLookupTable(true).
851 needCanonicalLoops(false).
852 sinkCommonInsts(true)));
853
Chandler Carruthe3f50642016-12-22 06:59:15 +0000854 // Optimize parallel scalar instruction chains into SIMD instructions.
855 OptimizePM.addPass(SLPVectorizerPass());
856
Chandler Carruthe3f50642016-12-22 06:59:15 +0000857 OptimizePM.addPass(InstCombinePass());
858
859 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000860 // execution resources of an out-of-order processor. We also then need to
861 // clean up redundancies and loop invariant code.
862 // FIXME: It would be really good to use a loop-integrated instruction
863 // combiner for cleanup here so that the unrolling and LICM can be pipelined
864 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000865 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
866 if (EnableUnrollAndJam) {
867 OptimizePM.addPass(
868 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
869 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000870 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000871 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000872 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000873 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000874 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000875
876 // Now that we've vectorized and unrolled loops, we may have more refined
877 // alignment information, try to re-derive it here.
878 OptimizePM.addPass(AlignmentFromAssumptionsPass());
879
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000880 // Split out cold code. Splitting is done late to avoid hiding context from
881 // other optimizations and inadvertently regressing performance. The tradeoff
882 // is that this has a higher code size cost than splitting early.
883 if (EnableHotColdSplit && !LTOPreLink)
884 MPM.addPass(HotColdSplittingPass());
885
Chandler Carrutha95ff382017-01-27 00:50:21 +0000886 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
887 // canonicalization pass that enables other optimizations. As a result,
888 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
889 // result too early.
890 OptimizePM.addPass(LoopSinkPass());
891
892 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000893 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000894
Sanjay Patel6fd43912017-09-09 13:38:18 +0000895 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
896 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
897 // flattening of blocks.
898 OptimizePM.addPass(DivRemPairsPass());
899
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000900 // LoopSink (and other loop passes since the last simplifyCFG) might have
901 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
902 OptimizePM.addPass(SimplifyCFGPass());
903
Chandler Carruthc34f7892017-11-28 11:32:31 +0000904 // Optimize PHIs by speculating around them when profitable. Note that this
905 // pass needs to be run after any PRE or similar pass as it is essentially
906 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
907 OptimizePM.addPass(SpeculateAroundPHIsPass());
908
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000909 for (auto &C : OptimizerLastEPCallbacks)
910 C(OptimizePM, Level);
911
Chandler Carrutha95ff382017-01-27 00:50:21 +0000912 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000913 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
914
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000915 MPM.addPass(CGProfilePass());
916
Chandler Carruthe3f50642016-12-22 06:59:15 +0000917 // Now we need to do some global optimization transforms.
918 // FIXME: It would seem like these should come first in the optimization
919 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
920 // ordering here.
921 MPM.addPass(GlobalDCEPass());
922 MPM.addPass(ConstantMergePass());
923
924 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000925}
926
Chandler Carruthe3f50642016-12-22 06:59:15 +0000927ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000928PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000929 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000930 assert(Level != O0 && "Must request optimizations for the default pipeline!");
931
932 ModulePassManager MPM(DebugLogging);
933
934 // Force any function attributes we want the rest of the pipeline to observe.
935 MPM.addPass(ForceFunctionAttrsPass());
936
David Blaikie0c64f5a2018-01-23 01:25:20 +0000937 // Apply module pipeline start EP callback.
938 for (auto &C : PipelineStartEPCallbacks)
939 C(MPM);
940
Dehao Chen08f88312017-08-07 20:23:20 +0000941 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000942 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
943
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000944 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000945 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
946 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000947
948 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000949 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000950
951 return MPM;
952}
953
954ModulePassManager
955PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
956 bool DebugLogging) {
957 assert(Level != O0 && "Must request optimizations for the default pipeline!");
958
959 ModulePassManager MPM(DebugLogging);
960
961 // Force any function attributes we want the rest of the pipeline to observe.
962 MPM.addPass(ForceFunctionAttrsPass());
963
Dehao Chen08f88312017-08-07 20:23:20 +0000964 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000965 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
966
David Blaikie0c64f5a2018-01-23 01:25:20 +0000967 // Apply module pipeline start EP callback.
968 for (auto &C : PipelineStartEPCallbacks)
969 C(MPM);
970
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000971 // If we are planning to perform ThinLTO later, we don't bloat the code with
972 // unrolling/vectorization/... now. Just simplify the module as much as we
973 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000974 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
975 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000976
977 // Run partial inlining pass to partially inline functions that have
978 // large bodies.
979 // FIXME: It isn't clear whether this is really the right place to run this
980 // in ThinLTO. Because there is another canonicalization and simplification
981 // phase that will run after the thin link, running this here ends up with
982 // less information than will be available later and it may grow functions in
983 // ways that aren't beneficial.
984 if (RunPartialInlining)
985 MPM.addPass(PartialInlinerPass());
986
987 // Reduce the size of the IR as much as possible.
988 MPM.addPass(GlobalOptPass());
989
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000990 return MPM;
991}
992
Teresa Johnson28023db2018-07-19 14:51:32 +0000993ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
994 OptimizationLevel Level, bool DebugLogging,
995 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000996 ModulePassManager MPM(DebugLogging);
997
Teresa Johnson28023db2018-07-19 14:51:32 +0000998 if (ImportSummary) {
999 // These passes import type identifier resolutions for whole-program
1000 // devirtualization and CFI. They must run early because other passes may
1001 // disturb the specific instruction patterns that these passes look for,
1002 // creating dependencies on resolutions that may not appear in the summary.
1003 //
1004 // For example, GVN may transform the pattern assume(type.test) appearing in
1005 // two basic blocks into assume(phi(type.test, type.test)), which would
1006 // transform a dependency on a WPD resolution into a dependency on a type
1007 // identifier resolution for CFI.
1008 //
1009 // Also, WPD has access to more precise information than ICP and can
1010 // devirtualize more effectively, so it should operate on the IR first.
1011 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1012 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1013 }
1014
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001015 // Force any function attributes we want the rest of the pipeline to observe.
1016 MPM.addPass(ForceFunctionAttrsPass());
1017
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001018 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001019 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1020 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001021
1022 // Now add the optimization pipeline.
1023 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1024
1025 return MPM;
1026}
1027
1028ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001029PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1030 bool DebugLogging) {
1031 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001032 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001033 return buildPerModuleDefaultPipeline(Level, DebugLogging,
1034 /*LTOPreLink=*/true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001035}
1036
Teresa Johnson28023db2018-07-19 14:51:32 +00001037ModulePassManager
1038PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1039 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001040 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1041 ModulePassManager MPM(DebugLogging);
1042
Xin Tong642c8d32018-11-15 18:06:42 +00001043 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
1044 // Load sample profile before running the LTO optimization pipeline.
1045 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
1046 PGOOpt->ProfileRemappingFile,
1047 false /* ThinLTOPhase::PreLink */));
1048 }
1049
Davide Italiano089a9122017-01-24 00:57:39 +00001050 // Remove unused virtual tables to improve the quality of code generated by
1051 // whole-program devirtualization and bitset lowering.
1052 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001053
Davide Italiano089a9122017-01-24 00:57:39 +00001054 // Force any function attributes we want the rest of the pipeline to observe.
1055 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001056
Davide Italiano089a9122017-01-24 00:57:39 +00001057 // Do basic inference of function attributes from known properties of system
1058 // libraries and other oracles.
1059 MPM.addPass(InferFunctionAttrsPass());
1060
1061 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001062 FunctionPassManager EarlyFPM(DebugLogging);
1063 EarlyFPM.addPass(CallSiteSplittingPass());
1064 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1065
Davide Italiano089a9122017-01-24 00:57:39 +00001066 // Indirect call promotion. This should promote all the targets that are
1067 // left by the earlier promotion pass that promotes intra-module targets.
1068 // This two-step promotion is to save the compile time. For LTO, it should
1069 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001070 MPM.addPass(PGOIndirectCallPromotion(
1071 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +00001072 // Propagate constants at call sites into the functions they call. This
1073 // opens opportunities for globalopt (and inlining) by substituting function
1074 // pointers passed as arguments to direct uses of functions.
1075 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001076
1077 // Attach metadata to indirect call sites indicating the set of functions
1078 // they may target at run-time. This should follow IPSCCP.
1079 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001080 }
1081
1082 // Now deduce any function attributes based in the current code.
1083 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1084 PostOrderFunctionAttrsPass()));
1085
1086 // Do RPO function attribute inference across the module to forward-propagate
1087 // attributes where applicable.
1088 // FIXME: Is this really an optimization rather than a canonicalization?
1089 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1090
Eric Christopher721eaef2019-02-26 20:33:22 +00001091 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001092 MPM.addPass(GlobalSplitPass());
1093
1094 // Run whole program optimization of virtual call when the list of callees
1095 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001096 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001097
1098 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001099 if (Level == 1) {
1100 // The LowerTypeTestsPass needs to run to lower type metadata and the
1101 // type.test intrinsics. The pass does nothing if CFI is disabled.
1102 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001103 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001104 }
Davide Italiano089a9122017-01-24 00:57:39 +00001105
1106 // Optimize globals to try and fold them into constants.
1107 MPM.addPass(GlobalOptPass());
1108
1109 // Promote any localized globals to SSA registers.
1110 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1111
1112 // Linking modules together can lead to duplicate global constant, only
1113 // keep one copy of each constant.
1114 MPM.addPass(ConstantMergePass());
1115
1116 // Remove unused arguments from functions.
1117 MPM.addPass(DeadArgumentEliminationPass());
1118
1119 // Reduce the code after globalopt and ipsccp. Both can open up significant
1120 // simplification opportunities, and both can propagate functions through
1121 // function pointers. When this happens, we often have to resolve varargs
1122 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001123 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001124 if (Level == O3)
1125 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001126 PeepholeFPM.addPass(InstCombinePass());
1127 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1128
1129 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001130
1131 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1132 // generally clean up exception handling overhead. It isn't clear this is
1133 // valuable as the inliner doesn't currently care whether it is inlining an
1134 // invoke or a call.
1135 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001136 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1137 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001138
1139 // Optimize globals again after we ran the inliner.
1140 MPM.addPass(GlobalOptPass());
1141
1142 // Garbage collect dead functions.
1143 // FIXME: Add ArgumentPromotion pass after once it's ported.
1144 MPM.addPass(GlobalDCEPass());
1145
1146 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001147 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001148 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001149 invokePeepholeEPCallbacks(FPM, Level);
1150
Davide Italiano089a9122017-01-24 00:57:39 +00001151 FPM.addPass(JumpThreadingPass());
1152
1153 // Break up allocas
1154 FPM.addPass(SROA());
1155
1156 // Run a few AA driver optimizations here and now to cleanup the code.
1157 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1158
1159 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1160 PostOrderFunctionAttrsPass()));
1161 // FIXME: here we run IP alias analysis in the legacy PM.
1162
1163 FunctionPassManager MainFPM;
1164
1165 // FIXME: once we fix LoopPass Manager, add LICM here.
1166 // FIXME: once we provide support for enabling MLSM, add it here.
1167 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001168 if (RunNewGVN)
1169 MainFPM.addPass(NewGVNPass());
1170 else
1171 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001172
1173 // Remove dead memcpy()'s.
1174 MainFPM.addPass(MemCpyOptPass());
1175
1176 // Nuke dead stores.
1177 MainFPM.addPass(DSEPass());
1178
1179 // FIXME: at this point, we run a bunch of loop passes:
1180 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1181 // loopVectorize. Enable them once the remaining issue with LPM
1182 // are sorted out.
1183
1184 MainFPM.addPass(InstCombinePass());
1185 MainFPM.addPass(SimplifyCFGPass());
1186 MainFPM.addPass(SCCPPass());
1187 MainFPM.addPass(InstCombinePass());
1188 MainFPM.addPass(BDCEPass());
1189
1190 // FIXME: We may want to run SLPVectorizer here.
1191 // After vectorization, assume intrinsics may tell us more
1192 // about pointer alignments.
1193#if 0
1194 MainFPM.add(AlignmentFromAssumptionsPass());
1195#endif
1196
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001197 // FIXME: Conditionally run LoadCombine here, after it's ported
1198 // (in case we still have this pass, given its questionable usefulness).
1199
Davide Italiano089a9122017-01-24 00:57:39 +00001200 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001201 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001202 MainFPM.addPass(JumpThreadingPass());
1203 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1204
1205 // Create a function that performs CFI checks for cross-DSO calls with
1206 // targets in the current module.
1207 MPM.addPass(CrossDSOCFIPass());
1208
1209 // Lower type metadata and the type.test intrinsic. This pass supports
1210 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1211 // to be run at link time if CFI is enabled. This pass does nothing if
1212 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001213 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001214
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001215 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1216 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1217 if (EnableHotColdSplit)
1218 MPM.addPass(HotColdSplittingPass());
1219
Davide Italiano089a9122017-01-24 00:57:39 +00001220 // Add late LTO optimization passes.
1221 // Delete basic blocks, which optimization passes may have killed.
1222 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1223
1224 // Drop bodies of available eternally objects to improve GlobalDCE.
1225 MPM.addPass(EliminateAvailableExternallyPass());
1226
1227 // Now that we have optimized the program, discard unreachable functions.
1228 MPM.addPass(GlobalDCEPass());
1229
1230 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001231 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001232}
1233
Chandler Carruth060ad612016-12-23 20:38:19 +00001234AAManager PassBuilder::buildDefaultAAPipeline() {
1235 AAManager AA;
1236
1237 // The order in which these are registered determines their priority when
1238 // being queried.
1239
1240 // First we register the basic alias analysis that provides the majority of
1241 // per-function local AA logic. This is a stateless, on-demand local set of
1242 // AA techniques.
1243 AA.registerFunctionAnalysis<BasicAA>();
1244
1245 // Next we query fast, specialized alias analyses that wrap IR-embedded
1246 // information about aliasing.
1247 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1248 AA.registerFunctionAnalysis<TypeBasedAA>();
1249
1250 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001251 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1252 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001253 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001254 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001255
1256 return AA;
1257}
1258
Chandler Carruth241bf242016-08-03 07:44:48 +00001259static Optional<int> parseRepeatPassName(StringRef Name) {
1260 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1261 return None;
1262 int Count;
1263 if (Name.getAsInteger(0, Count) || Count <= 0)
1264 return None;
1265 return Count;
1266}
1267
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001268static Optional<int> parseDevirtPassName(StringRef Name) {
1269 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1270 return None;
1271 int Count;
1272 if (Name.getAsInteger(0, Count) || Count <= 0)
1273 return None;
1274 return Count;
1275}
1276
Fedor Sergeevb7871402019-01-10 10:01:53 +00001277static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1278 if (!Name.consume_front(PassName))
1279 return false;
1280 // normal pass name w/o parameters == default parameters
1281 if (Name.empty())
1282 return true;
1283 return Name.startswith("<") && Name.endswith(">");
1284}
1285
1286namespace {
1287
1288/// This performs customized parsing of pass name with parameters.
1289///
1290/// We do not need parametrization of passes in textual pipeline very often,
1291/// yet on a rare occasion ability to specify parameters right there can be
1292/// useful.
1293///
1294/// \p Name - parameterized specification of a pass from a textual pipeline
1295/// is a string in a form of :
1296/// PassName '<' parameter-list '>'
1297///
1298/// Parameter list is being parsed by the parser callable argument, \p Parser,
1299/// It takes a string-ref of parameters and returns either StringError or a
1300/// parameter list in a form of a custom parameters type, all wrapped into
1301/// Expected<> template class.
1302///
1303template <typename ParametersParseCallableT>
1304auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1305 StringRef PassName) -> decltype(Parser(StringRef{})) {
1306 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1307
1308 StringRef Params = Name;
1309 if (!Params.consume_front(PassName)) {
1310 assert(false &&
1311 "unable to strip pass name from parametrized pass specification");
1312 }
1313 if (Params.empty())
1314 return ParametersT{};
1315 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1316 assert(false && "invalid format for parametrized pass name");
1317 }
1318
1319 Expected<ParametersT> Result = Parser(Params);
1320 assert((Result || Result.template errorIsA<StringError>()) &&
1321 "Pass parameter parser can only return StringErrors.");
1322 return std::move(Result);
1323}
1324
1325/// Parser of parameters for LoopUnroll pass.
1326Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1327 LoopUnrollOptions UnrollOpts;
1328 while (!Params.empty()) {
1329 StringRef ParamName;
1330 std::tie(ParamName, Params) = Params.split(';');
1331 int OptLevel = StringSwitch<int>(ParamName)
1332 .Case("O0", 0)
1333 .Case("O1", 1)
1334 .Case("O2", 2)
1335 .Case("O3", 3)
1336 .Default(-1);
1337 if (OptLevel >= 0) {
1338 UnrollOpts.setOptLevel(OptLevel);
1339 continue;
1340 }
1341
1342 bool Enable = !ParamName.consume_front("no-");
1343 if (ParamName == "partial") {
1344 UnrollOpts.setPartial(Enable);
1345 } else if (ParamName == "peeling") {
1346 UnrollOpts.setPeeling(Enable);
1347 } else if (ParamName == "runtime") {
1348 UnrollOpts.setRuntime(Enable);
1349 } else if (ParamName == "upperbound") {
1350 UnrollOpts.setUpperBound(Enable);
1351 } else {
1352 return make_error<StringError>(
1353 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1354 inconvertibleErrorCode());
1355 }
1356 }
1357 return UnrollOpts;
1358}
1359
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001360Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1361 MemorySanitizerOptions Result;
1362 while (!Params.empty()) {
1363 StringRef ParamName;
1364 std::tie(ParamName, Params) = Params.split(';');
1365
1366 if (ParamName == "recover") {
1367 Result.Recover = true;
1368 } else if (ParamName == "kernel") {
1369 Result.Kernel = true;
1370 } else if (ParamName.consume_front("track-origins=")) {
1371 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1372 return make_error<StringError>(
1373 formatv("invalid argument to MemorySanitizer pass track-origins "
1374 "parameter: '{0}' ",
1375 ParamName)
1376 .str(),
1377 inconvertibleErrorCode());
1378 } else {
1379 return make_error<StringError>(
1380 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1381 .str(),
1382 inconvertibleErrorCode());
1383 }
1384 }
1385 return Result;
1386}
1387
Fedor Sergeevb7871402019-01-10 10:01:53 +00001388} // namespace
1389
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001390/// Tests whether a pass name starts with a valid prefix for a default pipeline
1391/// alias.
1392static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1393 return Name.startswith("default") || Name.startswith("thinlto") ||
1394 Name.startswith("lto");
1395}
1396
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001397/// Tests whether registered callbacks will accept a given pass name.
1398///
1399/// When parsing a pipeline text, the type of the outermost pipeline may be
1400/// omitted, in which case the type is automatically determined from the first
1401/// pass name in the text. This may be a name that is handled through one of the
1402/// callbacks. We check this through the oridinary parsing callbacks by setting
1403/// up a dummy PassManager in order to not force the client to also handle this
1404/// type of query.
1405template <typename PassManagerT, typename CallbacksT>
1406static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1407 if (!Callbacks.empty()) {
1408 PassManagerT DummyPM;
1409 for (auto &CB : Callbacks)
1410 if (CB(Name, DummyPM, {}))
1411 return true;
1412 }
1413 return false;
1414}
1415
1416template <typename CallbacksT>
1417static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001418 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001419 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001420 return DefaultAliasRegex.match(Name);
1421
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001422 // Explicitly handle pass manager names.
1423 if (Name == "module")
1424 return true;
1425 if (Name == "cgscc")
1426 return true;
1427 if (Name == "function")
1428 return true;
1429
Chandler Carruth241bf242016-08-03 07:44:48 +00001430 // Explicitly handle custom-parsed pass names.
1431 if (parseRepeatPassName(Name))
1432 return true;
1433
Chandler Carruth74a8a222016-06-17 07:15:29 +00001434#define MODULE_PASS(NAME, CREATE_PASS) \
1435 if (Name == NAME) \
1436 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001437#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001438 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001439 return true;
1440#include "PassRegistry.def"
1441
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001442 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001443}
1444
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001445template <typename CallbacksT>
1446static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001447 // Explicitly handle pass manager names.
1448 if (Name == "cgscc")
1449 return true;
1450 if (Name == "function")
1451 return true;
1452
Chandler Carruth241bf242016-08-03 07:44:48 +00001453 // Explicitly handle custom-parsed pass names.
1454 if (parseRepeatPassName(Name))
1455 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001456 if (parseDevirtPassName(Name))
1457 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001458
Chandler Carruth74a8a222016-06-17 07:15:29 +00001459#define CGSCC_PASS(NAME, CREATE_PASS) \
1460 if (Name == NAME) \
1461 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001462#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001463 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001464 return true;
1465#include "PassRegistry.def"
1466
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001467 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001468}
1469
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001470template <typename CallbacksT>
1471static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001472 // Explicitly handle pass manager names.
1473 if (Name == "function")
1474 return true;
1475 if (Name == "loop")
1476 return true;
1477
Chandler Carruth241bf242016-08-03 07:44:48 +00001478 // Explicitly handle custom-parsed pass names.
1479 if (parseRepeatPassName(Name))
1480 return true;
1481
Chandler Carruth74a8a222016-06-17 07:15:29 +00001482#define FUNCTION_PASS(NAME, CREATE_PASS) \
1483 if (Name == NAME) \
1484 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001485#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1486 if (checkParametrizedPassName(Name, NAME)) \
1487 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001488#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001489 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001490 return true;
1491#include "PassRegistry.def"
1492
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001493 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001494}
1495
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001496template <typename CallbacksT>
1497static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001498 // Explicitly handle pass manager names.
1499 if (Name == "loop")
1500 return true;
1501
Chandler Carruth241bf242016-08-03 07:44:48 +00001502 // Explicitly handle custom-parsed pass names.
1503 if (parseRepeatPassName(Name))
1504 return true;
1505
Chandler Carruth74a8a222016-06-17 07:15:29 +00001506#define LOOP_PASS(NAME, CREATE_PASS) \
1507 if (Name == NAME) \
1508 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001509#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1510 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1511 return true;
1512#include "PassRegistry.def"
1513
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001514 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001515}
1516
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001517Optional<std::vector<PassBuilder::PipelineElement>>
1518PassBuilder::parsePipelineText(StringRef Text) {
1519 std::vector<PipelineElement> ResultPipeline;
1520
1521 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1522 &ResultPipeline};
1523 for (;;) {
1524 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1525 size_t Pos = Text.find_first_of(",()");
1526 Pipeline.push_back({Text.substr(0, Pos), {}});
1527
1528 // If we have a single terminating name, we're done.
1529 if (Pos == Text.npos)
1530 break;
1531
1532 char Sep = Text[Pos];
1533 Text = Text.substr(Pos + 1);
1534 if (Sep == ',')
1535 // Just a name ending in a comma, continue.
1536 continue;
1537
1538 if (Sep == '(') {
1539 // Push the inner pipeline onto the stack to continue processing.
1540 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1541 continue;
1542 }
1543
1544 assert(Sep == ')' && "Bogus separator!");
1545 // When handling the close parenthesis, we greedily consume them to avoid
1546 // empty strings in the pipeline.
1547 do {
1548 // If we try to pop the outer pipeline we have unbalanced parentheses.
1549 if (PipelineStack.size() == 1)
1550 return None;
1551
1552 PipelineStack.pop_back();
1553 } while (Text.consume_front(")"));
1554
1555 // Check if we've finished parsing.
1556 if (Text.empty())
1557 break;
1558
1559 // Otherwise, the end of an inner pipeline always has to be followed by
1560 // a comma, and then we can continue.
1561 if (!Text.consume_front(","))
1562 return None;
1563 }
1564
1565 if (PipelineStack.size() > 1)
1566 // Unbalanced paretheses.
1567 return None;
1568
1569 assert(PipelineStack.back() == &ResultPipeline &&
1570 "Wrong pipeline at the bottom of the stack!");
1571 return {std::move(ResultPipeline)};
1572}
1573
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001574Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1575 const PipelineElement &E,
1576 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001577 auto &Name = E.Name;
1578 auto &InnerPipeline = E.InnerPipeline;
1579
1580 // First handle complex passes like the pass managers which carry pipelines.
1581 if (!InnerPipeline.empty()) {
1582 if (Name == "module") {
1583 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001584 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1585 VerifyEachPass, DebugLogging))
1586 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001587 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001588 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001589 }
1590 if (Name == "cgscc") {
1591 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001592 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1593 DebugLogging))
1594 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001595 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001596 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001597 }
1598 if (Name == "function") {
1599 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001600 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1601 VerifyEachPass, DebugLogging))
1602 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001603 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001604 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001605 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001606 if (auto Count = parseRepeatPassName(Name)) {
1607 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001608 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1609 VerifyEachPass, DebugLogging))
1610 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001611 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001612 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001613 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001614
1615 for (auto &C : ModulePipelineParsingCallbacks)
1616 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001617 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001618
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001619 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001620 return make_error<StringError>(
1621 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1622 inconvertibleErrorCode());
1623 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001624 }
1625
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001626 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001627 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001628 SmallVector<StringRef, 3> Matches;
1629 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001630 return make_error<StringError>(
1631 formatv("unknown default pipeline alias '{0}'", Name).str(),
1632 inconvertibleErrorCode());
1633
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001634 assert(Matches.size() == 3 && "Must capture two matched strings!");
1635
Jordan Rosef85a95f2016-07-25 18:34:51 +00001636 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001637 .Case("O0", O0)
1638 .Case("O1", O1)
1639 .Case("O2", O2)
1640 .Case("O3", O3)
1641 .Case("Os", Os)
1642 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001643 if (L == O0)
1644 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001645 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001646
1647 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001648 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001649 } else if (Matches[1] == "thinlto-pre-link") {
1650 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1651 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001652 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001653 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001654 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001655 } else {
1656 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001657 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001658 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001659 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001660 }
1661
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001662 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001663#define MODULE_PASS(NAME, CREATE_PASS) \
1664 if (Name == NAME) { \
1665 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001666 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001667 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001668#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1669 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001670 MPM.addPass( \
1671 RequireAnalysisPass< \
1672 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001673 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001674 } \
1675 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001676 MPM.addPass(InvalidateAnalysisPass< \
1677 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001678 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001679 }
1680#include "PassRegistry.def"
1681
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001682 for (auto &C : ModulePipelineParsingCallbacks)
1683 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001684 return Error::success();
1685 return make_error<StringError>(
1686 formatv("unknown module pass '{0}'", Name).str(),
1687 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001688}
1689
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001690Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1691 const PipelineElement &E, bool VerifyEachPass,
1692 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001693 auto &Name = E.Name;
1694 auto &InnerPipeline = E.InnerPipeline;
1695
1696 // First handle complex passes like the pass managers which carry pipelines.
1697 if (!InnerPipeline.empty()) {
1698 if (Name == "cgscc") {
1699 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001700 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1701 VerifyEachPass, DebugLogging))
1702 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001703 // Add the nested pass manager with the appropriate adaptor.
1704 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001705 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001706 }
1707 if (Name == "function") {
1708 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001709 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1710 VerifyEachPass, DebugLogging))
1711 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001712 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001713 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001714 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001715 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001716 if (auto Count = parseRepeatPassName(Name)) {
1717 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001718 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1719 VerifyEachPass, DebugLogging))
1720 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001721 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001722 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001723 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001724 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1725 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001726 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1727 VerifyEachPass, DebugLogging))
1728 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001729 CGPM.addPass(
1730 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001731 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001732 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001733
1734 for (auto &C : CGSCCPipelineParsingCallbacks)
1735 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001736 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001737
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001738 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001739 return make_error<StringError>(
1740 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1741 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001742 }
1743
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001744// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001745#define CGSCC_PASS(NAME, CREATE_PASS) \
1746 if (Name == NAME) { \
1747 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001748 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001749 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001750#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1751 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001752 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001753 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001754 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1755 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001756 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001757 } \
1758 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001759 CGPM.addPass(InvalidateAnalysisPass< \
1760 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001761 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001762 }
1763#include "PassRegistry.def"
1764
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001765 for (auto &C : CGSCCPipelineParsingCallbacks)
1766 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001767 return Error::success();
1768 return make_error<StringError>(
1769 formatv("unknown cgscc pass '{0}'", Name).str(),
1770 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001771}
1772
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001773Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1774 const PipelineElement &E,
1775 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001776 auto &Name = E.Name;
1777 auto &InnerPipeline = E.InnerPipeline;
1778
1779 // First handle complex passes like the pass managers which carry pipelines.
1780 if (!InnerPipeline.empty()) {
1781 if (Name == "function") {
1782 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001783 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1784 VerifyEachPass, DebugLogging))
1785 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001786 // Add the nested pass manager with the appropriate adaptor.
1787 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001788 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001789 }
1790 if (Name == "loop") {
1791 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001792 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1793 DebugLogging))
1794 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001795 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001796 FPM.addPass(
1797 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001798 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001799 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001800 if (auto Count = parseRepeatPassName(Name)) {
1801 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001802 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1803 VerifyEachPass, DebugLogging))
1804 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001805 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001806 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001807 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001808
1809 for (auto &C : FunctionPipelineParsingCallbacks)
1810 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001811 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001812
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001813 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001814 return make_error<StringError>(
1815 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1816 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001817 }
1818
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001819// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001820#define FUNCTION_PASS(NAME, CREATE_PASS) \
1821 if (Name == NAME) { \
1822 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001823 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001824 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001825#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1826 if (checkParametrizedPassName(Name, NAME)) { \
1827 auto Params = parsePassParameters(PARSER, Name, NAME); \
1828 if (!Params) \
1829 return Params.takeError(); \
1830 FPM.addPass(CREATE_PASS(Params.get())); \
1831 return Error::success(); \
1832 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001833#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1834 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001835 FPM.addPass( \
1836 RequireAnalysisPass< \
1837 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001838 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001839 } \
1840 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001841 FPM.addPass(InvalidateAnalysisPass< \
1842 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001843 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001844 }
1845#include "PassRegistry.def"
1846
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001847 for (auto &C : FunctionPipelineParsingCallbacks)
1848 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001849 return Error::success();
1850 return make_error<StringError>(
1851 formatv("unknown function pass '{0}'", Name).str(),
1852 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001853}
1854
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001855Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1856 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001857 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001858 auto &InnerPipeline = E.InnerPipeline;
1859
1860 // First handle complex passes like the pass managers which carry pipelines.
1861 if (!InnerPipeline.empty()) {
1862 if (Name == "loop") {
1863 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001864 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1865 VerifyEachPass, DebugLogging))
1866 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001867 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001868 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001869 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001870 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001871 if (auto Count = parseRepeatPassName(Name)) {
1872 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001873 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1874 VerifyEachPass, DebugLogging))
1875 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001876 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001877 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001878 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001879
1880 for (auto &C : LoopPipelineParsingCallbacks)
1881 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001882 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001883
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001884 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001885 return make_error<StringError>(
1886 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1887 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001888 }
1889
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001890// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001891#define LOOP_PASS(NAME, CREATE_PASS) \
1892 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001893 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001894 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001895 }
1896#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1897 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001898 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001899 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1900 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1901 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001902 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001903 } \
1904 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001905 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001906 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001907 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001908 }
1909#include "PassRegistry.def"
1910
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001911 for (auto &C : LoopPipelineParsingCallbacks)
1912 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001913 return Error::success();
1914 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1915 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001916}
1917
Chandler Carruthedf59962016-02-18 09:45:17 +00001918bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001919#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1920 if (Name == NAME) { \
1921 AA.registerModuleAnalysis< \
1922 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1923 return true; \
1924 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001925#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1926 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001927 AA.registerFunctionAnalysis< \
1928 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001929 return true; \
1930 }
1931#include "PassRegistry.def"
1932
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001933 for (auto &C : AAParsingCallbacks)
1934 if (C(Name, AA))
1935 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001936 return false;
1937}
1938
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001939Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001940 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001941 bool VerifyEachPass,
1942 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001943 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001944 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1945 return Err;
1946 // FIXME: No verifier support for Loop passes!
1947 }
1948 return Error::success();
1949}
1950
1951Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1952 ArrayRef<PipelineElement> Pipeline,
1953 bool VerifyEachPass,
1954 bool DebugLogging) {
1955 for (const auto &Element : Pipeline) {
1956 if (auto Err =
1957 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1958 return Err;
1959 if (VerifyEachPass)
1960 FPM.addPass(VerifierPass());
1961 }
1962 return Error::success();
1963}
1964
1965Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1966 ArrayRef<PipelineElement> Pipeline,
1967 bool VerifyEachPass,
1968 bool DebugLogging) {
1969 for (const auto &Element : Pipeline) {
1970 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1971 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001972 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001973 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001974 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00001975}
1976
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001977void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1978 FunctionAnalysisManager &FAM,
1979 CGSCCAnalysisManager &CGAM,
1980 ModuleAnalysisManager &MAM) {
1981 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1982 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001983 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1984 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1985 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1986 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1987 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1988}
1989
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001990Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1991 ArrayRef<PipelineElement> Pipeline,
1992 bool VerifyEachPass,
1993 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001994 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001995 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1996 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001997 if (VerifyEachPass)
1998 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001999 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002000 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002001}
2002
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002003// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002004// FIXME: Should this routine accept a TargetMachine or require the caller to
2005// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002006Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2007 StringRef PipelineText,
2008 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002009 auto Pipeline = parsePipelineText(PipelineText);
2010 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002011 return make_error<StringError>(
2012 formatv("invalid pipeline '{0}'", PipelineText).str(),
2013 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002014
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002015 // If the first name isn't at the module layer, wrap the pipeline up
2016 // automatically.
2017 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002018
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002019 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2020 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002021 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002022 } else if (isFunctionPassName(FirstName,
2023 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002024 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002025 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002026 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002027 } else {
2028 for (auto &C : TopLevelPipelineParsingCallbacks)
2029 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002030 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002031
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002032 // Unknown pass or pipeline name!
2033 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2034 return make_error<StringError>(
2035 formatv("unknown {0} name '{1}'",
2036 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2037 .str(),
2038 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002039 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002040 }
2041
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002042 if (auto Err =
2043 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2044 return Err;
2045 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002046}
Chandler Carruthedf59962016-02-18 09:45:17 +00002047
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002048// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002049Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2050 StringRef PipelineText,
2051 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002052 auto Pipeline = parsePipelineText(PipelineText);
2053 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002054 return make_error<StringError>(
2055 formatv("invalid pipeline '{0}'", PipelineText).str(),
2056 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002057
2058 StringRef FirstName = Pipeline->front().Name;
2059 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002060 return make_error<StringError>(
2061 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2062 PipelineText)
2063 .str(),
2064 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002065
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002066 if (auto Err =
2067 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2068 return Err;
2069 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002070}
2071
2072// Primary pass pipeline description parsing routine for a \c
2073// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002074Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2075 StringRef PipelineText,
2076 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002077 auto Pipeline = parsePipelineText(PipelineText);
2078 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002079 return make_error<StringError>(
2080 formatv("invalid pipeline '{0}'", PipelineText).str(),
2081 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002082
2083 StringRef FirstName = Pipeline->front().Name;
2084 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002085 return make_error<StringError>(
2086 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2087 PipelineText)
2088 .str(),
2089 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002090
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002091 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2092 DebugLogging))
2093 return Err;
2094 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002095}
2096
2097// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002098Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2099 StringRef PipelineText,
2100 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002101 auto Pipeline = parsePipelineText(PipelineText);
2102 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002103 return make_error<StringError>(
2104 formatv("invalid pipeline '{0}'", PipelineText).str(),
2105 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002106
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002107 if (auto Err =
2108 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2109 return Err;
2110
2111 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002112}
2113
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002114Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002115 // If the pipeline just consists of the word 'default' just replace the AA
2116 // manager with our default one.
2117 if (PipelineText == "default") {
2118 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002119 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002120 }
2121
Chandler Carruthedf59962016-02-18 09:45:17 +00002122 while (!PipelineText.empty()) {
2123 StringRef Name;
2124 std::tie(Name, PipelineText) = PipelineText.split(',');
2125 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002126 return make_error<StringError>(
2127 formatv("unknown alias analysis name '{0}'", Name).str(),
2128 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002129 }
2130
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002131 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002132}