blob: cfc436183eb38c93e82c478d780ff1455ecc5d08 [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"
96#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000097#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +000098#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000099#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000100#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000101#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000102#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000103#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000104#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000105#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000106#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000107#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000108#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000109#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000110#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000111#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000112#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000113#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000114#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000115#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000116#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000117#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000118#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000119#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000120#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000121#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000122#include "llvm/Transforms/Scalar/LoopDistribute.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000123#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000124#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000125#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000126#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000127#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000128#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000129#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000130#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000131#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000132#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000133#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000134#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000135#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000136#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000137#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000138#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000139#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000140#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000141#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000142#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000143#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000144#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000145#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000146#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000147#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000148#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000149#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000150#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000151#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000152#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000153#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000154#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000155#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000156#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000157#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000158#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000159#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000160#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000161#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000162#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000163#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000164#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000165#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000166#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000167#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000168#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000169#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000170
Chandler Carruth66445382014-01-11 08:16:35 +0000171using namespace llvm;
172
Chandler Carruth719ffe12017-02-12 05:38:04 +0000173static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
174 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000175static cl::opt<bool>
176 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
177 cl::Hidden, cl::ZeroOrMore,
178 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000179
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000180static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000181 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000182 cl::Hidden, cl::ZeroOrMore,
183 cl::desc("Run NewGVN instead of GVN"));
184
Geoff Berry3cca1da2017-06-10 15:20:03 +0000185static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000186 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
187 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000188
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000189static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000190 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
191 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000192
Davide Italianobe1b6a92017-06-03 23:18:29 +0000193static cl::opt<bool> EnableGVNSink(
194 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
195 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
196
David Green963401d2018-07-01 12:47:30 +0000197static cl::opt<bool> EnableUnrollAndJam(
198 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
199 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
200
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000201static cl::opt<bool> EnableSyntheticCounts(
202 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
203 cl::desc("Run synthetic function entry count generation "
204 "pass"));
205
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000206static Regex DefaultAliasRegex(
207 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000208
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000209static cl::opt<bool>
210 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
211 cl::desc("Enable control height reduction optimization (CHR)"));
212
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000213extern cl::opt<bool> EnableHotColdSplit;
214
Wei Mi3bcccdf2019-01-17 20:48:34 +0000215extern cl::opt<bool> FlattenedProfileUsed;
216
Chandler Carruthe3f50642016-12-22 06:59:15 +0000217static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
218 switch (Level) {
219 case PassBuilder::O0:
220 case PassBuilder::O1:
221 case PassBuilder::O2:
222 case PassBuilder::O3:
223 return false;
224
225 case PassBuilder::Os:
226 case PassBuilder::Oz:
227 return true;
228 }
229 llvm_unreachable("Invalid optimization level!");
230}
231
Chandler Carruth66445382014-01-11 08:16:35 +0000232namespace {
233
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000234/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000235struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000236 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000237 return PreservedAnalyses::all();
238 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000239 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000240};
241
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000242/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000243class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
244 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000245 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000246
247public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000248 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000249 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000250 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000251};
252
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000253/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000254struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000255 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
256 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000257 return PreservedAnalyses::all();
258 }
259 static StringRef name() { return "NoOpCGSCCPass"; }
260};
261
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000262/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000263class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
264 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000265 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000266
267public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000268 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000269 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000270 return Result();
271 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000272 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000273};
274
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000275/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000276struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000277 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000278 return PreservedAnalyses::all();
279 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000280 static StringRef name() { return "NoOpFunctionPass"; }
281};
282
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000283/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000284class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
285 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000286 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000287
288public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000289 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000290 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000291 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000292};
293
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000294/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000295struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000296 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
297 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000298 return PreservedAnalyses::all();
299 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000300 static StringRef name() { return "NoOpLoopPass"; }
301};
302
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000303/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000304class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
305 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000306 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000307
308public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000309 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000310 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
311 return Result();
312 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000313 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000314};
315
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000316AnalysisKey NoOpModuleAnalysis::Key;
317AnalysisKey NoOpCGSCCAnalysis::Key;
318AnalysisKey NoOpFunctionAnalysis::Key;
319AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000320
Chandler Carruth66445382014-01-11 08:16:35 +0000321} // End anonymous namespace.
322
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000323void PassBuilder::invokePeepholeEPCallbacks(
324 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
325 for (auto &C : PeepholeEPCallbacks)
326 C(FPM, Level);
327}
328
Chandler Carruth1ff77242015-03-07 09:02:36 +0000329void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000330#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000331 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000332#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000333
334 for (auto &C : ModuleAnalysisRegistrationCallbacks)
335 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000336}
337
Chandler Carruth1ff77242015-03-07 09:02:36 +0000338void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000339#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000340 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000341#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000342
343 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
344 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000345}
346
Chandler Carruth1ff77242015-03-07 09:02:36 +0000347void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000348#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000349 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000350#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000351
352 for (auto &C : FunctionAnalysisRegistrationCallbacks)
353 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000354}
355
Justin Bognereecc3c82016-02-25 07:23:08 +0000356void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000357#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000358 LAM.registerPass([&] { return CREATE_PASS; });
359#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000360
361 for (auto &C : LoopAnalysisRegistrationCallbacks)
362 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000363}
364
Chandler Carruthe3f50642016-12-22 06:59:15 +0000365FunctionPassManager
366PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000367 ThinLTOPhase Phase,
368 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000369 assert(Level != O0 && "Must request optimizations!");
370 FunctionPassManager FPM(DebugLogging);
371
372 // Form SSA out of local memory accesses after breaking apart aggregates into
373 // scalars.
374 FPM.addPass(SROA());
375
376 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000377 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000378
Davide Italianoc3688312017-06-01 23:08:14 +0000379 // Hoisting of scalars and load expressions.
380 if (EnableGVNHoist)
381 FPM.addPass(GVNHoistPass());
382
Davide Italianobe1b6a92017-06-03 23:18:29 +0000383 // Global value numbering based sinking.
384 if (EnableGVNSink) {
385 FPM.addPass(GVNSinkPass());
386 FPM.addPass(SimplifyCFGPass());
387 }
388
Chandler Carruthe3f50642016-12-22 06:59:15 +0000389 // Speculative execution if the target has divergent branches; otherwise nop.
390 FPM.addPass(SpeculativeExecutionPass());
391
392 // Optimize based on known information about branches, and cleanup afterward.
393 FPM.addPass(JumpThreadingPass());
394 FPM.addPass(CorrelatedValuePropagationPass());
395 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000396 if (Level == O3)
397 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000398 FPM.addPass(InstCombinePass());
399
400 if (!isOptimizingForSize(Level))
401 FPM.addPass(LibCallsShrinkWrapPass());
402
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000403 invokePeepholeEPCallbacks(FPM, Level);
404
Rong Xue1f42452017-10-23 22:21:29 +0000405 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
406 // using the size value profile. Don't perform this when optimizing for size.
407 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
408 !isOptimizingForSize(Level))
409 FPM.addPass(PGOMemOPSizeOpt());
410
Chandler Carruthe3f50642016-12-22 06:59:15 +0000411 FPM.addPass(TailCallElimPass());
412 FPM.addPass(SimplifyCFGPass());
413
414 // Form canonically associated expression trees, and simplify the trees using
415 // basic mathematical properties. For example, this will form (nearly)
416 // minimal multiplication trees.
417 FPM.addPass(ReassociatePass());
418
419 // Add the primary loop simplification pipeline.
420 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000421 // some function passes in between them. These can and should be removed
422 // and/or replaced by scheduling the loop pass equivalents in the correct
423 // positions. But those equivalent passes aren't powerful enough yet.
424 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
425 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
426 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
427 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000428 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
429
Chandler Carruth71fd2702018-05-30 02:46:45 +0000430 // Simplify the loop body. We do this initially to clean up after other loop
431 // passes run, either when iterating on a loop or on inner loops with
432 // implications on the outer loop.
433 LPM1.addPass(LoopInstSimplifyPass());
434 LPM1.addPass(LoopSimplifyCFGPass());
435
Chandler Carruthe3f50642016-12-22 06:59:15 +0000436 // Rotate Loop - disable header duplication at -Oz
437 LPM1.addPass(LoopRotatePass(Level != Oz));
438 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000439 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000440 LPM2.addPass(IndVarSimplifyPass());
441 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000442
443 for (auto &C : LateLoopOptimizationsEPCallbacks)
444 C(LPM2, Level);
445
Chandler Carruth79b733b2017-01-26 23:21:17 +0000446 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000447 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000448 // because it changes IR to makes profile annotation in back compile
449 // inaccurate.
Dehao Chen95f00302017-07-30 04:55:39 +0000450 if (Phase != ThinLTOPhase::PreLink ||
451 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnsonecd90132017-08-02 20:35:29 +0000452 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000453
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000454 for (auto &C : LoopOptimizerEndEPCallbacks)
455 C(LPM2, Level);
456
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000457 // We provide the opt remark emitter pass for LICM to use. We only need to do
458 // this once as it is immutable.
459 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000460 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000461 FPM.addPass(SimplifyCFGPass());
462 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000463 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000464
465 // Eliminate redundancies.
466 if (Level != O1) {
467 // These passes add substantial compile time so skip them at O1.
468 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000469 if (RunNewGVN)
470 FPM.addPass(NewGVNPass());
471 else
472 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000473 }
474
475 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
476 FPM.addPass(MemCpyOptPass());
477
478 // Sparse conditional constant propagation.
479 // FIXME: It isn't clear why we do this *after* loop passes rather than
480 // before...
481 FPM.addPass(SCCPPass());
482
483 // Delete dead bit computations (instcombine runs after to fold away the dead
484 // computations, and then ADCE will run later to exploit any new DCE
485 // opportunities that creates).
486 FPM.addPass(BDCEPass());
487
488 // Run instcombine after redundancy and dead bit elimination to exploit
489 // opportunities opened up by them.
490 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000491 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000492
493 // Re-consider control flow based optimizations after redundancy elimination,
494 // redo DCE, etc.
495 FPM.addPass(JumpThreadingPass());
496 FPM.addPass(CorrelatedValuePropagationPass());
497 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000498 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000499
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000500 for (auto &C : ScalarOptimizerLateEPCallbacks)
501 C(FPM, Level);
502
Chandler Carruthe3f50642016-12-22 06:59:15 +0000503 // Finally, do an expensive DCE pass to catch all the dead code exposed by
504 // the simplifications and basic cleanup after all the simplifications.
505 FPM.addPass(ADCEPass());
506 FPM.addPass(SimplifyCFGPass());
507 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000508 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000509
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000510 if (EnableCHR && Level == O3 && PGOOpt &&
511 (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty()))
512 FPM.addPass(ControlHeightReductionPass());
513
Chandler Carruthe3f50642016-12-22 06:59:15 +0000514 return FPM;
515}
516
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000517void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
518 PassBuilder::OptimizationLevel Level,
519 bool RunProfileGen,
520 std::string ProfileGenFile,
Richard Smith6c676622018-10-10 23:13:47 +0000521 std::string ProfileUseFile,
522 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000523 // Generally running simplification passes and the inliner with an high
524 // threshold results in smaller executables, but there may be cases where
525 // the size grows, so let's be conservative here and skip this simplification
526 // at -Os/Oz.
527 if (!isOptimizingForSize(Level)) {
528 InlineParams IP;
529
530 // In the old pass manager, this is a cl::opt. Should still this be one?
531 IP.DefaultThreshold = 75;
532
533 // FIXME: The hint threshold has the same value used by the regular inliner.
534 // This should probably be lowered after performance testing.
535 // FIXME: this comment is cargo culted from the old pass manager, revisit).
536 IP.HintThreshold = 325;
537
538 CGSCCPassManager CGPipeline(DebugLogging);
539
540 CGPipeline.addPass(InlinerPass(IP));
541
542 FunctionPassManager FPM;
543 FPM.addPass(SROA());
544 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
545 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
546 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000547 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000548
Davide Italiano513dfaa2017-02-13 15:26:22 +0000549 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
550
551 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
552 }
553
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000554 // Delete anything that is now dead to make sure that we don't instrument
555 // dead code. Instrumentation can end up keeping dead code around and
556 // dramatically increase code size.
557 MPM.addPass(GlobalDCEPass());
558
Davide Italiano513dfaa2017-02-13 15:26:22 +0000559 if (RunProfileGen) {
560 MPM.addPass(PGOInstrumentationGen());
561
Xinliang David Lib67530e2017-06-25 00:26:43 +0000562 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000563 FPM.addPass(
564 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000565 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
566
Davide Italiano513dfaa2017-02-13 15:26:22 +0000567 // Add the profile lowering pass.
568 InstrProfOptions Options;
569 if (!ProfileGenFile.empty())
570 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000571 Options.DoCounterPromotion = true;
Rong Xu6cdf3d82019-02-27 17:24:33 +0000572 Options.UseBFIInPromotion = false;
573 MPM.addPass(InstrProfiling(Options, false));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000574 }
575
576 if (!ProfileUseFile.empty())
Richard Smith6c676622018-10-10 23:13:47 +0000577 MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000578}
579
Easwaran Raman8249fac2017-06-28 13:33:49 +0000580static InlineParams
581getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
582 auto O3 = PassBuilder::O3;
583 unsigned OptLevel = Level > O3 ? 2 : Level;
584 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
585 return getInlineParams(OptLevel, SizeLevel);
586}
587
Chandler Carruthe3f50642016-12-22 06:59:15 +0000588ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000589PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000590 ThinLTOPhase Phase,
591 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000592 ModulePassManager MPM(DebugLogging);
593
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000594 bool HasSampleProfile = PGOOpt && !PGOOpt->SampleProfileFile.empty();
595
596 // In ThinLTO mode, when flattened profile is used, all the available
597 // profile information will be annotated in PreLink phase so there is
598 // no need to load the profile again in PostLink.
599 bool LoadSampleProfile =
600 HasSampleProfile &&
601 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
602
603 // During the ThinLTO backend phase we perform early indirect call promotion
604 // here, before globalopt. Otherwise imported available_externally functions
605 // look unreferenced and are removed. If we are going to load the sample
606 // profile then defer until later.
607 // TODO: See if we can move later and consolidate with the location where
608 // we perform ICP when we are loading a sample profile.
609 // TODO: We pass HasSampleProfile (whether there was a sample profile file
610 // passed to the compile) to the SamplePGO flag of ICP. This is used to
611 // determine whether the new direct calls are annotated with prof metadata.
612 // Ideally this should be determined from whether the IR is annotated with
613 // sample profile, and not whether the a sample profile was provided on the
614 // command line. E.g. for flattened profiles where we will not be reloading
615 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
616 // provide the sample profile file.
617 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
618 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
619
Chandler Carruthe3f50642016-12-22 06:59:15 +0000620 // Do basic inference of function attributes from known properties of system
621 // libraries and other oracles.
622 MPM.addPass(InferFunctionAttrsPass());
623
624 // Create an early function pass manager to cleanup the output of the
625 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000626 FunctionPassManager EarlyFPM(DebugLogging);
627 EarlyFPM.addPass(SimplifyCFGPass());
628 EarlyFPM.addPass(SROA());
629 EarlyFPM.addPass(EarlyCSEPass());
630 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000631 if (Level == O3)
632 EarlyFPM.addPass(CallSiteSplittingPass());
633
Dehao Chen08f88312017-08-07 20:23:20 +0000634 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
635 // to convert bitcast to direct calls so that they can be inlined during the
636 // profile annotation prepration step.
637 // More details about SamplePGO design can be found in:
638 // https://research.google.com/pubs/pub45290.html
639 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000640 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000641 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000642 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000643
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000644 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000645 // Annotate sample profile right after early FPM to ensure freshness of
646 // the debug info.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000647 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
648 PGOOpt->ProfileRemappingFile,
649 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000650 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
651 // for the profile annotation to be accurate in the ThinLTO backend.
652 if (Phase != ThinLTOPhase::PreLink)
653 // We perform early indirect call promotion here, before globalopt.
654 // This is important for the ThinLTO backend phase because otherwise
655 // imported available_externally functions look unreferenced and are
656 // removed.
657 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000658 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000659 }
660
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000661 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000662 // and prior to optimizing globals.
663 // FIXME: This position in the pipeline hasn't been carefully considered in
664 // years, it should be re-analyzed.
665 MPM.addPass(IPSCCPPass());
666
Matthew Simpsoncb585582017-10-25 13:40:08 +0000667 // Attach metadata to indirect call sites indicating the set of functions
668 // they may target at run-time. This should follow IPSCCP.
669 MPM.addPass(CalledValuePropagationPass());
670
Chandler Carruthe3f50642016-12-22 06:59:15 +0000671 // Optimize globals to try and fold them into constants.
672 MPM.addPass(GlobalOptPass());
673
674 // Promote any localized globals to SSA registers.
675 // FIXME: Should this instead by a run of SROA?
676 // FIXME: We should probably run instcombine and simplify-cfg afterward to
677 // delete control flows that are dead once globals have been folded to
678 // constants.
679 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
680
681 // Remove any dead arguments exposed by cleanups and constand folding
682 // globals.
683 MPM.addPass(DeadArgumentEliminationPass());
684
685 // Create a small function pass pipeline to cleanup after all the global
686 // optimizations.
687 FunctionPassManager GlobalCleanupPM(DebugLogging);
688 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000689 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
690
Chandler Carruthe3f50642016-12-22 06:59:15 +0000691 GlobalCleanupPM.addPass(SimplifyCFGPass());
692 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
693
Dehao Chen89d32262017-08-02 01:28:31 +0000694 // Add all the requested passes for instrumentation PGO, if requested.
695 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
696 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
697 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
Richard Smith6c676622018-10-10 23:13:47 +0000698 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
699 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000700 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000701 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000702
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000703 // Synthesize function entry counts for non-PGO compilation.
704 if (EnableSyntheticCounts && !PGOOpt)
705 MPM.addPass(SyntheticCountsPropagation());
706
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000707 // Require the GlobalsAA analysis for the module so we can query it within
708 // the CGSCC pipeline.
709 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000710
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000711 // Require the ProfileSummaryAnalysis for the module so we can query it within
712 // the inliner pass.
713 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
714
Chandler Carruthe3f50642016-12-22 06:59:15 +0000715 // Now begin the main postorder CGSCC pipeline.
716 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
717 // manager and trying to emulate its precise behavior. Much of this doesn't
718 // make a lot of sense and we should revisit the core CGSCC structure.
719 CGSCCPassManager MainCGPipeline(DebugLogging);
720
721 // Note: historically, the PruneEH pass was run first to deduce nounwind and
722 // generally clean up exception handling overhead. It isn't clear this is
723 // valuable as the inliner doesn't currently care whether it is inlining an
724 // invoke or a call.
725
726 // Run the inliner first. The theory is that we are walking bottom-up and so
727 // the callees have already been fully optimized, and we want to inline them
728 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000729 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000730 // because it makes profile annotation in the backend inaccurate.
731 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000732 if (Phase == ThinLTOPhase::PreLink &&
733 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000734 IP.HotCallSiteThreshold = 0;
735 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000736
737 // Now deduce any function attributes based in the current code.
738 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
739
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000740 // When at O3 add argument promotion to the pass pipeline.
741 // FIXME: It isn't at all clear why this should be limited to O3.
742 if (Level == O3)
743 MainCGPipeline.addPass(ArgumentPromotionPass());
744
Chandler Carruthe3f50642016-12-22 06:59:15 +0000745 // Lastly, add the core function simplification pipeline nested inside the
746 // CGSCC walk.
747 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000748 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000749
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000750 for (auto &C : CGSCCOptimizerLateEPCallbacks)
751 C(MainCGPipeline, Level);
752
Chandler Carruth719ffe12017-02-12 05:38:04 +0000753 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
754 // to detect when we devirtualize indirect calls and iterate the SCC passes
755 // in that case to try and catch knock-on inlining or function attrs
756 // opportunities. Then we add it to the module pipeline by walking the SCCs
757 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000758 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000759 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000760 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000761
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000762 return MPM;
763}
764
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000765ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
766 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000767 ModulePassManager MPM(DebugLogging);
768
769 // Optimize globals now that the module is fully simplified.
770 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000771 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000772
Xinliang David Li126157c2017-05-22 16:41:57 +0000773 // Run partial inlining pass to partially inline functions that have
774 // large bodies.
775 if (RunPartialInlining)
776 MPM.addPass(PartialInlinerPass());
777
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000778 // Remove avail extern fns and globals definitions since we aren't compiling
779 // an object file for later LTO. For LTO we want to preserve these so they
780 // are eligible for inlining at link-time. Note if they are unreferenced they
781 // will be removed by GlobalDCE later, so this only impacts referenced
782 // available externally globals. Eventually they will be suppressed during
783 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
784 // may make globals referenced by available external functions dead and saves
785 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000786 MPM.addPass(EliminateAvailableExternallyPass());
787
788 // Do RPO function attribute inference across the module to forward-propagate
789 // attributes where applicable.
790 // FIXME: Is this really an optimization rather than a canonicalization?
791 MPM.addPass(ReversePostOrderFunctionAttrsPass());
792
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000793 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000794 // useful as the above will have inlined, DCE'ed, and function-attr
795 // propagated everything. We should at this point have a reasonably minimal
796 // and richly annotated call graph. By computing aliasing and mod/ref
797 // information for all local globals here, the late loop passes and notably
798 // the vectorizer will be able to use them to help recognize vectorizable
799 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000800 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000801
802 FunctionPassManager OptimizePM(DebugLogging);
803 OptimizePM.addPass(Float2IntPass());
804 // FIXME: We need to run some loop optimizations to re-rotate loops after
805 // simplify-cfg and others undo their rotation.
806
807 // Optimize the loop execution. These passes operate on entire loop nests
808 // rather than on each loop in an inside-out manner, and so they are actually
809 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000810
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000811 for (auto &C : VectorizerStartEPCallbacks)
812 C(OptimizePM, Level);
813
Chandler Carrutha95ff382017-01-27 00:50:21 +0000814 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000815 OptimizePM.addPass(
816 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000817
818 // Distribute loops to allow partial vectorization. I.e. isolate dependences
819 // into separate loop that would otherwise inhibit vectorization. This is
820 // currently only performed for loops marked with the metadata
821 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000822 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000823
824 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000825 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000826
Chandler Carruthbaabda92017-01-27 01:32:26 +0000827 // Eliminate loads by forwarding stores from the previous iteration to loads
828 // of the current iteration.
829 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000830
831 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000832 OptimizePM.addPass(InstCombinePass());
833
Chandler Carrutha95ff382017-01-27 00:50:21 +0000834 // Now that we've formed fast to execute loop structures, we do further
835 // optimizations. These are run afterward as they might block doing complex
836 // analyses and transforms such as what are needed for loop vectorization.
837
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000838 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
839 // GVN, loop transforms, and others have already run, so it's now better to
840 // convert to more optimized IR using more aggressive simplify CFG options.
841 // The extra sinking transform can create larger basic blocks, so do this
842 // before SLP vectorization.
843 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
844 forwardSwitchCondToPhi(true).
845 convertSwitchToLookupTable(true).
846 needCanonicalLoops(false).
847 sinkCommonInsts(true)));
848
Chandler Carruthe3f50642016-12-22 06:59:15 +0000849 // Optimize parallel scalar instruction chains into SIMD instructions.
850 OptimizePM.addPass(SLPVectorizerPass());
851
Chandler Carruthe3f50642016-12-22 06:59:15 +0000852 OptimizePM.addPass(InstCombinePass());
853
854 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000855 // execution resources of an out-of-order processor. We also then need to
856 // clean up redundancies and loop invariant code.
857 // FIXME: It would be really good to use a loop-integrated instruction
858 // combiner for cleanup here so that the unrolling and LICM can be pipelined
859 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000860 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
861 if (EnableUnrollAndJam) {
862 OptimizePM.addPass(
863 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
864 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000865 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000866 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000867 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000868 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000869 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000870
871 // Now that we've vectorized and unrolled loops, we may have more refined
872 // alignment information, try to re-derive it here.
873 OptimizePM.addPass(AlignmentFromAssumptionsPass());
874
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000875 // Split out cold code. Splitting is done late to avoid hiding context from
876 // other optimizations and inadvertently regressing performance. The tradeoff
877 // is that this has a higher code size cost than splitting early.
878 if (EnableHotColdSplit && !LTOPreLink)
879 MPM.addPass(HotColdSplittingPass());
880
Chandler Carrutha95ff382017-01-27 00:50:21 +0000881 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
882 // canonicalization pass that enables other optimizations. As a result,
883 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
884 // result too early.
885 OptimizePM.addPass(LoopSinkPass());
886
887 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000888 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000889
Sanjay Patel6fd43912017-09-09 13:38:18 +0000890 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
891 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
892 // flattening of blocks.
893 OptimizePM.addPass(DivRemPairsPass());
894
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000895 // LoopSink (and other loop passes since the last simplifyCFG) might have
896 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
897 OptimizePM.addPass(SimplifyCFGPass());
898
Chandler Carruthc34f7892017-11-28 11:32:31 +0000899 // Optimize PHIs by speculating around them when profitable. Note that this
900 // pass needs to be run after any PRE or similar pass as it is essentially
901 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
902 OptimizePM.addPass(SpeculateAroundPHIsPass());
903
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000904 for (auto &C : OptimizerLastEPCallbacks)
905 C(OptimizePM, Level);
906
Chandler Carrutha95ff382017-01-27 00:50:21 +0000907 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000908 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
909
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000910 MPM.addPass(CGProfilePass());
911
Chandler Carruthe3f50642016-12-22 06:59:15 +0000912 // Now we need to do some global optimization transforms.
913 // FIXME: It would seem like these should come first in the optimization
914 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
915 // ordering here.
916 MPM.addPass(GlobalDCEPass());
917 MPM.addPass(ConstantMergePass());
918
919 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000920}
921
Chandler Carruthe3f50642016-12-22 06:59:15 +0000922ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000923PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000924 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000925 assert(Level != O0 && "Must request optimizations for the default pipeline!");
926
927 ModulePassManager MPM(DebugLogging);
928
929 // Force any function attributes we want the rest of the pipeline to observe.
930 MPM.addPass(ForceFunctionAttrsPass());
931
David Blaikie0c64f5a2018-01-23 01:25:20 +0000932 // Apply module pipeline start EP callback.
933 for (auto &C : PipelineStartEPCallbacks)
934 C(MPM);
935
Dehao Chen08f88312017-08-07 20:23:20 +0000936 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000937 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
938
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000939 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000940 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
941 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000942
943 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000944 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000945
946 return MPM;
947}
948
949ModulePassManager
950PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
951 bool DebugLogging) {
952 assert(Level != O0 && "Must request optimizations for the default pipeline!");
953
954 ModulePassManager MPM(DebugLogging);
955
956 // Force any function attributes we want the rest of the pipeline to observe.
957 MPM.addPass(ForceFunctionAttrsPass());
958
Dehao Chen08f88312017-08-07 20:23:20 +0000959 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000960 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
961
David Blaikie0c64f5a2018-01-23 01:25:20 +0000962 // Apply module pipeline start EP callback.
963 for (auto &C : PipelineStartEPCallbacks)
964 C(MPM);
965
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000966 // If we are planning to perform ThinLTO later, we don't bloat the code with
967 // unrolling/vectorization/... now. Just simplify the module as much as we
968 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000969 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
970 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000971
972 // Run partial inlining pass to partially inline functions that have
973 // large bodies.
974 // FIXME: It isn't clear whether this is really the right place to run this
975 // in ThinLTO. Because there is another canonicalization and simplification
976 // phase that will run after the thin link, running this here ends up with
977 // less information than will be available later and it may grow functions in
978 // ways that aren't beneficial.
979 if (RunPartialInlining)
980 MPM.addPass(PartialInlinerPass());
981
982 // Reduce the size of the IR as much as possible.
983 MPM.addPass(GlobalOptPass());
984
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000985 return MPM;
986}
987
Teresa Johnson28023db2018-07-19 14:51:32 +0000988ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
989 OptimizationLevel Level, bool DebugLogging,
990 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000991 ModulePassManager MPM(DebugLogging);
992
Teresa Johnson28023db2018-07-19 14:51:32 +0000993 if (ImportSummary) {
994 // These passes import type identifier resolutions for whole-program
995 // devirtualization and CFI. They must run early because other passes may
996 // disturb the specific instruction patterns that these passes look for,
997 // creating dependencies on resolutions that may not appear in the summary.
998 //
999 // For example, GVN may transform the pattern assume(type.test) appearing in
1000 // two basic blocks into assume(phi(type.test, type.test)), which would
1001 // transform a dependency on a WPD resolution into a dependency on a type
1002 // identifier resolution for CFI.
1003 //
1004 // Also, WPD has access to more precise information than ICP and can
1005 // devirtualize more effectively, so it should operate on the IR first.
1006 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1007 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1008 }
1009
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001010 // Force any function attributes we want the rest of the pipeline to observe.
1011 MPM.addPass(ForceFunctionAttrsPass());
1012
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001013 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001014 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1015 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001016
1017 // Now add the optimization pipeline.
1018 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1019
1020 return MPM;
1021}
1022
1023ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001024PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1025 bool DebugLogging) {
1026 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001027 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001028 return buildPerModuleDefaultPipeline(Level, DebugLogging,
1029 /*LTOPreLink=*/true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001030}
1031
Teresa Johnson28023db2018-07-19 14:51:32 +00001032ModulePassManager
1033PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1034 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001035 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1036 ModulePassManager MPM(DebugLogging);
1037
Xin Tong642c8d32018-11-15 18:06:42 +00001038 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
1039 // Load sample profile before running the LTO optimization pipeline.
1040 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
1041 PGOOpt->ProfileRemappingFile,
1042 false /* ThinLTOPhase::PreLink */));
1043 }
1044
Davide Italiano089a9122017-01-24 00:57:39 +00001045 // Remove unused virtual tables to improve the quality of code generated by
1046 // whole-program devirtualization and bitset lowering.
1047 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001048
Davide Italiano089a9122017-01-24 00:57:39 +00001049 // Force any function attributes we want the rest of the pipeline to observe.
1050 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001051
Davide Italiano089a9122017-01-24 00:57:39 +00001052 // Do basic inference of function attributes from known properties of system
1053 // libraries and other oracles.
1054 MPM.addPass(InferFunctionAttrsPass());
1055
1056 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001057 FunctionPassManager EarlyFPM(DebugLogging);
1058 EarlyFPM.addPass(CallSiteSplittingPass());
1059 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1060
Davide Italiano089a9122017-01-24 00:57:39 +00001061 // Indirect call promotion. This should promote all the targets that are
1062 // left by the earlier promotion pass that promotes intra-module targets.
1063 // This two-step promotion is to save the compile time. For LTO, it should
1064 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001065 MPM.addPass(PGOIndirectCallPromotion(
1066 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +00001067 // Propagate constants at call sites into the functions they call. This
1068 // opens opportunities for globalopt (and inlining) by substituting function
1069 // pointers passed as arguments to direct uses of functions.
1070 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001071
1072 // Attach metadata to indirect call sites indicating the set of functions
1073 // they may target at run-time. This should follow IPSCCP.
1074 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001075 }
1076
1077 // Now deduce any function attributes based in the current code.
1078 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1079 PostOrderFunctionAttrsPass()));
1080
1081 // Do RPO function attribute inference across the module to forward-propagate
1082 // attributes where applicable.
1083 // FIXME: Is this really an optimization rather than a canonicalization?
1084 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1085
Eric Christopher721eaef2019-02-26 20:33:22 +00001086 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001087 MPM.addPass(GlobalSplitPass());
1088
1089 // Run whole program optimization of virtual call when the list of callees
1090 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001091 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001092
1093 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001094 if (Level == 1) {
1095 // The LowerTypeTestsPass needs to run to lower type metadata and the
1096 // type.test intrinsics. The pass does nothing if CFI is disabled.
1097 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001098 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001099 }
Davide Italiano089a9122017-01-24 00:57:39 +00001100
1101 // Optimize globals to try and fold them into constants.
1102 MPM.addPass(GlobalOptPass());
1103
1104 // Promote any localized globals to SSA registers.
1105 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1106
1107 // Linking modules together can lead to duplicate global constant, only
1108 // keep one copy of each constant.
1109 MPM.addPass(ConstantMergePass());
1110
1111 // Remove unused arguments from functions.
1112 MPM.addPass(DeadArgumentEliminationPass());
1113
1114 // Reduce the code after globalopt and ipsccp. Both can open up significant
1115 // simplification opportunities, and both can propagate functions through
1116 // function pointers. When this happens, we often have to resolve varargs
1117 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001118 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001119 if (Level == O3)
1120 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001121 PeepholeFPM.addPass(InstCombinePass());
1122 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1123
1124 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001125
1126 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1127 // generally clean up exception handling overhead. It isn't clear this is
1128 // valuable as the inliner doesn't currently care whether it is inlining an
1129 // invoke or a call.
1130 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001131 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1132 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001133
1134 // Optimize globals again after we ran the inliner.
1135 MPM.addPass(GlobalOptPass());
1136
1137 // Garbage collect dead functions.
1138 // FIXME: Add ArgumentPromotion pass after once it's ported.
1139 MPM.addPass(GlobalDCEPass());
1140
1141 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001142 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001143 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001144 invokePeepholeEPCallbacks(FPM, Level);
1145
Davide Italiano089a9122017-01-24 00:57:39 +00001146 FPM.addPass(JumpThreadingPass());
1147
1148 // Break up allocas
1149 FPM.addPass(SROA());
1150
1151 // Run a few AA driver optimizations here and now to cleanup the code.
1152 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1153
1154 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1155 PostOrderFunctionAttrsPass()));
1156 // FIXME: here we run IP alias analysis in the legacy PM.
1157
1158 FunctionPassManager MainFPM;
1159
1160 // FIXME: once we fix LoopPass Manager, add LICM here.
1161 // FIXME: once we provide support for enabling MLSM, add it here.
1162 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001163 if (RunNewGVN)
1164 MainFPM.addPass(NewGVNPass());
1165 else
1166 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001167
1168 // Remove dead memcpy()'s.
1169 MainFPM.addPass(MemCpyOptPass());
1170
1171 // Nuke dead stores.
1172 MainFPM.addPass(DSEPass());
1173
1174 // FIXME: at this point, we run a bunch of loop passes:
1175 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1176 // loopVectorize. Enable them once the remaining issue with LPM
1177 // are sorted out.
1178
1179 MainFPM.addPass(InstCombinePass());
1180 MainFPM.addPass(SimplifyCFGPass());
1181 MainFPM.addPass(SCCPPass());
1182 MainFPM.addPass(InstCombinePass());
1183 MainFPM.addPass(BDCEPass());
1184
1185 // FIXME: We may want to run SLPVectorizer here.
1186 // After vectorization, assume intrinsics may tell us more
1187 // about pointer alignments.
1188#if 0
1189 MainFPM.add(AlignmentFromAssumptionsPass());
1190#endif
1191
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001192 // FIXME: Conditionally run LoadCombine here, after it's ported
1193 // (in case we still have this pass, given its questionable usefulness).
1194
Davide Italiano089a9122017-01-24 00:57:39 +00001195 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001196 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001197 MainFPM.addPass(JumpThreadingPass());
1198 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1199
1200 // Create a function that performs CFI checks for cross-DSO calls with
1201 // targets in the current module.
1202 MPM.addPass(CrossDSOCFIPass());
1203
1204 // Lower type metadata and the type.test intrinsic. This pass supports
1205 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1206 // to be run at link time if CFI is enabled. This pass does nothing if
1207 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001208 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001209
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001210 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1211 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1212 if (EnableHotColdSplit)
1213 MPM.addPass(HotColdSplittingPass());
1214
Davide Italiano089a9122017-01-24 00:57:39 +00001215 // Add late LTO optimization passes.
1216 // Delete basic blocks, which optimization passes may have killed.
1217 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1218
1219 // Drop bodies of available eternally objects to improve GlobalDCE.
1220 MPM.addPass(EliminateAvailableExternallyPass());
1221
1222 // Now that we have optimized the program, discard unreachable functions.
1223 MPM.addPass(GlobalDCEPass());
1224
1225 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001226 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001227}
1228
Chandler Carruth060ad612016-12-23 20:38:19 +00001229AAManager PassBuilder::buildDefaultAAPipeline() {
1230 AAManager AA;
1231
1232 // The order in which these are registered determines their priority when
1233 // being queried.
1234
1235 // First we register the basic alias analysis that provides the majority of
1236 // per-function local AA logic. This is a stateless, on-demand local set of
1237 // AA techniques.
1238 AA.registerFunctionAnalysis<BasicAA>();
1239
1240 // Next we query fast, specialized alias analyses that wrap IR-embedded
1241 // information about aliasing.
1242 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1243 AA.registerFunctionAnalysis<TypeBasedAA>();
1244
1245 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001246 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1247 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001248 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001249 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001250
1251 return AA;
1252}
1253
Chandler Carruth241bf242016-08-03 07:44:48 +00001254static Optional<int> parseRepeatPassName(StringRef Name) {
1255 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1256 return None;
1257 int Count;
1258 if (Name.getAsInteger(0, Count) || Count <= 0)
1259 return None;
1260 return Count;
1261}
1262
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001263static Optional<int> parseDevirtPassName(StringRef Name) {
1264 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1265 return None;
1266 int Count;
1267 if (Name.getAsInteger(0, Count) || Count <= 0)
1268 return None;
1269 return Count;
1270}
1271
Fedor Sergeevb7871402019-01-10 10:01:53 +00001272static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1273 if (!Name.consume_front(PassName))
1274 return false;
1275 // normal pass name w/o parameters == default parameters
1276 if (Name.empty())
1277 return true;
1278 return Name.startswith("<") && Name.endswith(">");
1279}
1280
1281namespace {
1282
1283/// This performs customized parsing of pass name with parameters.
1284///
1285/// We do not need parametrization of passes in textual pipeline very often,
1286/// yet on a rare occasion ability to specify parameters right there can be
1287/// useful.
1288///
1289/// \p Name - parameterized specification of a pass from a textual pipeline
1290/// is a string in a form of :
1291/// PassName '<' parameter-list '>'
1292///
1293/// Parameter list is being parsed by the parser callable argument, \p Parser,
1294/// It takes a string-ref of parameters and returns either StringError or a
1295/// parameter list in a form of a custom parameters type, all wrapped into
1296/// Expected<> template class.
1297///
1298template <typename ParametersParseCallableT>
1299auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1300 StringRef PassName) -> decltype(Parser(StringRef{})) {
1301 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1302
1303 StringRef Params = Name;
1304 if (!Params.consume_front(PassName)) {
1305 assert(false &&
1306 "unable to strip pass name from parametrized pass specification");
1307 }
1308 if (Params.empty())
1309 return ParametersT{};
1310 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1311 assert(false && "invalid format for parametrized pass name");
1312 }
1313
1314 Expected<ParametersT> Result = Parser(Params);
1315 assert((Result || Result.template errorIsA<StringError>()) &&
1316 "Pass parameter parser can only return StringErrors.");
1317 return std::move(Result);
1318}
1319
1320/// Parser of parameters for LoopUnroll pass.
1321Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1322 LoopUnrollOptions UnrollOpts;
1323 while (!Params.empty()) {
1324 StringRef ParamName;
1325 std::tie(ParamName, Params) = Params.split(';');
1326 int OptLevel = StringSwitch<int>(ParamName)
1327 .Case("O0", 0)
1328 .Case("O1", 1)
1329 .Case("O2", 2)
1330 .Case("O3", 3)
1331 .Default(-1);
1332 if (OptLevel >= 0) {
1333 UnrollOpts.setOptLevel(OptLevel);
1334 continue;
1335 }
1336
1337 bool Enable = !ParamName.consume_front("no-");
1338 if (ParamName == "partial") {
1339 UnrollOpts.setPartial(Enable);
1340 } else if (ParamName == "peeling") {
1341 UnrollOpts.setPeeling(Enable);
1342 } else if (ParamName == "runtime") {
1343 UnrollOpts.setRuntime(Enable);
1344 } else if (ParamName == "upperbound") {
1345 UnrollOpts.setUpperBound(Enable);
1346 } else {
1347 return make_error<StringError>(
1348 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1349 inconvertibleErrorCode());
1350 }
1351 }
1352 return UnrollOpts;
1353}
1354
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001355Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1356 MemorySanitizerOptions Result;
1357 while (!Params.empty()) {
1358 StringRef ParamName;
1359 std::tie(ParamName, Params) = Params.split(';');
1360
1361 if (ParamName == "recover") {
1362 Result.Recover = true;
1363 } else if (ParamName == "kernel") {
1364 Result.Kernel = true;
1365 } else if (ParamName.consume_front("track-origins=")) {
1366 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1367 return make_error<StringError>(
1368 formatv("invalid argument to MemorySanitizer pass track-origins "
1369 "parameter: '{0}' ",
1370 ParamName)
1371 .str(),
1372 inconvertibleErrorCode());
1373 } else {
1374 return make_error<StringError>(
1375 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1376 .str(),
1377 inconvertibleErrorCode());
1378 }
1379 }
1380 return Result;
1381}
1382
Fedor Sergeevb7871402019-01-10 10:01:53 +00001383} // namespace
1384
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001385/// Tests whether a pass name starts with a valid prefix for a default pipeline
1386/// alias.
1387static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1388 return Name.startswith("default") || Name.startswith("thinlto") ||
1389 Name.startswith("lto");
1390}
1391
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001392/// Tests whether registered callbacks will accept a given pass name.
1393///
1394/// When parsing a pipeline text, the type of the outermost pipeline may be
1395/// omitted, in which case the type is automatically determined from the first
1396/// pass name in the text. This may be a name that is handled through one of the
1397/// callbacks. We check this through the oridinary parsing callbacks by setting
1398/// up a dummy PassManager in order to not force the client to also handle this
1399/// type of query.
1400template <typename PassManagerT, typename CallbacksT>
1401static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1402 if (!Callbacks.empty()) {
1403 PassManagerT DummyPM;
1404 for (auto &CB : Callbacks)
1405 if (CB(Name, DummyPM, {}))
1406 return true;
1407 }
1408 return false;
1409}
1410
1411template <typename CallbacksT>
1412static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001413 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001414 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001415 return DefaultAliasRegex.match(Name);
1416
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001417 // Explicitly handle pass manager names.
1418 if (Name == "module")
1419 return true;
1420 if (Name == "cgscc")
1421 return true;
1422 if (Name == "function")
1423 return true;
1424
Chandler Carruth241bf242016-08-03 07:44:48 +00001425 // Explicitly handle custom-parsed pass names.
1426 if (parseRepeatPassName(Name))
1427 return true;
1428
Chandler Carruth74a8a222016-06-17 07:15:29 +00001429#define MODULE_PASS(NAME, CREATE_PASS) \
1430 if (Name == NAME) \
1431 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001432#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001433 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001434 return true;
1435#include "PassRegistry.def"
1436
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001437 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001438}
1439
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001440template <typename CallbacksT>
1441static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001442 // Explicitly handle pass manager names.
1443 if (Name == "cgscc")
1444 return true;
1445 if (Name == "function")
1446 return true;
1447
Chandler Carruth241bf242016-08-03 07:44:48 +00001448 // Explicitly handle custom-parsed pass names.
1449 if (parseRepeatPassName(Name))
1450 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001451 if (parseDevirtPassName(Name))
1452 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001453
Chandler Carruth74a8a222016-06-17 07:15:29 +00001454#define CGSCC_PASS(NAME, CREATE_PASS) \
1455 if (Name == NAME) \
1456 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001457#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001458 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001459 return true;
1460#include "PassRegistry.def"
1461
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001462 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001463}
1464
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001465template <typename CallbacksT>
1466static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001467 // Explicitly handle pass manager names.
1468 if (Name == "function")
1469 return true;
1470 if (Name == "loop")
1471 return true;
1472
Chandler Carruth241bf242016-08-03 07:44:48 +00001473 // Explicitly handle custom-parsed pass names.
1474 if (parseRepeatPassName(Name))
1475 return true;
1476
Chandler Carruth74a8a222016-06-17 07:15:29 +00001477#define FUNCTION_PASS(NAME, CREATE_PASS) \
1478 if (Name == NAME) \
1479 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001480#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1481 if (checkParametrizedPassName(Name, NAME)) \
1482 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001483#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001484 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001485 return true;
1486#include "PassRegistry.def"
1487
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001488 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001489}
1490
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001491template <typename CallbacksT>
1492static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001493 // Explicitly handle pass manager names.
1494 if (Name == "loop")
1495 return true;
1496
Chandler Carruth241bf242016-08-03 07:44:48 +00001497 // Explicitly handle custom-parsed pass names.
1498 if (parseRepeatPassName(Name))
1499 return true;
1500
Chandler Carruth74a8a222016-06-17 07:15:29 +00001501#define LOOP_PASS(NAME, CREATE_PASS) \
1502 if (Name == NAME) \
1503 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001504#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1505 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1506 return true;
1507#include "PassRegistry.def"
1508
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001509 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001510}
1511
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001512Optional<std::vector<PassBuilder::PipelineElement>>
1513PassBuilder::parsePipelineText(StringRef Text) {
1514 std::vector<PipelineElement> ResultPipeline;
1515
1516 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1517 &ResultPipeline};
1518 for (;;) {
1519 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1520 size_t Pos = Text.find_first_of(",()");
1521 Pipeline.push_back({Text.substr(0, Pos), {}});
1522
1523 // If we have a single terminating name, we're done.
1524 if (Pos == Text.npos)
1525 break;
1526
1527 char Sep = Text[Pos];
1528 Text = Text.substr(Pos + 1);
1529 if (Sep == ',')
1530 // Just a name ending in a comma, continue.
1531 continue;
1532
1533 if (Sep == '(') {
1534 // Push the inner pipeline onto the stack to continue processing.
1535 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1536 continue;
1537 }
1538
1539 assert(Sep == ')' && "Bogus separator!");
1540 // When handling the close parenthesis, we greedily consume them to avoid
1541 // empty strings in the pipeline.
1542 do {
1543 // If we try to pop the outer pipeline we have unbalanced parentheses.
1544 if (PipelineStack.size() == 1)
1545 return None;
1546
1547 PipelineStack.pop_back();
1548 } while (Text.consume_front(")"));
1549
1550 // Check if we've finished parsing.
1551 if (Text.empty())
1552 break;
1553
1554 // Otherwise, the end of an inner pipeline always has to be followed by
1555 // a comma, and then we can continue.
1556 if (!Text.consume_front(","))
1557 return None;
1558 }
1559
1560 if (PipelineStack.size() > 1)
1561 // Unbalanced paretheses.
1562 return None;
1563
1564 assert(PipelineStack.back() == &ResultPipeline &&
1565 "Wrong pipeline at the bottom of the stack!");
1566 return {std::move(ResultPipeline)};
1567}
1568
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001569Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1570 const PipelineElement &E,
1571 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001572 auto &Name = E.Name;
1573 auto &InnerPipeline = E.InnerPipeline;
1574
1575 // First handle complex passes like the pass managers which carry pipelines.
1576 if (!InnerPipeline.empty()) {
1577 if (Name == "module") {
1578 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001579 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1580 VerifyEachPass, DebugLogging))
1581 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001582 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001583 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001584 }
1585 if (Name == "cgscc") {
1586 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001587 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1588 DebugLogging))
1589 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001590 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001591 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001592 }
1593 if (Name == "function") {
1594 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001595 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1596 VerifyEachPass, DebugLogging))
1597 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001598 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001599 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001600 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001601 if (auto Count = parseRepeatPassName(Name)) {
1602 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001603 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1604 VerifyEachPass, DebugLogging))
1605 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001606 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001607 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001608 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001609
1610 for (auto &C : ModulePipelineParsingCallbacks)
1611 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001612 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001613
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001614 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001615 return make_error<StringError>(
1616 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1617 inconvertibleErrorCode());
1618 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001619 }
1620
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001621 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001622 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001623 SmallVector<StringRef, 3> Matches;
1624 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001625 return make_error<StringError>(
1626 formatv("unknown default pipeline alias '{0}'", Name).str(),
1627 inconvertibleErrorCode());
1628
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001629 assert(Matches.size() == 3 && "Must capture two matched strings!");
1630
Jordan Rosef85a95f2016-07-25 18:34:51 +00001631 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001632 .Case("O0", O0)
1633 .Case("O1", O1)
1634 .Case("O2", O2)
1635 .Case("O3", O3)
1636 .Case("Os", Os)
1637 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001638 if (L == O0)
1639 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001640 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001641
1642 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001643 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001644 } else if (Matches[1] == "thinlto-pre-link") {
1645 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1646 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001647 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001648 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001649 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001650 } else {
1651 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001652 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001653 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001654 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001655 }
1656
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001657 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001658#define MODULE_PASS(NAME, CREATE_PASS) \
1659 if (Name == NAME) { \
1660 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001661 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001662 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001663#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1664 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001665 MPM.addPass( \
1666 RequireAnalysisPass< \
1667 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001668 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001669 } \
1670 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001671 MPM.addPass(InvalidateAnalysisPass< \
1672 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001673 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001674 }
1675#include "PassRegistry.def"
1676
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001677 for (auto &C : ModulePipelineParsingCallbacks)
1678 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001679 return Error::success();
1680 return make_error<StringError>(
1681 formatv("unknown module pass '{0}'", Name).str(),
1682 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001683}
1684
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001685Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1686 const PipelineElement &E, bool VerifyEachPass,
1687 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001688 auto &Name = E.Name;
1689 auto &InnerPipeline = E.InnerPipeline;
1690
1691 // First handle complex passes like the pass managers which carry pipelines.
1692 if (!InnerPipeline.empty()) {
1693 if (Name == "cgscc") {
1694 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001695 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1696 VerifyEachPass, DebugLogging))
1697 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001698 // Add the nested pass manager with the appropriate adaptor.
1699 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001700 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001701 }
1702 if (Name == "function") {
1703 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001704 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1705 VerifyEachPass, DebugLogging))
1706 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001707 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001708 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001709 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001710 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001711 if (auto Count = parseRepeatPassName(Name)) {
1712 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001713 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1714 VerifyEachPass, DebugLogging))
1715 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001716 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001717 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001718 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001719 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1720 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001721 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1722 VerifyEachPass, DebugLogging))
1723 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001724 CGPM.addPass(
1725 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001726 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001727 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001728
1729 for (auto &C : CGSCCPipelineParsingCallbacks)
1730 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001731 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001732
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001733 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001734 return make_error<StringError>(
1735 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1736 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001737 }
1738
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001739// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001740#define CGSCC_PASS(NAME, CREATE_PASS) \
1741 if (Name == NAME) { \
1742 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001743 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001744 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001745#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1746 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001747 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001748 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001749 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1750 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001751 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001752 } \
1753 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001754 CGPM.addPass(InvalidateAnalysisPass< \
1755 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001756 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001757 }
1758#include "PassRegistry.def"
1759
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001760 for (auto &C : CGSCCPipelineParsingCallbacks)
1761 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001762 return Error::success();
1763 return make_error<StringError>(
1764 formatv("unknown cgscc pass '{0}'", Name).str(),
1765 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001766}
1767
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001768Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1769 const PipelineElement &E,
1770 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001771 auto &Name = E.Name;
1772 auto &InnerPipeline = E.InnerPipeline;
1773
1774 // First handle complex passes like the pass managers which carry pipelines.
1775 if (!InnerPipeline.empty()) {
1776 if (Name == "function") {
1777 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001778 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1779 VerifyEachPass, DebugLogging))
1780 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001781 // Add the nested pass manager with the appropriate adaptor.
1782 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001783 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001784 }
1785 if (Name == "loop") {
1786 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001787 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1788 DebugLogging))
1789 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001790 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001791 FPM.addPass(
1792 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001793 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001794 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001795 if (auto Count = parseRepeatPassName(Name)) {
1796 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001797 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1798 VerifyEachPass, DebugLogging))
1799 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001800 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001801 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001802 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001803
1804 for (auto &C : FunctionPipelineParsingCallbacks)
1805 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001806 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001807
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001808 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001809 return make_error<StringError>(
1810 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1811 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001812 }
1813
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001814// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001815#define FUNCTION_PASS(NAME, CREATE_PASS) \
1816 if (Name == NAME) { \
1817 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001818 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001819 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001820#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1821 if (checkParametrizedPassName(Name, NAME)) { \
1822 auto Params = parsePassParameters(PARSER, Name, NAME); \
1823 if (!Params) \
1824 return Params.takeError(); \
1825 FPM.addPass(CREATE_PASS(Params.get())); \
1826 return Error::success(); \
1827 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001828#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1829 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001830 FPM.addPass( \
1831 RequireAnalysisPass< \
1832 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001833 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001834 } \
1835 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001836 FPM.addPass(InvalidateAnalysisPass< \
1837 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001838 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001839 }
1840#include "PassRegistry.def"
1841
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001842 for (auto &C : FunctionPipelineParsingCallbacks)
1843 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001844 return Error::success();
1845 return make_error<StringError>(
1846 formatv("unknown function pass '{0}'", Name).str(),
1847 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001848}
1849
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001850Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1851 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001852 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001853 auto &InnerPipeline = E.InnerPipeline;
1854
1855 // First handle complex passes like the pass managers which carry pipelines.
1856 if (!InnerPipeline.empty()) {
1857 if (Name == "loop") {
1858 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001859 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1860 VerifyEachPass, DebugLogging))
1861 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001862 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001863 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001864 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001865 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001866 if (auto Count = parseRepeatPassName(Name)) {
1867 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001868 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1869 VerifyEachPass, DebugLogging))
1870 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001871 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001872 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001873 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001874
1875 for (auto &C : LoopPipelineParsingCallbacks)
1876 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001877 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001878
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001879 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001880 return make_error<StringError>(
1881 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1882 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001883 }
1884
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001885// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001886#define LOOP_PASS(NAME, CREATE_PASS) \
1887 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001888 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001889 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001890 }
1891#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1892 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001893 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001894 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1895 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1896 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001897 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001898 } \
1899 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001900 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001901 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001902 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001903 }
1904#include "PassRegistry.def"
1905
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001906 for (auto &C : LoopPipelineParsingCallbacks)
1907 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001908 return Error::success();
1909 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1910 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001911}
1912
Chandler Carruthedf59962016-02-18 09:45:17 +00001913bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001914#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1915 if (Name == NAME) { \
1916 AA.registerModuleAnalysis< \
1917 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1918 return true; \
1919 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001920#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1921 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001922 AA.registerFunctionAnalysis< \
1923 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001924 return true; \
1925 }
1926#include "PassRegistry.def"
1927
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001928 for (auto &C : AAParsingCallbacks)
1929 if (C(Name, AA))
1930 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001931 return false;
1932}
1933
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001934Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001935 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001936 bool VerifyEachPass,
1937 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001938 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001939 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1940 return Err;
1941 // FIXME: No verifier support for Loop passes!
1942 }
1943 return Error::success();
1944}
1945
1946Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1947 ArrayRef<PipelineElement> Pipeline,
1948 bool VerifyEachPass,
1949 bool DebugLogging) {
1950 for (const auto &Element : Pipeline) {
1951 if (auto Err =
1952 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1953 return Err;
1954 if (VerifyEachPass)
1955 FPM.addPass(VerifierPass());
1956 }
1957 return Error::success();
1958}
1959
1960Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1961 ArrayRef<PipelineElement> Pipeline,
1962 bool VerifyEachPass,
1963 bool DebugLogging) {
1964 for (const auto &Element : Pipeline) {
1965 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1966 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001967 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001968 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001969 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00001970}
1971
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001972void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1973 FunctionAnalysisManager &FAM,
1974 CGSCCAnalysisManager &CGAM,
1975 ModuleAnalysisManager &MAM) {
1976 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1977 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001978 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1979 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1980 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1981 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1982 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1983}
1984
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001985Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1986 ArrayRef<PipelineElement> Pipeline,
1987 bool VerifyEachPass,
1988 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001989 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001990 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1991 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001992 if (VerifyEachPass)
1993 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001994 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001995 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001996}
1997
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001998// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00001999// FIXME: Should this routine accept a TargetMachine or require the caller to
2000// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002001Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2002 StringRef PipelineText,
2003 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002004 auto Pipeline = parsePipelineText(PipelineText);
2005 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002006 return make_error<StringError>(
2007 formatv("invalid pipeline '{0}'", PipelineText).str(),
2008 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002009
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002010 // If the first name isn't at the module layer, wrap the pipeline up
2011 // automatically.
2012 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002013
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002014 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2015 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002016 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002017 } else if (isFunctionPassName(FirstName,
2018 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002019 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002020 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002021 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002022 } else {
2023 for (auto &C : TopLevelPipelineParsingCallbacks)
2024 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002025 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002026
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002027 // Unknown pass or pipeline name!
2028 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2029 return make_error<StringError>(
2030 formatv("unknown {0} name '{1}'",
2031 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2032 .str(),
2033 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002034 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002035 }
2036
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002037 if (auto Err =
2038 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2039 return Err;
2040 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002041}
Chandler Carruthedf59962016-02-18 09:45:17 +00002042
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002043// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002044Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2045 StringRef PipelineText,
2046 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002047 auto Pipeline = parsePipelineText(PipelineText);
2048 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002049 return make_error<StringError>(
2050 formatv("invalid pipeline '{0}'", PipelineText).str(),
2051 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002052
2053 StringRef FirstName = Pipeline->front().Name;
2054 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002055 return make_error<StringError>(
2056 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2057 PipelineText)
2058 .str(),
2059 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002060
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002061 if (auto Err =
2062 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2063 return Err;
2064 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002065}
2066
2067// Primary pass pipeline description parsing routine for a \c
2068// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002069Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2070 StringRef PipelineText,
2071 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002072 auto Pipeline = parsePipelineText(PipelineText);
2073 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002074 return make_error<StringError>(
2075 formatv("invalid pipeline '{0}'", PipelineText).str(),
2076 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002077
2078 StringRef FirstName = Pipeline->front().Name;
2079 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002080 return make_error<StringError>(
2081 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2082 PipelineText)
2083 .str(),
2084 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002085
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002086 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2087 DebugLogging))
2088 return Err;
2089 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002090}
2091
2092// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002093Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2094 StringRef PipelineText,
2095 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002096 auto Pipeline = parsePipelineText(PipelineText);
2097 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002098 return make_error<StringError>(
2099 formatv("invalid pipeline '{0}'", PipelineText).str(),
2100 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002101
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002102 if (auto Err =
2103 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2104 return Err;
2105
2106 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002107}
2108
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002109Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002110 // If the pipeline just consists of the word 'default' just replace the AA
2111 // manager with our default one.
2112 if (PipelineText == "default") {
2113 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002114 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002115 }
2116
Chandler Carruthedf59962016-02-18 09:45:17 +00002117 while (!PipelineText.empty()) {
2118 StringRef Name;
2119 std::tie(Name, PipelineText) = PipelineText.split(',');
2120 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002121 return make_error<StringError>(
2122 formatv("unknown alias analysis name '{0}'", Name).str(),
2123 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002124 }
2125
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002126 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002127}