blob: 2baff8990105d7b485cf9fd3868771a453a0235d [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.
Rong Xudb29a3a2019-03-04 20:21:27 +0000409 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000410 !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.
Rong Xudb29a3a2019-03-04 20:21:27 +0000452 if (Phase != ThinLTOPhase::PreLink || !PGOOpt ||
453 PGOOpt->Action != PGOOptions::SampleUse)
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 &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000513 (PGOOpt->Action == PGOOptions::IRUse ||
514 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000515 FPM.addPass(ControlHeightReductionPass());
516
Chandler Carruthe3f50642016-12-22 06:59:15 +0000517 return FPM;
518}
519
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000520void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
521 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000522 bool RunProfileGen, bool IsCS,
523 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000524 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
Rong Xudb29a3a2019-03-04 20:21:27 +0000528 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
529 // IsCS is true).
530 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000531 InlineParams IP;
532
533 // In the old pass manager, this is a cl::opt. Should still this be one?
534 IP.DefaultThreshold = 75;
535
536 // FIXME: The hint threshold has the same value used by the regular inliner.
537 // This should probably be lowered after performance testing.
538 // FIXME: this comment is cargo culted from the old pass manager, revisit).
539 IP.HintThreshold = 325;
540
541 CGSCCPassManager CGPipeline(DebugLogging);
542
543 CGPipeline.addPass(InlinerPass(IP));
544
545 FunctionPassManager FPM;
546 FPM.addPass(SROA());
547 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
548 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
549 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000550 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000551
Davide Italiano513dfaa2017-02-13 15:26:22 +0000552 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
553
554 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
555 }
556
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000557 // Delete anything that is now dead to make sure that we don't instrument
558 // dead code. Instrumentation can end up keeping dead code around and
559 // dramatically increase code size.
560 MPM.addPass(GlobalDCEPass());
561
Davide Italiano513dfaa2017-02-13 15:26:22 +0000562 if (RunProfileGen) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000563 MPM.addPass(PGOInstrumentationGen(IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000564
Xinliang David Lib67530e2017-06-25 00:26:43 +0000565 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000566 FPM.addPass(
567 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000568 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
569
Davide Italiano513dfaa2017-02-13 15:26:22 +0000570 // Add the profile lowering pass.
571 InstrProfOptions Options;
Rong Xudb29a3a2019-03-04 20:21:27 +0000572 if (!ProfileFile.empty())
573 Options.InstrProfileOutput = ProfileFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000574 Options.DoCounterPromotion = true;
Rong Xudb29a3a2019-03-04 20:21:27 +0000575 Options.UseBFIInPromotion = IsCS;
576 MPM.addPass(InstrProfiling(Options, IsCS));
577 } else if (!ProfileFile.empty())
578 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000579}
580
Easwaran Raman8249fac2017-06-28 13:33:49 +0000581static InlineParams
582getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
583 auto O3 = PassBuilder::O3;
584 unsigned OptLevel = Level > O3 ? 2 : Level;
585 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
586 return getInlineParams(OptLevel, SizeLevel);
587}
588
Chandler Carruthe3f50642016-12-22 06:59:15 +0000589ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000590PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000591 ThinLTOPhase Phase,
592 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000593 ModulePassManager MPM(DebugLogging);
594
Rong Xudb29a3a2019-03-04 20:21:27 +0000595 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000596
597 // In ThinLTO mode, when flattened profile is used, all the available
598 // profile information will be annotated in PreLink phase so there is
599 // no need to load the profile again in PostLink.
600 bool LoadSampleProfile =
601 HasSampleProfile &&
602 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
603
604 // During the ThinLTO backend phase we perform early indirect call promotion
605 // here, before globalopt. Otherwise imported available_externally functions
606 // look unreferenced and are removed. If we are going to load the sample
607 // profile then defer until later.
608 // TODO: See if we can move later and consolidate with the location where
609 // we perform ICP when we are loading a sample profile.
610 // TODO: We pass HasSampleProfile (whether there was a sample profile file
611 // passed to the compile) to the SamplePGO flag of ICP. This is used to
612 // determine whether the new direct calls are annotated with prof metadata.
613 // Ideally this should be determined from whether the IR is annotated with
614 // sample profile, and not whether the a sample profile was provided on the
615 // command line. E.g. for flattened profiles where we will not be reloading
616 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
617 // provide the sample profile file.
618 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
619 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
620
Chandler Carruthe3f50642016-12-22 06:59:15 +0000621 // Do basic inference of function attributes from known properties of system
622 // libraries and other oracles.
623 MPM.addPass(InferFunctionAttrsPass());
624
625 // Create an early function pass manager to cleanup the output of the
626 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000627 FunctionPassManager EarlyFPM(DebugLogging);
628 EarlyFPM.addPass(SimplifyCFGPass());
629 EarlyFPM.addPass(SROA());
630 EarlyFPM.addPass(EarlyCSEPass());
631 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000632 if (Level == O3)
633 EarlyFPM.addPass(CallSiteSplittingPass());
634
Dehao Chen08f88312017-08-07 20:23:20 +0000635 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
636 // to convert bitcast to direct calls so that they can be inlined during the
637 // profile annotation prepration step.
638 // More details about SamplePGO design can be found in:
639 // https://research.google.com/pubs/pub45290.html
640 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000641 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000642 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000643 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000644
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000645 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000646 // Annotate sample profile right after early FPM to ensure freshness of
647 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000648 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000649 PGOOpt->ProfileRemappingFile,
650 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000651 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
652 // for the profile annotation to be accurate in the ThinLTO backend.
653 if (Phase != ThinLTOPhase::PreLink)
654 // We perform early indirect call promotion here, before globalopt.
655 // This is important for the ThinLTO backend phase because otherwise
656 // imported available_externally functions look unreferenced and are
657 // removed.
658 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000659 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000660 }
661
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000662 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000663 // and prior to optimizing globals.
664 // FIXME: This position in the pipeline hasn't been carefully considered in
665 // years, it should be re-analyzed.
666 MPM.addPass(IPSCCPPass());
667
Matthew Simpsoncb585582017-10-25 13:40:08 +0000668 // Attach metadata to indirect call sites indicating the set of functions
669 // they may target at run-time. This should follow IPSCCP.
670 MPM.addPass(CalledValuePropagationPass());
671
Chandler Carruthe3f50642016-12-22 06:59:15 +0000672 // Optimize globals to try and fold them into constants.
673 MPM.addPass(GlobalOptPass());
674
675 // Promote any localized globals to SSA registers.
676 // FIXME: Should this instead by a run of SROA?
677 // FIXME: We should probably run instcombine and simplify-cfg afterward to
678 // delete control flows that are dead once globals have been folded to
679 // constants.
680 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
681
682 // Remove any dead arguments exposed by cleanups and constand folding
683 // globals.
684 MPM.addPass(DeadArgumentEliminationPass());
685
686 // Create a small function pass pipeline to cleanup after all the global
687 // optimizations.
688 FunctionPassManager GlobalCleanupPM(DebugLogging);
689 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000690 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
691
Chandler Carruthe3f50642016-12-22 06:59:15 +0000692 GlobalCleanupPM.addPass(SimplifyCFGPass());
693 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
694
Dehao Chen89d32262017-08-02 01:28:31 +0000695 // Add all the requested passes for instrumentation PGO, if requested.
696 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000697 (PGOOpt->Action == PGOOptions::IRInstr ||
698 PGOOpt->Action == PGOOptions::IRUse)) {
699 addPGOInstrPasses(MPM, DebugLogging, Level,
700 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
701 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000702 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000703 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000704 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000705 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
706 PGOOpt->CSAction == PGOOptions::CSIRInstr)
707 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000708
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000709 // Synthesize function entry counts for non-PGO compilation.
710 if (EnableSyntheticCounts && !PGOOpt)
711 MPM.addPass(SyntheticCountsPropagation());
712
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000713 // Require the GlobalsAA analysis for the module so we can query it within
714 // the CGSCC pipeline.
715 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000716
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000717 // Require the ProfileSummaryAnalysis for the module so we can query it within
718 // the inliner pass.
719 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
720
Chandler Carruthe3f50642016-12-22 06:59:15 +0000721 // Now begin the main postorder CGSCC pipeline.
722 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
723 // manager and trying to emulate its precise behavior. Much of this doesn't
724 // make a lot of sense and we should revisit the core CGSCC structure.
725 CGSCCPassManager MainCGPipeline(DebugLogging);
726
727 // Note: historically, the PruneEH pass was run first to deduce nounwind and
728 // generally clean up exception handling overhead. It isn't clear this is
729 // valuable as the inliner doesn't currently care whether it is inlining an
730 // invoke or a call.
731
732 // Run the inliner first. The theory is that we are walking bottom-up and so
733 // the callees have already been fully optimized, and we want to inline them
734 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000735 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000736 // because it makes profile annotation in the backend inaccurate.
737 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000738 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
739 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000740 IP.HotCallSiteThreshold = 0;
741 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000742
743 // Now deduce any function attributes based in the current code.
744 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
745
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000746 // When at O3 add argument promotion to the pass pipeline.
747 // FIXME: It isn't at all clear why this should be limited to O3.
748 if (Level == O3)
749 MainCGPipeline.addPass(ArgumentPromotionPass());
750
Chandler Carruthe3f50642016-12-22 06:59:15 +0000751 // Lastly, add the core function simplification pipeline nested inside the
752 // CGSCC walk.
753 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000754 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000755
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000756 for (auto &C : CGSCCOptimizerLateEPCallbacks)
757 C(MainCGPipeline, Level);
758
Chandler Carruth719ffe12017-02-12 05:38:04 +0000759 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
760 // to detect when we devirtualize indirect calls and iterate the SCC passes
761 // in that case to try and catch knock-on inlining or function attrs
762 // opportunities. Then we add it to the module pipeline by walking the SCCs
763 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000764 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000765 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000766 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000767
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000768 return MPM;
769}
770
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000771ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
772 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000773 ModulePassManager MPM(DebugLogging);
774
775 // Optimize globals now that the module is fully simplified.
776 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000777 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000778
Xinliang David Li126157c2017-05-22 16:41:57 +0000779 // Run partial inlining pass to partially inline functions that have
780 // large bodies.
781 if (RunPartialInlining)
782 MPM.addPass(PartialInlinerPass());
783
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000784 // Remove avail extern fns and globals definitions since we aren't compiling
785 // an object file for later LTO. For LTO we want to preserve these so they
786 // are eligible for inlining at link-time. Note if they are unreferenced they
787 // will be removed by GlobalDCE later, so this only impacts referenced
788 // available externally globals. Eventually they will be suppressed during
789 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
790 // may make globals referenced by available external functions dead and saves
791 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000792 MPM.addPass(EliminateAvailableExternallyPass());
793
Manman Ren18295122019-02-28 20:13:38 +0000794 if (EnableOrderFileInstrumentation)
795 MPM.addPass(InstrOrderFilePass());
796
Chandler Carruthe3f50642016-12-22 06:59:15 +0000797 // Do RPO function attribute inference across the module to forward-propagate
798 // attributes where applicable.
799 // FIXME: Is this really an optimization rather than a canonicalization?
800 MPM.addPass(ReversePostOrderFunctionAttrsPass());
801
Rong Xudb29a3a2019-03-04 20:21:27 +0000802 // Do a post inline PGO instrumentation and use pass. This is a context
803 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
804 // cross-module inline has not been done yet. The context sensitive
805 // instrumentation is after all the inlines are done.
806 if (!LTOPreLink && PGOOpt) {
807 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
808 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
809 /* IsCS */ true, PGOOpt->CSProfileGenFile,
810 PGOOpt->ProfileRemappingFile);
811 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
812 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
813 /* IsCS */ true, PGOOpt->ProfileFile,
814 PGOOpt->ProfileRemappingFile);
815 }
816
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000817 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000818 // useful as the above will have inlined, DCE'ed, and function-attr
819 // propagated everything. We should at this point have a reasonably minimal
820 // and richly annotated call graph. By computing aliasing and mod/ref
821 // information for all local globals here, the late loop passes and notably
822 // the vectorizer will be able to use them to help recognize vectorizable
823 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000824 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000825
826 FunctionPassManager OptimizePM(DebugLogging);
827 OptimizePM.addPass(Float2IntPass());
828 // FIXME: We need to run some loop optimizations to re-rotate loops after
829 // simplify-cfg and others undo their rotation.
830
831 // Optimize the loop execution. These passes operate on entire loop nests
832 // rather than on each loop in an inside-out manner, and so they are actually
833 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000834
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000835 for (auto &C : VectorizerStartEPCallbacks)
836 C(OptimizePM, Level);
837
Chandler Carrutha95ff382017-01-27 00:50:21 +0000838 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000839 OptimizePM.addPass(
840 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000841
842 // Distribute loops to allow partial vectorization. I.e. isolate dependences
843 // into separate loop that would otherwise inhibit vectorization. This is
844 // currently only performed for loops marked with the metadata
845 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000846 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000847
848 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000849 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000850
Chandler Carruthbaabda92017-01-27 01:32:26 +0000851 // Eliminate loads by forwarding stores from the previous iteration to loads
852 // of the current iteration.
853 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000854
855 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000856 OptimizePM.addPass(InstCombinePass());
857
Chandler Carrutha95ff382017-01-27 00:50:21 +0000858 // Now that we've formed fast to execute loop structures, we do further
859 // optimizations. These are run afterward as they might block doing complex
860 // analyses and transforms such as what are needed for loop vectorization.
861
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000862 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
863 // GVN, loop transforms, and others have already run, so it's now better to
864 // convert to more optimized IR using more aggressive simplify CFG options.
865 // The extra sinking transform can create larger basic blocks, so do this
866 // before SLP vectorization.
867 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
868 forwardSwitchCondToPhi(true).
869 convertSwitchToLookupTable(true).
870 needCanonicalLoops(false).
871 sinkCommonInsts(true)));
872
Chandler Carruthe3f50642016-12-22 06:59:15 +0000873 // Optimize parallel scalar instruction chains into SIMD instructions.
874 OptimizePM.addPass(SLPVectorizerPass());
875
Chandler Carruthe3f50642016-12-22 06:59:15 +0000876 OptimizePM.addPass(InstCombinePass());
877
878 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000879 // execution resources of an out-of-order processor. We also then need to
880 // clean up redundancies and loop invariant code.
881 // FIXME: It would be really good to use a loop-integrated instruction
882 // combiner for cleanup here so that the unrolling and LICM can be pipelined
883 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000884 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
885 if (EnableUnrollAndJam) {
886 OptimizePM.addPass(
887 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
888 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000889 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000890 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000891 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000892 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000893 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000894
895 // Now that we've vectorized and unrolled loops, we may have more refined
896 // alignment information, try to re-derive it here.
897 OptimizePM.addPass(AlignmentFromAssumptionsPass());
898
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000899 // Split out cold code. Splitting is done late to avoid hiding context from
900 // other optimizations and inadvertently regressing performance. The tradeoff
901 // is that this has a higher code size cost than splitting early.
902 if (EnableHotColdSplit && !LTOPreLink)
903 MPM.addPass(HotColdSplittingPass());
904
Chandler Carrutha95ff382017-01-27 00:50:21 +0000905 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
906 // canonicalization pass that enables other optimizations. As a result,
907 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
908 // result too early.
909 OptimizePM.addPass(LoopSinkPass());
910
911 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000912 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000913
Sanjay Patel6fd43912017-09-09 13:38:18 +0000914 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
915 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
916 // flattening of blocks.
917 OptimizePM.addPass(DivRemPairsPass());
918
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000919 // LoopSink (and other loop passes since the last simplifyCFG) might have
920 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
921 OptimizePM.addPass(SimplifyCFGPass());
922
Chandler Carruthc34f7892017-11-28 11:32:31 +0000923 // Optimize PHIs by speculating around them when profitable. Note that this
924 // pass needs to be run after any PRE or similar pass as it is essentially
925 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
926 OptimizePM.addPass(SpeculateAroundPHIsPass());
927
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000928 for (auto &C : OptimizerLastEPCallbacks)
929 C(OptimizePM, Level);
930
Chandler Carrutha95ff382017-01-27 00:50:21 +0000931 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000932 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
933
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000934 MPM.addPass(CGProfilePass());
935
Chandler Carruthe3f50642016-12-22 06:59:15 +0000936 // Now we need to do some global optimization transforms.
937 // FIXME: It would seem like these should come first in the optimization
938 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
939 // ordering here.
940 MPM.addPass(GlobalDCEPass());
941 MPM.addPass(ConstantMergePass());
942
943 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000944}
945
Chandler Carruthe3f50642016-12-22 06:59:15 +0000946ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000947PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000948 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000949 assert(Level != O0 && "Must request optimizations for the default pipeline!");
950
951 ModulePassManager MPM(DebugLogging);
952
953 // Force any function attributes we want the rest of the pipeline to observe.
954 MPM.addPass(ForceFunctionAttrsPass());
955
David Blaikie0c64f5a2018-01-23 01:25:20 +0000956 // Apply module pipeline start EP callback.
957 for (auto &C : PipelineStartEPCallbacks)
958 C(MPM);
959
Dehao Chen08f88312017-08-07 20:23:20 +0000960 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000961 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
962
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000963 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000964 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
965 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000966
967 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000968 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000969
970 return MPM;
971}
972
973ModulePassManager
974PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
975 bool DebugLogging) {
976 assert(Level != O0 && "Must request optimizations for the default pipeline!");
977
978 ModulePassManager MPM(DebugLogging);
979
980 // Force any function attributes we want the rest of the pipeline to observe.
981 MPM.addPass(ForceFunctionAttrsPass());
982
Dehao Chen08f88312017-08-07 20:23:20 +0000983 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000984 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
985
David Blaikie0c64f5a2018-01-23 01:25:20 +0000986 // Apply module pipeline start EP callback.
987 for (auto &C : PipelineStartEPCallbacks)
988 C(MPM);
989
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000990 // If we are planning to perform ThinLTO later, we don't bloat the code with
991 // unrolling/vectorization/... now. Just simplify the module as much as we
992 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000993 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
994 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000995
996 // Run partial inlining pass to partially inline functions that have
997 // large bodies.
998 // FIXME: It isn't clear whether this is really the right place to run this
999 // in ThinLTO. Because there is another canonicalization and simplification
1000 // phase that will run after the thin link, running this here ends up with
1001 // less information than will be available later and it may grow functions in
1002 // ways that aren't beneficial.
1003 if (RunPartialInlining)
1004 MPM.addPass(PartialInlinerPass());
1005
1006 // Reduce the size of the IR as much as possible.
1007 MPM.addPass(GlobalOptPass());
1008
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001009 return MPM;
1010}
1011
Teresa Johnson28023db2018-07-19 14:51:32 +00001012ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1013 OptimizationLevel Level, bool DebugLogging,
1014 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001015 ModulePassManager MPM(DebugLogging);
1016
Teresa Johnson28023db2018-07-19 14:51:32 +00001017 if (ImportSummary) {
1018 // These passes import type identifier resolutions for whole-program
1019 // devirtualization and CFI. They must run early because other passes may
1020 // disturb the specific instruction patterns that these passes look for,
1021 // creating dependencies on resolutions that may not appear in the summary.
1022 //
1023 // For example, GVN may transform the pattern assume(type.test) appearing in
1024 // two basic blocks into assume(phi(type.test, type.test)), which would
1025 // transform a dependency on a WPD resolution into a dependency on a type
1026 // identifier resolution for CFI.
1027 //
1028 // Also, WPD has access to more precise information than ICP and can
1029 // devirtualize more effectively, so it should operate on the IR first.
1030 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1031 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1032 }
1033
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001034 // Force any function attributes we want the rest of the pipeline to observe.
1035 MPM.addPass(ForceFunctionAttrsPass());
1036
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001037 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001038 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1039 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001040
1041 // Now add the optimization pipeline.
1042 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1043
1044 return MPM;
1045}
1046
1047ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001048PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1049 bool DebugLogging) {
1050 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001051 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001052 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001053 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001054}
1055
Teresa Johnson28023db2018-07-19 14:51:32 +00001056ModulePassManager
1057PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1058 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001059 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1060 ModulePassManager MPM(DebugLogging);
1061
Rong Xudb29a3a2019-03-04 20:21:27 +00001062 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001063 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001064 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001065 PGOOpt->ProfileRemappingFile,
1066 false /* ThinLTOPhase::PreLink */));
1067 }
1068
Davide Italiano089a9122017-01-24 00:57:39 +00001069 // Remove unused virtual tables to improve the quality of code generated by
1070 // whole-program devirtualization and bitset lowering.
1071 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001072
Davide Italiano089a9122017-01-24 00:57:39 +00001073 // Force any function attributes we want the rest of the pipeline to observe.
1074 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001075
Davide Italiano089a9122017-01-24 00:57:39 +00001076 // Do basic inference of function attributes from known properties of system
1077 // libraries and other oracles.
1078 MPM.addPass(InferFunctionAttrsPass());
1079
1080 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001081 FunctionPassManager EarlyFPM(DebugLogging);
1082 EarlyFPM.addPass(CallSiteSplittingPass());
1083 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1084
Davide Italiano089a9122017-01-24 00:57:39 +00001085 // Indirect call promotion. This should promote all the targets that are
1086 // left by the earlier promotion pass that promotes intra-module targets.
1087 // This two-step promotion is to save the compile time. For LTO, it should
1088 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001089 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001090 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001091 // Propagate constants at call sites into the functions they call. This
1092 // opens opportunities for globalopt (and inlining) by substituting function
1093 // pointers passed as arguments to direct uses of functions.
1094 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001095
1096 // Attach metadata to indirect call sites indicating the set of functions
1097 // they may target at run-time. This should follow IPSCCP.
1098 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001099 }
1100
1101 // Now deduce any function attributes based in the current code.
1102 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1103 PostOrderFunctionAttrsPass()));
1104
1105 // Do RPO function attribute inference across the module to forward-propagate
1106 // attributes where applicable.
1107 // FIXME: Is this really an optimization rather than a canonicalization?
1108 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1109
Eric Christopher721eaef2019-02-26 20:33:22 +00001110 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001111 MPM.addPass(GlobalSplitPass());
1112
1113 // Run whole program optimization of virtual call when the list of callees
1114 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001115 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001116
1117 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001118 if (Level == 1) {
1119 // The LowerTypeTestsPass needs to run to lower type metadata and the
1120 // type.test intrinsics. The pass does nothing if CFI is disabled.
1121 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001122 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001123 }
Davide Italiano089a9122017-01-24 00:57:39 +00001124
1125 // Optimize globals to try and fold them into constants.
1126 MPM.addPass(GlobalOptPass());
1127
1128 // Promote any localized globals to SSA registers.
1129 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1130
1131 // Linking modules together can lead to duplicate global constant, only
1132 // keep one copy of each constant.
1133 MPM.addPass(ConstantMergePass());
1134
1135 // Remove unused arguments from functions.
1136 MPM.addPass(DeadArgumentEliminationPass());
1137
1138 // Reduce the code after globalopt and ipsccp. Both can open up significant
1139 // simplification opportunities, and both can propagate functions through
1140 // function pointers. When this happens, we often have to resolve varargs
1141 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001142 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001143 if (Level == O3)
1144 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001145 PeepholeFPM.addPass(InstCombinePass());
1146 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1147
1148 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001149
1150 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1151 // generally clean up exception handling overhead. It isn't clear this is
1152 // valuable as the inliner doesn't currently care whether it is inlining an
1153 // invoke or a call.
1154 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001155 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1156 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001157
1158 // Optimize globals again after we ran the inliner.
1159 MPM.addPass(GlobalOptPass());
1160
1161 // Garbage collect dead functions.
1162 // FIXME: Add ArgumentPromotion pass after once it's ported.
1163 MPM.addPass(GlobalDCEPass());
1164
1165 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001166 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001167 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001168 invokePeepholeEPCallbacks(FPM, Level);
1169
Davide Italiano089a9122017-01-24 00:57:39 +00001170 FPM.addPass(JumpThreadingPass());
1171
Rong Xudb29a3a2019-03-04 20:21:27 +00001172 // Do a post inline PGO instrumentation and use pass. This is a context
1173 // sensitive PGO pass.
1174 if (PGOOpt) {
1175 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1176 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1177 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1178 PGOOpt->ProfileRemappingFile);
1179 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1180 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1181 /* IsCS */ true, PGOOpt->ProfileFile,
1182 PGOOpt->ProfileRemappingFile);
1183 }
1184
Davide Italiano089a9122017-01-24 00:57:39 +00001185 // Break up allocas
1186 FPM.addPass(SROA());
1187
1188 // Run a few AA driver optimizations here and now to cleanup the code.
1189 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1190
1191 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1192 PostOrderFunctionAttrsPass()));
1193 // FIXME: here we run IP alias analysis in the legacy PM.
1194
1195 FunctionPassManager MainFPM;
1196
1197 // FIXME: once we fix LoopPass Manager, add LICM here.
1198 // FIXME: once we provide support for enabling MLSM, add it here.
1199 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001200 if (RunNewGVN)
1201 MainFPM.addPass(NewGVNPass());
1202 else
1203 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001204
1205 // Remove dead memcpy()'s.
1206 MainFPM.addPass(MemCpyOptPass());
1207
1208 // Nuke dead stores.
1209 MainFPM.addPass(DSEPass());
1210
1211 // FIXME: at this point, we run a bunch of loop passes:
1212 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1213 // loopVectorize. Enable them once the remaining issue with LPM
1214 // are sorted out.
1215
1216 MainFPM.addPass(InstCombinePass());
1217 MainFPM.addPass(SimplifyCFGPass());
1218 MainFPM.addPass(SCCPPass());
1219 MainFPM.addPass(InstCombinePass());
1220 MainFPM.addPass(BDCEPass());
1221
1222 // FIXME: We may want to run SLPVectorizer here.
1223 // After vectorization, assume intrinsics may tell us more
1224 // about pointer alignments.
1225#if 0
1226 MainFPM.add(AlignmentFromAssumptionsPass());
1227#endif
1228
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001229 // FIXME: Conditionally run LoadCombine here, after it's ported
1230 // (in case we still have this pass, given its questionable usefulness).
1231
Davide Italiano089a9122017-01-24 00:57:39 +00001232 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001233 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001234 MainFPM.addPass(JumpThreadingPass());
1235 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1236
1237 // Create a function that performs CFI checks for cross-DSO calls with
1238 // targets in the current module.
1239 MPM.addPass(CrossDSOCFIPass());
1240
1241 // Lower type metadata and the type.test intrinsic. This pass supports
1242 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1243 // to be run at link time if CFI is enabled. This pass does nothing if
1244 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001245 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001246
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001247 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1248 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1249 if (EnableHotColdSplit)
1250 MPM.addPass(HotColdSplittingPass());
1251
Davide Italiano089a9122017-01-24 00:57:39 +00001252 // Add late LTO optimization passes.
1253 // Delete basic blocks, which optimization passes may have killed.
1254 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1255
1256 // Drop bodies of available eternally objects to improve GlobalDCE.
1257 MPM.addPass(EliminateAvailableExternallyPass());
1258
1259 // Now that we have optimized the program, discard unreachable functions.
1260 MPM.addPass(GlobalDCEPass());
1261
1262 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001263 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001264}
1265
Chandler Carruth060ad612016-12-23 20:38:19 +00001266AAManager PassBuilder::buildDefaultAAPipeline() {
1267 AAManager AA;
1268
1269 // The order in which these are registered determines their priority when
1270 // being queried.
1271
1272 // First we register the basic alias analysis that provides the majority of
1273 // per-function local AA logic. This is a stateless, on-demand local set of
1274 // AA techniques.
1275 AA.registerFunctionAnalysis<BasicAA>();
1276
1277 // Next we query fast, specialized alias analyses that wrap IR-embedded
1278 // information about aliasing.
1279 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1280 AA.registerFunctionAnalysis<TypeBasedAA>();
1281
1282 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001283 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1284 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001285 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001286 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001287
1288 return AA;
1289}
1290
Chandler Carruth241bf242016-08-03 07:44:48 +00001291static Optional<int> parseRepeatPassName(StringRef Name) {
1292 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1293 return None;
1294 int Count;
1295 if (Name.getAsInteger(0, Count) || Count <= 0)
1296 return None;
1297 return Count;
1298}
1299
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001300static Optional<int> parseDevirtPassName(StringRef Name) {
1301 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1302 return None;
1303 int Count;
1304 if (Name.getAsInteger(0, Count) || Count <= 0)
1305 return None;
1306 return Count;
1307}
1308
Fedor Sergeevb7871402019-01-10 10:01:53 +00001309static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1310 if (!Name.consume_front(PassName))
1311 return false;
1312 // normal pass name w/o parameters == default parameters
1313 if (Name.empty())
1314 return true;
1315 return Name.startswith("<") && Name.endswith(">");
1316}
1317
1318namespace {
1319
1320/// This performs customized parsing of pass name with parameters.
1321///
1322/// We do not need parametrization of passes in textual pipeline very often,
1323/// yet on a rare occasion ability to specify parameters right there can be
1324/// useful.
1325///
1326/// \p Name - parameterized specification of a pass from a textual pipeline
1327/// is a string in a form of :
1328/// PassName '<' parameter-list '>'
1329///
1330/// Parameter list is being parsed by the parser callable argument, \p Parser,
1331/// It takes a string-ref of parameters and returns either StringError or a
1332/// parameter list in a form of a custom parameters type, all wrapped into
1333/// Expected<> template class.
1334///
1335template <typename ParametersParseCallableT>
1336auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1337 StringRef PassName) -> decltype(Parser(StringRef{})) {
1338 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1339
1340 StringRef Params = Name;
1341 if (!Params.consume_front(PassName)) {
1342 assert(false &&
1343 "unable to strip pass name from parametrized pass specification");
1344 }
1345 if (Params.empty())
1346 return ParametersT{};
1347 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1348 assert(false && "invalid format for parametrized pass name");
1349 }
1350
1351 Expected<ParametersT> Result = Parser(Params);
1352 assert((Result || Result.template errorIsA<StringError>()) &&
1353 "Pass parameter parser can only return StringErrors.");
1354 return std::move(Result);
1355}
1356
1357/// Parser of parameters for LoopUnroll pass.
1358Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1359 LoopUnrollOptions UnrollOpts;
1360 while (!Params.empty()) {
1361 StringRef ParamName;
1362 std::tie(ParamName, Params) = Params.split(';');
1363 int OptLevel = StringSwitch<int>(ParamName)
1364 .Case("O0", 0)
1365 .Case("O1", 1)
1366 .Case("O2", 2)
1367 .Case("O3", 3)
1368 .Default(-1);
1369 if (OptLevel >= 0) {
1370 UnrollOpts.setOptLevel(OptLevel);
1371 continue;
1372 }
1373
1374 bool Enable = !ParamName.consume_front("no-");
1375 if (ParamName == "partial") {
1376 UnrollOpts.setPartial(Enable);
1377 } else if (ParamName == "peeling") {
1378 UnrollOpts.setPeeling(Enable);
1379 } else if (ParamName == "runtime") {
1380 UnrollOpts.setRuntime(Enable);
1381 } else if (ParamName == "upperbound") {
1382 UnrollOpts.setUpperBound(Enable);
1383 } else {
1384 return make_error<StringError>(
1385 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1386 inconvertibleErrorCode());
1387 }
1388 }
1389 return UnrollOpts;
1390}
1391
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001392Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1393 MemorySanitizerOptions Result;
1394 while (!Params.empty()) {
1395 StringRef ParamName;
1396 std::tie(ParamName, Params) = Params.split(';');
1397
1398 if (ParamName == "recover") {
1399 Result.Recover = true;
1400 } else if (ParamName == "kernel") {
1401 Result.Kernel = true;
1402 } else if (ParamName.consume_front("track-origins=")) {
1403 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1404 return make_error<StringError>(
1405 formatv("invalid argument to MemorySanitizer pass track-origins "
1406 "parameter: '{0}' ",
1407 ParamName)
1408 .str(),
1409 inconvertibleErrorCode());
1410 } else {
1411 return make_error<StringError>(
1412 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1413 .str(),
1414 inconvertibleErrorCode());
1415 }
1416 }
1417 return Result;
1418}
1419
Fedor Sergeevb7871402019-01-10 10:01:53 +00001420} // namespace
1421
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001422/// Tests whether a pass name starts with a valid prefix for a default pipeline
1423/// alias.
1424static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1425 return Name.startswith("default") || Name.startswith("thinlto") ||
1426 Name.startswith("lto");
1427}
1428
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001429/// Tests whether registered callbacks will accept a given pass name.
1430///
1431/// When parsing a pipeline text, the type of the outermost pipeline may be
1432/// omitted, in which case the type is automatically determined from the first
1433/// pass name in the text. This may be a name that is handled through one of the
1434/// callbacks. We check this through the oridinary parsing callbacks by setting
1435/// up a dummy PassManager in order to not force the client to also handle this
1436/// type of query.
1437template <typename PassManagerT, typename CallbacksT>
1438static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1439 if (!Callbacks.empty()) {
1440 PassManagerT DummyPM;
1441 for (auto &CB : Callbacks)
1442 if (CB(Name, DummyPM, {}))
1443 return true;
1444 }
1445 return false;
1446}
1447
1448template <typename CallbacksT>
1449static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001450 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001451 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001452 return DefaultAliasRegex.match(Name);
1453
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001454 // Explicitly handle pass manager names.
1455 if (Name == "module")
1456 return true;
1457 if (Name == "cgscc")
1458 return true;
1459 if (Name == "function")
1460 return true;
1461
Chandler Carruth241bf242016-08-03 07:44:48 +00001462 // Explicitly handle custom-parsed pass names.
1463 if (parseRepeatPassName(Name))
1464 return true;
1465
Chandler Carruth74a8a222016-06-17 07:15:29 +00001466#define MODULE_PASS(NAME, CREATE_PASS) \
1467 if (Name == NAME) \
1468 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001469#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001470 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001471 return true;
1472#include "PassRegistry.def"
1473
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001474 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001475}
1476
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001477template <typename CallbacksT>
1478static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001479 // Explicitly handle pass manager names.
1480 if (Name == "cgscc")
1481 return true;
1482 if (Name == "function")
1483 return true;
1484
Chandler Carruth241bf242016-08-03 07:44:48 +00001485 // Explicitly handle custom-parsed pass names.
1486 if (parseRepeatPassName(Name))
1487 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001488 if (parseDevirtPassName(Name))
1489 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001490
Chandler Carruth74a8a222016-06-17 07:15:29 +00001491#define CGSCC_PASS(NAME, CREATE_PASS) \
1492 if (Name == NAME) \
1493 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001494#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001495 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001496 return true;
1497#include "PassRegistry.def"
1498
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001499 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001500}
1501
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001502template <typename CallbacksT>
1503static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001504 // Explicitly handle pass manager names.
1505 if (Name == "function")
1506 return true;
1507 if (Name == "loop")
1508 return true;
1509
Chandler Carruth241bf242016-08-03 07:44:48 +00001510 // Explicitly handle custom-parsed pass names.
1511 if (parseRepeatPassName(Name))
1512 return true;
1513
Chandler Carruth74a8a222016-06-17 07:15:29 +00001514#define FUNCTION_PASS(NAME, CREATE_PASS) \
1515 if (Name == NAME) \
1516 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001517#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1518 if (checkParametrizedPassName(Name, NAME)) \
1519 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001520#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001521 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001522 return true;
1523#include "PassRegistry.def"
1524
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001525 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001526}
1527
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001528template <typename CallbacksT>
1529static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001530 // Explicitly handle pass manager names.
1531 if (Name == "loop")
1532 return true;
1533
Chandler Carruth241bf242016-08-03 07:44:48 +00001534 // Explicitly handle custom-parsed pass names.
1535 if (parseRepeatPassName(Name))
1536 return true;
1537
Chandler Carruth74a8a222016-06-17 07:15:29 +00001538#define LOOP_PASS(NAME, CREATE_PASS) \
1539 if (Name == NAME) \
1540 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001541#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1542 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1543 return true;
1544#include "PassRegistry.def"
1545
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001546 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001547}
1548
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001549Optional<std::vector<PassBuilder::PipelineElement>>
1550PassBuilder::parsePipelineText(StringRef Text) {
1551 std::vector<PipelineElement> ResultPipeline;
1552
1553 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1554 &ResultPipeline};
1555 for (;;) {
1556 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1557 size_t Pos = Text.find_first_of(",()");
1558 Pipeline.push_back({Text.substr(0, Pos), {}});
1559
1560 // If we have a single terminating name, we're done.
1561 if (Pos == Text.npos)
1562 break;
1563
1564 char Sep = Text[Pos];
1565 Text = Text.substr(Pos + 1);
1566 if (Sep == ',')
1567 // Just a name ending in a comma, continue.
1568 continue;
1569
1570 if (Sep == '(') {
1571 // Push the inner pipeline onto the stack to continue processing.
1572 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1573 continue;
1574 }
1575
1576 assert(Sep == ')' && "Bogus separator!");
1577 // When handling the close parenthesis, we greedily consume them to avoid
1578 // empty strings in the pipeline.
1579 do {
1580 // If we try to pop the outer pipeline we have unbalanced parentheses.
1581 if (PipelineStack.size() == 1)
1582 return None;
1583
1584 PipelineStack.pop_back();
1585 } while (Text.consume_front(")"));
1586
1587 // Check if we've finished parsing.
1588 if (Text.empty())
1589 break;
1590
1591 // Otherwise, the end of an inner pipeline always has to be followed by
1592 // a comma, and then we can continue.
1593 if (!Text.consume_front(","))
1594 return None;
1595 }
1596
1597 if (PipelineStack.size() > 1)
1598 // Unbalanced paretheses.
1599 return None;
1600
1601 assert(PipelineStack.back() == &ResultPipeline &&
1602 "Wrong pipeline at the bottom of the stack!");
1603 return {std::move(ResultPipeline)};
1604}
1605
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001606Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1607 const PipelineElement &E,
1608 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001609 auto &Name = E.Name;
1610 auto &InnerPipeline = E.InnerPipeline;
1611
1612 // First handle complex passes like the pass managers which carry pipelines.
1613 if (!InnerPipeline.empty()) {
1614 if (Name == "module") {
1615 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001616 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1617 VerifyEachPass, DebugLogging))
1618 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001619 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001620 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001621 }
1622 if (Name == "cgscc") {
1623 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001624 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1625 DebugLogging))
1626 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001627 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001628 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001629 }
1630 if (Name == "function") {
1631 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001632 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1633 VerifyEachPass, DebugLogging))
1634 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001635 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001636 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001637 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001638 if (auto Count = parseRepeatPassName(Name)) {
1639 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001640 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1641 VerifyEachPass, DebugLogging))
1642 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001643 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001644 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001645 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001646
1647 for (auto &C : ModulePipelineParsingCallbacks)
1648 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001649 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001650
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001651 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001652 return make_error<StringError>(
1653 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1654 inconvertibleErrorCode());
1655 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001656 }
1657
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001658 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001659 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001660 SmallVector<StringRef, 3> Matches;
1661 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001662 return make_error<StringError>(
1663 formatv("unknown default pipeline alias '{0}'", Name).str(),
1664 inconvertibleErrorCode());
1665
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001666 assert(Matches.size() == 3 && "Must capture two matched strings!");
1667
Jordan Rosef85a95f2016-07-25 18:34:51 +00001668 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001669 .Case("O0", O0)
1670 .Case("O1", O1)
1671 .Case("O2", O2)
1672 .Case("O3", O3)
1673 .Case("Os", Os)
1674 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001675 if (L == O0)
1676 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001677 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001678
1679 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001680 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001681 } else if (Matches[1] == "thinlto-pre-link") {
1682 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1683 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001684 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001685 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001686 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001687 } else {
1688 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001689 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001690 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001691 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001692 }
1693
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001694 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001695#define MODULE_PASS(NAME, CREATE_PASS) \
1696 if (Name == NAME) { \
1697 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001698 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001699 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001700#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1701 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001702 MPM.addPass( \
1703 RequireAnalysisPass< \
1704 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001705 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001706 } \
1707 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001708 MPM.addPass(InvalidateAnalysisPass< \
1709 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001710 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001711 }
1712#include "PassRegistry.def"
1713
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001714 for (auto &C : ModulePipelineParsingCallbacks)
1715 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001716 return Error::success();
1717 return make_error<StringError>(
1718 formatv("unknown module pass '{0}'", Name).str(),
1719 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001720}
1721
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001722Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1723 const PipelineElement &E, bool VerifyEachPass,
1724 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001725 auto &Name = E.Name;
1726 auto &InnerPipeline = E.InnerPipeline;
1727
1728 // First handle complex passes like the pass managers which carry pipelines.
1729 if (!InnerPipeline.empty()) {
1730 if (Name == "cgscc") {
1731 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001732 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1733 VerifyEachPass, DebugLogging))
1734 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001735 // Add the nested pass manager with the appropriate adaptor.
1736 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001737 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001738 }
1739 if (Name == "function") {
1740 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001741 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1742 VerifyEachPass, DebugLogging))
1743 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001744 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001745 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001746 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001747 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001748 if (auto Count = parseRepeatPassName(Name)) {
1749 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001750 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1751 VerifyEachPass, DebugLogging))
1752 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001753 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001754 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001755 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001756 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1757 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001758 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1759 VerifyEachPass, DebugLogging))
1760 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001761 CGPM.addPass(
1762 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001763 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001764 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001765
1766 for (auto &C : CGSCCPipelineParsingCallbacks)
1767 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001768 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001769
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001770 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001771 return make_error<StringError>(
1772 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1773 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001774 }
1775
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001776// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001777#define CGSCC_PASS(NAME, CREATE_PASS) \
1778 if (Name == NAME) { \
1779 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001780 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001781 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001782#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1783 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001784 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001785 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001786 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1787 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001788 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001789 } \
1790 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001791 CGPM.addPass(InvalidateAnalysisPass< \
1792 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001793 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001794 }
1795#include "PassRegistry.def"
1796
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001797 for (auto &C : CGSCCPipelineParsingCallbacks)
1798 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001799 return Error::success();
1800 return make_error<StringError>(
1801 formatv("unknown cgscc pass '{0}'", Name).str(),
1802 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001803}
1804
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001805Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1806 const PipelineElement &E,
1807 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001808 auto &Name = E.Name;
1809 auto &InnerPipeline = E.InnerPipeline;
1810
1811 // First handle complex passes like the pass managers which carry pipelines.
1812 if (!InnerPipeline.empty()) {
1813 if (Name == "function") {
1814 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001815 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1816 VerifyEachPass, DebugLogging))
1817 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001818 // Add the nested pass manager with the appropriate adaptor.
1819 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001820 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001821 }
1822 if (Name == "loop") {
1823 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001824 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1825 DebugLogging))
1826 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001827 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001828 FPM.addPass(
1829 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001830 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001831 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001832 if (auto Count = parseRepeatPassName(Name)) {
1833 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001834 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1835 VerifyEachPass, DebugLogging))
1836 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001837 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001838 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001839 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001840
1841 for (auto &C : FunctionPipelineParsingCallbacks)
1842 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001843 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001844
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001845 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001846 return make_error<StringError>(
1847 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1848 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001849 }
1850
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001851// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001852#define FUNCTION_PASS(NAME, CREATE_PASS) \
1853 if (Name == NAME) { \
1854 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001855 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001856 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001857#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1858 if (checkParametrizedPassName(Name, NAME)) { \
1859 auto Params = parsePassParameters(PARSER, Name, NAME); \
1860 if (!Params) \
1861 return Params.takeError(); \
1862 FPM.addPass(CREATE_PASS(Params.get())); \
1863 return Error::success(); \
1864 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001865#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1866 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001867 FPM.addPass( \
1868 RequireAnalysisPass< \
1869 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001870 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001871 } \
1872 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001873 FPM.addPass(InvalidateAnalysisPass< \
1874 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001875 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001876 }
1877#include "PassRegistry.def"
1878
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001879 for (auto &C : FunctionPipelineParsingCallbacks)
1880 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001881 return Error::success();
1882 return make_error<StringError>(
1883 formatv("unknown function pass '{0}'", Name).str(),
1884 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001885}
1886
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001887Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1888 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001889 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001890 auto &InnerPipeline = E.InnerPipeline;
1891
1892 // First handle complex passes like the pass managers which carry pipelines.
1893 if (!InnerPipeline.empty()) {
1894 if (Name == "loop") {
1895 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001896 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1897 VerifyEachPass, DebugLogging))
1898 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001899 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001900 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001901 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001902 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001903 if (auto Count = parseRepeatPassName(Name)) {
1904 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001905 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1906 VerifyEachPass, DebugLogging))
1907 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001908 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001909 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001910 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001911
1912 for (auto &C : LoopPipelineParsingCallbacks)
1913 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001914 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001915
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001916 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001917 return make_error<StringError>(
1918 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1919 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001920 }
1921
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001922// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001923#define LOOP_PASS(NAME, CREATE_PASS) \
1924 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001925 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001926 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001927 }
1928#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1929 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001930 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001931 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1932 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1933 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001934 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001935 } \
1936 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001937 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001938 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001939 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001940 }
1941#include "PassRegistry.def"
1942
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001943 for (auto &C : LoopPipelineParsingCallbacks)
1944 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001945 return Error::success();
1946 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1947 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001948}
1949
Chandler Carruthedf59962016-02-18 09:45:17 +00001950bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001951#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1952 if (Name == NAME) { \
1953 AA.registerModuleAnalysis< \
1954 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1955 return true; \
1956 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001957#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1958 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001959 AA.registerFunctionAnalysis< \
1960 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001961 return true; \
1962 }
1963#include "PassRegistry.def"
1964
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001965 for (auto &C : AAParsingCallbacks)
1966 if (C(Name, AA))
1967 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001968 return false;
1969}
1970
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001971Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001972 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001973 bool VerifyEachPass,
1974 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001975 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001976 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1977 return Err;
1978 // FIXME: No verifier support for Loop passes!
1979 }
1980 return Error::success();
1981}
1982
1983Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1984 ArrayRef<PipelineElement> Pipeline,
1985 bool VerifyEachPass,
1986 bool DebugLogging) {
1987 for (const auto &Element : Pipeline) {
1988 if (auto Err =
1989 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1990 return Err;
1991 if (VerifyEachPass)
1992 FPM.addPass(VerifierPass());
1993 }
1994 return Error::success();
1995}
1996
1997Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1998 ArrayRef<PipelineElement> Pipeline,
1999 bool VerifyEachPass,
2000 bool DebugLogging) {
2001 for (const auto &Element : Pipeline) {
2002 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2003 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002004 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002005 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002006 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002007}
2008
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002009void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2010 FunctionAnalysisManager &FAM,
2011 CGSCCAnalysisManager &CGAM,
2012 ModuleAnalysisManager &MAM) {
2013 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2014 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002015 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2016 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2017 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2018 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2019 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2020}
2021
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002022Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2023 ArrayRef<PipelineElement> Pipeline,
2024 bool VerifyEachPass,
2025 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002026 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002027 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2028 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002029 if (VerifyEachPass)
2030 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002031 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002032 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002033}
2034
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002035// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002036// FIXME: Should this routine accept a TargetMachine or require the caller to
2037// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002038Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2039 StringRef PipelineText,
2040 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002041 auto Pipeline = parsePipelineText(PipelineText);
2042 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002043 return make_error<StringError>(
2044 formatv("invalid pipeline '{0}'", PipelineText).str(),
2045 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002046
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002047 // If the first name isn't at the module layer, wrap the pipeline up
2048 // automatically.
2049 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002050
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002051 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2052 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002053 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002054 } else if (isFunctionPassName(FirstName,
2055 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002056 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002057 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002058 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002059 } else {
2060 for (auto &C : TopLevelPipelineParsingCallbacks)
2061 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002062 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002063
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002064 // Unknown pass or pipeline name!
2065 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2066 return make_error<StringError>(
2067 formatv("unknown {0} name '{1}'",
2068 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2069 .str(),
2070 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002071 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002072 }
2073
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002074 if (auto Err =
2075 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2076 return Err;
2077 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002078}
Chandler Carruthedf59962016-02-18 09:45:17 +00002079
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002080// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002081Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2082 StringRef PipelineText,
2083 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002084 auto Pipeline = parsePipelineText(PipelineText);
2085 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002086 return make_error<StringError>(
2087 formatv("invalid pipeline '{0}'", PipelineText).str(),
2088 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002089
2090 StringRef FirstName = Pipeline->front().Name;
2091 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002092 return make_error<StringError>(
2093 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2094 PipelineText)
2095 .str(),
2096 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002097
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002098 if (auto Err =
2099 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2100 return Err;
2101 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002102}
2103
2104// Primary pass pipeline description parsing routine for a \c
2105// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002106Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2107 StringRef PipelineText,
2108 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002109 auto Pipeline = parsePipelineText(PipelineText);
2110 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002111 return make_error<StringError>(
2112 formatv("invalid pipeline '{0}'", PipelineText).str(),
2113 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002114
2115 StringRef FirstName = Pipeline->front().Name;
2116 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002117 return make_error<StringError>(
2118 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2119 PipelineText)
2120 .str(),
2121 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002122
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002123 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2124 DebugLogging))
2125 return Err;
2126 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002127}
2128
2129// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002130Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2131 StringRef PipelineText,
2132 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002133 auto Pipeline = parsePipelineText(PipelineText);
2134 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002135 return make_error<StringError>(
2136 formatv("invalid pipeline '{0}'", PipelineText).str(),
2137 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002138
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002139 if (auto Err =
2140 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2141 return Err;
2142
2143 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002144}
2145
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002146Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002147 // If the pipeline just consists of the word 'default' just replace the AA
2148 // manager with our default one.
2149 if (PipelineText == "default") {
2150 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002151 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002152 }
2153
Chandler Carruthedf59962016-02-18 09:45:17 +00002154 while (!PipelineText.empty()) {
2155 StringRef Name;
2156 std::tie(Name, PipelineText) = PipelineText.split(',');
2157 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002158 return make_error<StringError>(
2159 formatv("unknown alias analysis name '{0}'", Name).str(),
2160 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002161 }
2162
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002163 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002164}