blob: a36956e121ce49b7091eba9585c37a04609a5c9a [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"
Fedor Sergeeva2ed4482019-03-31 10:15:39 +000059#include "llvm/IR/SafepointIRVerifier.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000060#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000061#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000062#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000063#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000064#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000065#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000066#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000067#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000068#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000069#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000070#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000071#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000072#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000073#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000074#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000075#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000076#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000077#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000078#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000079#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000080#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000081#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000082#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000083#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000084#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000085#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000086#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000087#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000088#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000089#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000090#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000091#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000092#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000093#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000094#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000095#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000096#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Manman Ren18295122019-02-28 20:13:38 +000097#include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000098#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000099#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +0000100#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +0000101#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000102#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000103#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000104#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000105#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000106#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000107#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000108#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000109#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000110#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000111#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000112#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000113#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000114#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000115#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000116#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000117#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000118#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000119#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000120#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000121#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000122#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000123#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000124#include "llvm/Transforms/Scalar/LoopDistribute.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000125#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000126#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000127#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000128#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000129#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000130#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000131#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000132#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000133#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000134#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000135#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000136#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000137#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000138#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000139#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000140#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000141#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000142#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000143#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000144#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000145#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000146#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000147#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000148#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000149#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000150#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000151#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000152#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000153#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000154#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000155#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000156#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000157#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000158#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000159#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000160#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000161#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000162#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000163#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000164#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000165#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000166#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000167#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000168#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000169#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000170#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000171#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000172
Chandler Carruth66445382014-01-11 08:16:35 +0000173using namespace llvm;
174
Chandler Carruth719ffe12017-02-12 05:38:04 +0000175static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
176 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000177static cl::opt<bool>
178 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
179 cl::Hidden, cl::ZeroOrMore,
180 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000181
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000182static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000183 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000184 cl::Hidden, cl::ZeroOrMore,
185 cl::desc("Run NewGVN instead of GVN"));
186
Geoff Berry3cca1da2017-06-10 15:20:03 +0000187static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000188 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
189 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000190
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000191static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000192 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
193 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000194
Davide Italianobe1b6a92017-06-03 23:18:29 +0000195static cl::opt<bool> EnableGVNSink(
196 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
197 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
198
David Green963401d2018-07-01 12:47:30 +0000199static cl::opt<bool> EnableUnrollAndJam(
200 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
201 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
202
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000203static cl::opt<bool> EnableSyntheticCounts(
204 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
205 cl::desc("Run synthetic function entry count generation "
206 "pass"));
207
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000208static Regex DefaultAliasRegex(
209 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000210
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000211static cl::opt<bool>
212 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
213 cl::desc("Enable control height reduction optimization (CHR)"));
214
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000215extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000216extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000217
Wei Mi3bcccdf2019-01-17 20:48:34 +0000218extern cl::opt<bool> FlattenedProfileUsed;
219
Chandler Carruthe3f50642016-12-22 06:59:15 +0000220static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
221 switch (Level) {
222 case PassBuilder::O0:
223 case PassBuilder::O1:
224 case PassBuilder::O2:
225 case PassBuilder::O3:
226 return false;
227
228 case PassBuilder::Os:
229 case PassBuilder::Oz:
230 return true;
231 }
232 llvm_unreachable("Invalid optimization level!");
233}
234
Chandler Carruth66445382014-01-11 08:16:35 +0000235namespace {
236
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000237/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000238struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000239 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000240 return PreservedAnalyses::all();
241 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000242 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000243};
244
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000245/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000246class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
247 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000248 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000249
250public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000251 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000252 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000253 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000254};
255
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000256/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000257struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000258 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
259 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000260 return PreservedAnalyses::all();
261 }
262 static StringRef name() { return "NoOpCGSCCPass"; }
263};
264
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000265/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000266class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
267 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000268 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000269
270public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000271 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000272 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000273 return Result();
274 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000275 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000276};
277
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000278/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000279struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000280 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000281 return PreservedAnalyses::all();
282 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000283 static StringRef name() { return "NoOpFunctionPass"; }
284};
285
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000286/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000287class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
288 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000289 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000290
291public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000292 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000293 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000294 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000295};
296
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000297/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000298struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000299 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
300 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000301 return PreservedAnalyses::all();
302 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000303 static StringRef name() { return "NoOpLoopPass"; }
304};
305
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000306/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000307class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
308 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000309 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000310
311public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000312 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000313 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
314 return Result();
315 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000316 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000317};
318
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000319AnalysisKey NoOpModuleAnalysis::Key;
320AnalysisKey NoOpCGSCCAnalysis::Key;
321AnalysisKey NoOpFunctionAnalysis::Key;
322AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000323
Chandler Carruth66445382014-01-11 08:16:35 +0000324} // End anonymous namespace.
325
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000326void PassBuilder::invokePeepholeEPCallbacks(
327 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
328 for (auto &C : PeepholeEPCallbacks)
329 C(FPM, Level);
330}
331
Chandler Carruth1ff77242015-03-07 09:02:36 +0000332void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000333#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000334 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000335#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000336
337 for (auto &C : ModuleAnalysisRegistrationCallbacks)
338 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000339}
340
Chandler Carruth1ff77242015-03-07 09:02:36 +0000341void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000342#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000343 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000344#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000345
346 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
347 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000348}
349
Chandler Carruth1ff77242015-03-07 09:02:36 +0000350void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000351#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000352 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000353#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000354
355 for (auto &C : FunctionAnalysisRegistrationCallbacks)
356 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000357}
358
Justin Bognereecc3c82016-02-25 07:23:08 +0000359void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000360#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000361 LAM.registerPass([&] { return CREATE_PASS; });
362#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000363
364 for (auto &C : LoopAnalysisRegistrationCallbacks)
365 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000366}
367
Chandler Carruthe3f50642016-12-22 06:59:15 +0000368FunctionPassManager
369PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000370 ThinLTOPhase Phase,
371 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000372 assert(Level != O0 && "Must request optimizations!");
373 FunctionPassManager FPM(DebugLogging);
374
375 // Form SSA out of local memory accesses after breaking apart aggregates into
376 // scalars.
377 FPM.addPass(SROA());
378
379 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000380 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000381
Davide Italianoc3688312017-06-01 23:08:14 +0000382 // Hoisting of scalars and load expressions.
383 if (EnableGVNHoist)
384 FPM.addPass(GVNHoistPass());
385
Davide Italianobe1b6a92017-06-03 23:18:29 +0000386 // Global value numbering based sinking.
387 if (EnableGVNSink) {
388 FPM.addPass(GVNSinkPass());
389 FPM.addPass(SimplifyCFGPass());
390 }
391
Chandler Carruthe3f50642016-12-22 06:59:15 +0000392 // Speculative execution if the target has divergent branches; otherwise nop.
393 FPM.addPass(SpeculativeExecutionPass());
394
395 // Optimize based on known information about branches, and cleanup afterward.
396 FPM.addPass(JumpThreadingPass());
397 FPM.addPass(CorrelatedValuePropagationPass());
398 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000399 if (Level == O3)
400 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000401 FPM.addPass(InstCombinePass());
402
403 if (!isOptimizingForSize(Level))
404 FPM.addPass(LibCallsShrinkWrapPass());
405
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000406 invokePeepholeEPCallbacks(FPM, Level);
407
Rong Xue1f42452017-10-23 22:21:29 +0000408 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
409 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000410 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000411 !isOptimizingForSize(Level))
412 FPM.addPass(PGOMemOPSizeOpt());
413
Chandler Carruthe3f50642016-12-22 06:59:15 +0000414 FPM.addPass(TailCallElimPass());
415 FPM.addPass(SimplifyCFGPass());
416
417 // Form canonically associated expression trees, and simplify the trees using
418 // basic mathematical properties. For example, this will form (nearly)
419 // minimal multiplication trees.
420 FPM.addPass(ReassociatePass());
421
422 // Add the primary loop simplification pipeline.
423 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000424 // some function passes in between them. These can and should be removed
425 // and/or replaced by scheduling the loop pass equivalents in the correct
426 // positions. But those equivalent passes aren't powerful enough yet.
427 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
428 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
429 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
430 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000431 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
432
Chandler Carruth71fd2702018-05-30 02:46:45 +0000433 // Simplify the loop body. We do this initially to clean up after other loop
434 // passes run, either when iterating on a loop or on inner loops with
435 // implications on the outer loop.
436 LPM1.addPass(LoopInstSimplifyPass());
437 LPM1.addPass(LoopSimplifyCFGPass());
438
Chandler Carruthe3f50642016-12-22 06:59:15 +0000439 // Rotate Loop - disable header duplication at -Oz
440 LPM1.addPass(LoopRotatePass(Level != Oz));
441 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000442 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000443 LPM2.addPass(IndVarSimplifyPass());
444 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000445
446 for (auto &C : LateLoopOptimizationsEPCallbacks)
447 C(LPM2, Level);
448
Chandler Carruth79b733b2017-01-26 23:21:17 +0000449 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000450 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000451 // because it changes IR to makes profile annotation in back compile
452 // inaccurate.
Rong Xudb29a3a2019-03-04 20:21:27 +0000453 if (Phase != ThinLTOPhase::PreLink || !PGOOpt ||
454 PGOOpt->Action != PGOOptions::SampleUse)
Teresa Johnsonecd90132017-08-02 20:35:29 +0000455 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000456
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000457 for (auto &C : LoopOptimizerEndEPCallbacks)
458 C(LPM2, Level);
459
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000460 // We provide the opt remark emitter pass for LICM to use. We only need to do
461 // this once as it is immutable.
462 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000463 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000464 FPM.addPass(SimplifyCFGPass());
465 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000466 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000467
468 // Eliminate redundancies.
469 if (Level != O1) {
470 // These passes add substantial compile time so skip them at O1.
471 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000472 if (RunNewGVN)
473 FPM.addPass(NewGVNPass());
474 else
475 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000476 }
477
478 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
479 FPM.addPass(MemCpyOptPass());
480
481 // Sparse conditional constant propagation.
482 // FIXME: It isn't clear why we do this *after* loop passes rather than
483 // before...
484 FPM.addPass(SCCPPass());
485
486 // Delete dead bit computations (instcombine runs after to fold away the dead
487 // computations, and then ADCE will run later to exploit any new DCE
488 // opportunities that creates).
489 FPM.addPass(BDCEPass());
490
491 // Run instcombine after redundancy and dead bit elimination to exploit
492 // opportunities opened up by them.
493 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000494 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000495
496 // Re-consider control flow based optimizations after redundancy elimination,
497 // redo DCE, etc.
498 FPM.addPass(JumpThreadingPass());
499 FPM.addPass(CorrelatedValuePropagationPass());
500 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000501 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000502
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000503 for (auto &C : ScalarOptimizerLateEPCallbacks)
504 C(FPM, Level);
505
Chandler Carruthe3f50642016-12-22 06:59:15 +0000506 // Finally, do an expensive DCE pass to catch all the dead code exposed by
507 // the simplifications and basic cleanup after all the simplifications.
508 FPM.addPass(ADCEPass());
509 FPM.addPass(SimplifyCFGPass());
510 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000511 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000512
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000513 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000514 (PGOOpt->Action == PGOOptions::IRUse ||
515 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000516 FPM.addPass(ControlHeightReductionPass());
517
Chandler Carruthe3f50642016-12-22 06:59:15 +0000518 return FPM;
519}
520
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000521void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
522 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000523 bool RunProfileGen, bool IsCS,
524 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000525 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000526 // Generally running simplification passes and the inliner with an high
527 // threshold results in smaller executables, but there may be cases where
528 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000529 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
530 // IsCS is true).
531 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000532 InlineParams IP;
533
534 // In the old pass manager, this is a cl::opt. Should still this be one?
535 IP.DefaultThreshold = 75;
536
537 // FIXME: The hint threshold has the same value used by the regular inliner.
538 // This should probably be lowered after performance testing.
539 // FIXME: this comment is cargo culted from the old pass manager, revisit).
540 IP.HintThreshold = 325;
541
542 CGSCCPassManager CGPipeline(DebugLogging);
543
544 CGPipeline.addPass(InlinerPass(IP));
545
546 FunctionPassManager FPM;
547 FPM.addPass(SROA());
548 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
549 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
550 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000551 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000552
Davide Italiano513dfaa2017-02-13 15:26:22 +0000553 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
554
555 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
556 }
557
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000558 // Delete anything that is now dead to make sure that we don't instrument
559 // dead code. Instrumentation can end up keeping dead code around and
560 // dramatically increase code size.
561 MPM.addPass(GlobalDCEPass());
562
Davide Italiano513dfaa2017-02-13 15:26:22 +0000563 if (RunProfileGen) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000564 MPM.addPass(PGOInstrumentationGen(IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000565
Xinliang David Lib67530e2017-06-25 00:26:43 +0000566 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000567 FPM.addPass(
568 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000569 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
570
Davide Italiano513dfaa2017-02-13 15:26:22 +0000571 // Add the profile lowering pass.
572 InstrProfOptions Options;
Rong Xudb29a3a2019-03-04 20:21:27 +0000573 if (!ProfileFile.empty())
574 Options.InstrProfileOutput = ProfileFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000575 Options.DoCounterPromotion = true;
Rong Xudb29a3a2019-03-04 20:21:27 +0000576 Options.UseBFIInPromotion = IsCS;
577 MPM.addPass(InstrProfiling(Options, IsCS));
578 } else if (!ProfileFile.empty())
579 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000580}
581
Easwaran Raman8249fac2017-06-28 13:33:49 +0000582static InlineParams
583getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
584 auto O3 = PassBuilder::O3;
585 unsigned OptLevel = Level > O3 ? 2 : Level;
586 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
587 return getInlineParams(OptLevel, SizeLevel);
588}
589
Chandler Carruthe3f50642016-12-22 06:59:15 +0000590ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000591PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000592 ThinLTOPhase Phase,
593 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000594 ModulePassManager MPM(DebugLogging);
595
Rong Xudb29a3a2019-03-04 20:21:27 +0000596 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000597
598 // In ThinLTO mode, when flattened profile is used, all the available
599 // profile information will be annotated in PreLink phase so there is
600 // no need to load the profile again in PostLink.
601 bool LoadSampleProfile =
602 HasSampleProfile &&
603 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
604
605 // During the ThinLTO backend phase we perform early indirect call promotion
606 // here, before globalopt. Otherwise imported available_externally functions
607 // look unreferenced and are removed. If we are going to load the sample
608 // profile then defer until later.
609 // TODO: See if we can move later and consolidate with the location where
610 // we perform ICP when we are loading a sample profile.
611 // TODO: We pass HasSampleProfile (whether there was a sample profile file
612 // passed to the compile) to the SamplePGO flag of ICP. This is used to
613 // determine whether the new direct calls are annotated with prof metadata.
614 // Ideally this should be determined from whether the IR is annotated with
615 // sample profile, and not whether the a sample profile was provided on the
616 // command line. E.g. for flattened profiles where we will not be reloading
617 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
618 // provide the sample profile file.
619 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
620 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
621
Chandler Carruthe3f50642016-12-22 06:59:15 +0000622 // Do basic inference of function attributes from known properties of system
623 // libraries and other oracles.
624 MPM.addPass(InferFunctionAttrsPass());
625
626 // Create an early function pass manager to cleanup the output of the
627 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000628 FunctionPassManager EarlyFPM(DebugLogging);
629 EarlyFPM.addPass(SimplifyCFGPass());
630 EarlyFPM.addPass(SROA());
631 EarlyFPM.addPass(EarlyCSEPass());
632 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000633 if (Level == O3)
634 EarlyFPM.addPass(CallSiteSplittingPass());
635
Dehao Chen08f88312017-08-07 20:23:20 +0000636 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
637 // to convert bitcast to direct calls so that they can be inlined during the
638 // profile annotation prepration step.
639 // More details about SamplePGO design can be found in:
640 // https://research.google.com/pubs/pub45290.html
641 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000642 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000643 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000644 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000645
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000646 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000647 // Annotate sample profile right after early FPM to ensure freshness of
648 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000649 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000650 PGOOpt->ProfileRemappingFile,
651 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000652 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
653 // for the profile annotation to be accurate in the ThinLTO backend.
654 if (Phase != ThinLTOPhase::PreLink)
655 // We perform early indirect call promotion here, before globalopt.
656 // This is important for the ThinLTO backend phase because otherwise
657 // imported available_externally functions look unreferenced and are
658 // removed.
659 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000660 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000661 }
662
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000663 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000664 // and prior to optimizing globals.
665 // FIXME: This position in the pipeline hasn't been carefully considered in
666 // years, it should be re-analyzed.
667 MPM.addPass(IPSCCPPass());
668
Matthew Simpsoncb585582017-10-25 13:40:08 +0000669 // Attach metadata to indirect call sites indicating the set of functions
670 // they may target at run-time. This should follow IPSCCP.
671 MPM.addPass(CalledValuePropagationPass());
672
Chandler Carruthe3f50642016-12-22 06:59:15 +0000673 // Optimize globals to try and fold them into constants.
674 MPM.addPass(GlobalOptPass());
675
676 // Promote any localized globals to SSA registers.
677 // FIXME: Should this instead by a run of SROA?
678 // FIXME: We should probably run instcombine and simplify-cfg afterward to
679 // delete control flows that are dead once globals have been folded to
680 // constants.
681 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
682
683 // Remove any dead arguments exposed by cleanups and constand folding
684 // globals.
685 MPM.addPass(DeadArgumentEliminationPass());
686
687 // Create a small function pass pipeline to cleanup after all the global
688 // optimizations.
689 FunctionPassManager GlobalCleanupPM(DebugLogging);
690 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000691 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
692
Chandler Carruthe3f50642016-12-22 06:59:15 +0000693 GlobalCleanupPM.addPass(SimplifyCFGPass());
694 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
695
Dehao Chen89d32262017-08-02 01:28:31 +0000696 // Add all the requested passes for instrumentation PGO, if requested.
697 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000698 (PGOOpt->Action == PGOOptions::IRInstr ||
699 PGOOpt->Action == PGOOptions::IRUse)) {
700 addPGOInstrPasses(MPM, DebugLogging, Level,
701 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
702 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000703 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000704 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000705 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000706 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
707 PGOOpt->CSAction == PGOOptions::CSIRInstr)
708 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000709
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000710 // Synthesize function entry counts for non-PGO compilation.
711 if (EnableSyntheticCounts && !PGOOpt)
712 MPM.addPass(SyntheticCountsPropagation());
713
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000714 // Require the GlobalsAA analysis for the module so we can query it within
715 // the CGSCC pipeline.
716 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000717
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000718 // Require the ProfileSummaryAnalysis for the module so we can query it within
719 // the inliner pass.
720 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
721
Chandler Carruthe3f50642016-12-22 06:59:15 +0000722 // Now begin the main postorder CGSCC pipeline.
723 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
724 // manager and trying to emulate its precise behavior. Much of this doesn't
725 // make a lot of sense and we should revisit the core CGSCC structure.
726 CGSCCPassManager MainCGPipeline(DebugLogging);
727
728 // Note: historically, the PruneEH pass was run first to deduce nounwind and
729 // generally clean up exception handling overhead. It isn't clear this is
730 // valuable as the inliner doesn't currently care whether it is inlining an
731 // invoke or a call.
732
733 // Run the inliner first. The theory is that we are walking bottom-up and so
734 // the callees have already been fully optimized, and we want to inline them
735 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000736 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000737 // because it makes profile annotation in the backend inaccurate.
738 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000739 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
740 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000741 IP.HotCallSiteThreshold = 0;
742 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000743
744 // Now deduce any function attributes based in the current code.
745 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
746
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000747 // When at O3 add argument promotion to the pass pipeline.
748 // FIXME: It isn't at all clear why this should be limited to O3.
749 if (Level == O3)
750 MainCGPipeline.addPass(ArgumentPromotionPass());
751
Chandler Carruthe3f50642016-12-22 06:59:15 +0000752 // Lastly, add the core function simplification pipeline nested inside the
753 // CGSCC walk.
754 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000755 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000756
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000757 for (auto &C : CGSCCOptimizerLateEPCallbacks)
758 C(MainCGPipeline, Level);
759
Chandler Carruth719ffe12017-02-12 05:38:04 +0000760 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
761 // to detect when we devirtualize indirect calls and iterate the SCC passes
762 // in that case to try and catch knock-on inlining or function attrs
763 // opportunities. Then we add it to the module pipeline by walking the SCCs
764 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000765 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000766 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000767 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000768
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000769 return MPM;
770}
771
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000772ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
773 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000774 ModulePassManager MPM(DebugLogging);
775
776 // Optimize globals now that the module is fully simplified.
777 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000778 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000779
Xinliang David Li126157c2017-05-22 16:41:57 +0000780 // Run partial inlining pass to partially inline functions that have
781 // large bodies.
782 if (RunPartialInlining)
783 MPM.addPass(PartialInlinerPass());
784
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000785 // Remove avail extern fns and globals definitions since we aren't compiling
786 // an object file for later LTO. For LTO we want to preserve these so they
787 // are eligible for inlining at link-time. Note if they are unreferenced they
788 // will be removed by GlobalDCE later, so this only impacts referenced
789 // available externally globals. Eventually they will be suppressed during
790 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
791 // may make globals referenced by available external functions dead and saves
792 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000793 MPM.addPass(EliminateAvailableExternallyPass());
794
Manman Ren18295122019-02-28 20:13:38 +0000795 if (EnableOrderFileInstrumentation)
796 MPM.addPass(InstrOrderFilePass());
797
Chandler Carruthe3f50642016-12-22 06:59:15 +0000798 // Do RPO function attribute inference across the module to forward-propagate
799 // attributes where applicable.
800 // FIXME: Is this really an optimization rather than a canonicalization?
801 MPM.addPass(ReversePostOrderFunctionAttrsPass());
802
Rong Xudb29a3a2019-03-04 20:21:27 +0000803 // Do a post inline PGO instrumentation and use pass. This is a context
804 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
805 // cross-module inline has not been done yet. The context sensitive
806 // instrumentation is after all the inlines are done.
807 if (!LTOPreLink && PGOOpt) {
808 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
809 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
810 /* IsCS */ true, PGOOpt->CSProfileGenFile,
811 PGOOpt->ProfileRemappingFile);
812 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
813 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
814 /* IsCS */ true, PGOOpt->ProfileFile,
815 PGOOpt->ProfileRemappingFile);
816 }
817
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000818 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000819 // useful as the above will have inlined, DCE'ed, and function-attr
820 // propagated everything. We should at this point have a reasonably minimal
821 // and richly annotated call graph. By computing aliasing and mod/ref
822 // information for all local globals here, the late loop passes and notably
823 // the vectorizer will be able to use them to help recognize vectorizable
824 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000825 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000826
827 FunctionPassManager OptimizePM(DebugLogging);
828 OptimizePM.addPass(Float2IntPass());
829 // FIXME: We need to run some loop optimizations to re-rotate loops after
830 // simplify-cfg and others undo their rotation.
831
832 // Optimize the loop execution. These passes operate on entire loop nests
833 // rather than on each loop in an inside-out manner, and so they are actually
834 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000835
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000836 for (auto &C : VectorizerStartEPCallbacks)
837 C(OptimizePM, Level);
838
Chandler Carrutha95ff382017-01-27 00:50:21 +0000839 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000840 OptimizePM.addPass(
841 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000842
843 // Distribute loops to allow partial vectorization. I.e. isolate dependences
844 // into separate loop that would otherwise inhibit vectorization. This is
845 // currently only performed for loops marked with the metadata
846 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000847 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000848
849 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000850 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000851
Chandler Carruthbaabda92017-01-27 01:32:26 +0000852 // Eliminate loads by forwarding stores from the previous iteration to loads
853 // of the current iteration.
854 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000855
856 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000857 OptimizePM.addPass(InstCombinePass());
858
Chandler Carrutha95ff382017-01-27 00:50:21 +0000859 // Now that we've formed fast to execute loop structures, we do further
860 // optimizations. These are run afterward as they might block doing complex
861 // analyses and transforms such as what are needed for loop vectorization.
862
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000863 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
864 // GVN, loop transforms, and others have already run, so it's now better to
865 // convert to more optimized IR using more aggressive simplify CFG options.
866 // The extra sinking transform can create larger basic blocks, so do this
867 // before SLP vectorization.
868 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
869 forwardSwitchCondToPhi(true).
870 convertSwitchToLookupTable(true).
871 needCanonicalLoops(false).
872 sinkCommonInsts(true)));
873
Chandler Carruthe3f50642016-12-22 06:59:15 +0000874 // Optimize parallel scalar instruction chains into SIMD instructions.
875 OptimizePM.addPass(SLPVectorizerPass());
876
Chandler Carruthe3f50642016-12-22 06:59:15 +0000877 OptimizePM.addPass(InstCombinePass());
878
879 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000880 // execution resources of an out-of-order processor. We also then need to
881 // clean up redundancies and loop invariant code.
882 // FIXME: It would be really good to use a loop-integrated instruction
883 // combiner for cleanup here so that the unrolling and LICM can be pipelined
884 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000885 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
886 if (EnableUnrollAndJam) {
887 OptimizePM.addPass(
888 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
889 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000890 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000891 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000892 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000893 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000894 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000895
896 // Now that we've vectorized and unrolled loops, we may have more refined
897 // alignment information, try to re-derive it here.
898 OptimizePM.addPass(AlignmentFromAssumptionsPass());
899
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000900 // Split out cold code. Splitting is done late to avoid hiding context from
901 // other optimizations and inadvertently regressing performance. The tradeoff
902 // is that this has a higher code size cost than splitting early.
903 if (EnableHotColdSplit && !LTOPreLink)
904 MPM.addPass(HotColdSplittingPass());
905
Chandler Carrutha95ff382017-01-27 00:50:21 +0000906 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
907 // canonicalization pass that enables other optimizations. As a result,
908 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
909 // result too early.
910 OptimizePM.addPass(LoopSinkPass());
911
912 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000913 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000914
Sanjay Patel6fd43912017-09-09 13:38:18 +0000915 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
916 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
917 // flattening of blocks.
918 OptimizePM.addPass(DivRemPairsPass());
919
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000920 // LoopSink (and other loop passes since the last simplifyCFG) might have
921 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
922 OptimizePM.addPass(SimplifyCFGPass());
923
Chandler Carruthc34f7892017-11-28 11:32:31 +0000924 // Optimize PHIs by speculating around them when profitable. Note that this
925 // pass needs to be run after any PRE or similar pass as it is essentially
926 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
927 OptimizePM.addPass(SpeculateAroundPHIsPass());
928
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000929 for (auto &C : OptimizerLastEPCallbacks)
930 C(OptimizePM, Level);
931
Chandler Carrutha95ff382017-01-27 00:50:21 +0000932 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000933 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
934
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000935 MPM.addPass(CGProfilePass());
936
Chandler Carruthe3f50642016-12-22 06:59:15 +0000937 // Now we need to do some global optimization transforms.
938 // FIXME: It would seem like these should come first in the optimization
939 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
940 // ordering here.
941 MPM.addPass(GlobalDCEPass());
942 MPM.addPass(ConstantMergePass());
943
944 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000945}
946
Chandler Carruthe3f50642016-12-22 06:59:15 +0000947ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000948PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000949 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000950 assert(Level != O0 && "Must request optimizations for the default pipeline!");
951
952 ModulePassManager MPM(DebugLogging);
953
954 // Force any function attributes we want the rest of the pipeline to observe.
955 MPM.addPass(ForceFunctionAttrsPass());
956
David Blaikie0c64f5a2018-01-23 01:25:20 +0000957 // Apply module pipeline start EP callback.
958 for (auto &C : PipelineStartEPCallbacks)
959 C(MPM);
960
Dehao Chen08f88312017-08-07 20:23:20 +0000961 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000962 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
963
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000964 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000965 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
966 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000967
968 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000969 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000970
971 return MPM;
972}
973
974ModulePassManager
975PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
976 bool DebugLogging) {
977 assert(Level != O0 && "Must request optimizations for the default pipeline!");
978
979 ModulePassManager MPM(DebugLogging);
980
981 // Force any function attributes we want the rest of the pipeline to observe.
982 MPM.addPass(ForceFunctionAttrsPass());
983
Dehao Chen08f88312017-08-07 20:23:20 +0000984 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000985 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
986
David Blaikie0c64f5a2018-01-23 01:25:20 +0000987 // Apply module pipeline start EP callback.
988 for (auto &C : PipelineStartEPCallbacks)
989 C(MPM);
990
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000991 // If we are planning to perform ThinLTO later, we don't bloat the code with
992 // unrolling/vectorization/... now. Just simplify the module as much as we
993 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000994 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
995 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000996
997 // Run partial inlining pass to partially inline functions that have
998 // large bodies.
999 // FIXME: It isn't clear whether this is really the right place to run this
1000 // in ThinLTO. Because there is another canonicalization and simplification
1001 // phase that will run after the thin link, running this here ends up with
1002 // less information than will be available later and it may grow functions in
1003 // ways that aren't beneficial.
1004 if (RunPartialInlining)
1005 MPM.addPass(PartialInlinerPass());
1006
1007 // Reduce the size of the IR as much as possible.
1008 MPM.addPass(GlobalOptPass());
1009
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001010 return MPM;
1011}
1012
Teresa Johnson28023db2018-07-19 14:51:32 +00001013ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1014 OptimizationLevel Level, bool DebugLogging,
1015 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001016 ModulePassManager MPM(DebugLogging);
1017
Teresa Johnson28023db2018-07-19 14:51:32 +00001018 if (ImportSummary) {
1019 // These passes import type identifier resolutions for whole-program
1020 // devirtualization and CFI. They must run early because other passes may
1021 // disturb the specific instruction patterns that these passes look for,
1022 // creating dependencies on resolutions that may not appear in the summary.
1023 //
1024 // For example, GVN may transform the pattern assume(type.test) appearing in
1025 // two basic blocks into assume(phi(type.test, type.test)), which would
1026 // transform a dependency on a WPD resolution into a dependency on a type
1027 // identifier resolution for CFI.
1028 //
1029 // Also, WPD has access to more precise information than ICP and can
1030 // devirtualize more effectively, so it should operate on the IR first.
1031 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1032 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1033 }
1034
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001035 // Force any function attributes we want the rest of the pipeline to observe.
1036 MPM.addPass(ForceFunctionAttrsPass());
1037
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001038 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001039 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1040 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001041
1042 // Now add the optimization pipeline.
1043 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1044
1045 return MPM;
1046}
1047
1048ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001049PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1050 bool DebugLogging) {
1051 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001052 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001053 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001054 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001055}
1056
Teresa Johnson28023db2018-07-19 14:51:32 +00001057ModulePassManager
1058PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1059 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001060 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1061 ModulePassManager MPM(DebugLogging);
1062
Rong Xudb29a3a2019-03-04 20:21:27 +00001063 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001064 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001065 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001066 PGOOpt->ProfileRemappingFile,
1067 false /* ThinLTOPhase::PreLink */));
1068 }
1069
Davide Italiano089a9122017-01-24 00:57:39 +00001070 // Remove unused virtual tables to improve the quality of code generated by
1071 // whole-program devirtualization and bitset lowering.
1072 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001073
Davide Italiano089a9122017-01-24 00:57:39 +00001074 // Force any function attributes we want the rest of the pipeline to observe.
1075 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001076
Davide Italiano089a9122017-01-24 00:57:39 +00001077 // Do basic inference of function attributes from known properties of system
1078 // libraries and other oracles.
1079 MPM.addPass(InferFunctionAttrsPass());
1080
1081 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001082 FunctionPassManager EarlyFPM(DebugLogging);
1083 EarlyFPM.addPass(CallSiteSplittingPass());
1084 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1085
Davide Italiano089a9122017-01-24 00:57:39 +00001086 // Indirect call promotion. This should promote all the targets that are
1087 // left by the earlier promotion pass that promotes intra-module targets.
1088 // This two-step promotion is to save the compile time. For LTO, it should
1089 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001090 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001091 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001092 // Propagate constants at call sites into the functions they call. This
1093 // opens opportunities for globalopt (and inlining) by substituting function
1094 // pointers passed as arguments to direct uses of functions.
1095 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001096
1097 // Attach metadata to indirect call sites indicating the set of functions
1098 // they may target at run-time. This should follow IPSCCP.
1099 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001100 }
1101
1102 // Now deduce any function attributes based in the current code.
1103 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1104 PostOrderFunctionAttrsPass()));
1105
1106 // Do RPO function attribute inference across the module to forward-propagate
1107 // attributes where applicable.
1108 // FIXME: Is this really an optimization rather than a canonicalization?
1109 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1110
Eric Christopher721eaef2019-02-26 20:33:22 +00001111 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001112 MPM.addPass(GlobalSplitPass());
1113
1114 // Run whole program optimization of virtual call when the list of callees
1115 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001116 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001117
1118 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001119 if (Level == 1) {
1120 // The LowerTypeTestsPass needs to run to lower type metadata and the
1121 // type.test intrinsics. The pass does nothing if CFI is disabled.
1122 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001123 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001124 }
Davide Italiano089a9122017-01-24 00:57:39 +00001125
1126 // Optimize globals to try and fold them into constants.
1127 MPM.addPass(GlobalOptPass());
1128
1129 // Promote any localized globals to SSA registers.
1130 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1131
1132 // Linking modules together can lead to duplicate global constant, only
1133 // keep one copy of each constant.
1134 MPM.addPass(ConstantMergePass());
1135
1136 // Remove unused arguments from functions.
1137 MPM.addPass(DeadArgumentEliminationPass());
1138
1139 // Reduce the code after globalopt and ipsccp. Both can open up significant
1140 // simplification opportunities, and both can propagate functions through
1141 // function pointers. When this happens, we often have to resolve varargs
1142 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001143 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001144 if (Level == O3)
1145 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001146 PeepholeFPM.addPass(InstCombinePass());
1147 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1148
1149 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001150
1151 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1152 // generally clean up exception handling overhead. It isn't clear this is
1153 // valuable as the inliner doesn't currently care whether it is inlining an
1154 // invoke or a call.
1155 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001156 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1157 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001158
1159 // Optimize globals again after we ran the inliner.
1160 MPM.addPass(GlobalOptPass());
1161
1162 // Garbage collect dead functions.
1163 // FIXME: Add ArgumentPromotion pass after once it's ported.
1164 MPM.addPass(GlobalDCEPass());
1165
1166 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001167 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001168 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001169 invokePeepholeEPCallbacks(FPM, Level);
1170
Davide Italiano089a9122017-01-24 00:57:39 +00001171 FPM.addPass(JumpThreadingPass());
1172
Rong Xudb29a3a2019-03-04 20:21:27 +00001173 // Do a post inline PGO instrumentation and use pass. This is a context
1174 // sensitive PGO pass.
1175 if (PGOOpt) {
1176 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1177 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1178 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1179 PGOOpt->ProfileRemappingFile);
1180 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1181 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1182 /* IsCS */ true, PGOOpt->ProfileFile,
1183 PGOOpt->ProfileRemappingFile);
1184 }
1185
Davide Italiano089a9122017-01-24 00:57:39 +00001186 // Break up allocas
1187 FPM.addPass(SROA());
1188
Robert Lougherf2158a82019-03-20 19:08:18 +00001189 // LTO provides additional opportunities for tailcall elimination due to
1190 // link-time inlining, and visibility of nocapture attribute.
1191 FPM.addPass(TailCallElimPass());
1192
Davide Italiano089a9122017-01-24 00:57:39 +00001193 // Run a few AA driver optimizations here and now to cleanup the code.
1194 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1195
1196 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1197 PostOrderFunctionAttrsPass()));
1198 // FIXME: here we run IP alias analysis in the legacy PM.
1199
1200 FunctionPassManager MainFPM;
1201
1202 // FIXME: once we fix LoopPass Manager, add LICM here.
1203 // FIXME: once we provide support for enabling MLSM, add it here.
1204 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001205 if (RunNewGVN)
1206 MainFPM.addPass(NewGVNPass());
1207 else
1208 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001209
1210 // Remove dead memcpy()'s.
1211 MainFPM.addPass(MemCpyOptPass());
1212
1213 // Nuke dead stores.
1214 MainFPM.addPass(DSEPass());
1215
1216 // FIXME: at this point, we run a bunch of loop passes:
1217 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1218 // loopVectorize. Enable them once the remaining issue with LPM
1219 // are sorted out.
1220
1221 MainFPM.addPass(InstCombinePass());
1222 MainFPM.addPass(SimplifyCFGPass());
1223 MainFPM.addPass(SCCPPass());
1224 MainFPM.addPass(InstCombinePass());
1225 MainFPM.addPass(BDCEPass());
1226
1227 // FIXME: We may want to run SLPVectorizer here.
1228 // After vectorization, assume intrinsics may tell us more
1229 // about pointer alignments.
1230#if 0
1231 MainFPM.add(AlignmentFromAssumptionsPass());
1232#endif
1233
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001234 // FIXME: Conditionally run LoadCombine here, after it's ported
1235 // (in case we still have this pass, given its questionable usefulness).
1236
Davide Italiano089a9122017-01-24 00:57:39 +00001237 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001238 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001239 MainFPM.addPass(JumpThreadingPass());
1240 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1241
1242 // Create a function that performs CFI checks for cross-DSO calls with
1243 // targets in the current module.
1244 MPM.addPass(CrossDSOCFIPass());
1245
1246 // Lower type metadata and the type.test intrinsic. This pass supports
1247 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1248 // to be run at link time if CFI is enabled. This pass does nothing if
1249 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001250 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001251
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001252 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1253 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1254 if (EnableHotColdSplit)
1255 MPM.addPass(HotColdSplittingPass());
1256
Davide Italiano089a9122017-01-24 00:57:39 +00001257 // Add late LTO optimization passes.
1258 // Delete basic blocks, which optimization passes may have killed.
1259 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1260
1261 // Drop bodies of available eternally objects to improve GlobalDCE.
1262 MPM.addPass(EliminateAvailableExternallyPass());
1263
1264 // Now that we have optimized the program, discard unreachable functions.
1265 MPM.addPass(GlobalDCEPass());
1266
1267 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001268 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001269}
1270
Chandler Carruth060ad612016-12-23 20:38:19 +00001271AAManager PassBuilder::buildDefaultAAPipeline() {
1272 AAManager AA;
1273
1274 // The order in which these are registered determines their priority when
1275 // being queried.
1276
1277 // First we register the basic alias analysis that provides the majority of
1278 // per-function local AA logic. This is a stateless, on-demand local set of
1279 // AA techniques.
1280 AA.registerFunctionAnalysis<BasicAA>();
1281
1282 // Next we query fast, specialized alias analyses that wrap IR-embedded
1283 // information about aliasing.
1284 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1285 AA.registerFunctionAnalysis<TypeBasedAA>();
1286
1287 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001288 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1289 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001290 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001291 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001292
1293 return AA;
1294}
1295
Chandler Carruth241bf242016-08-03 07:44:48 +00001296static Optional<int> parseRepeatPassName(StringRef Name) {
1297 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1298 return None;
1299 int Count;
1300 if (Name.getAsInteger(0, Count) || Count <= 0)
1301 return None;
1302 return Count;
1303}
1304
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001305static Optional<int> parseDevirtPassName(StringRef Name) {
1306 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1307 return None;
1308 int Count;
1309 if (Name.getAsInteger(0, Count) || Count <= 0)
1310 return None;
1311 return Count;
1312}
1313
Fedor Sergeevb7871402019-01-10 10:01:53 +00001314static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1315 if (!Name.consume_front(PassName))
1316 return false;
1317 // normal pass name w/o parameters == default parameters
1318 if (Name.empty())
1319 return true;
1320 return Name.startswith("<") && Name.endswith(">");
1321}
1322
1323namespace {
1324
1325/// This performs customized parsing of pass name with parameters.
1326///
1327/// We do not need parametrization of passes in textual pipeline very often,
1328/// yet on a rare occasion ability to specify parameters right there can be
1329/// useful.
1330///
1331/// \p Name - parameterized specification of a pass from a textual pipeline
1332/// is a string in a form of :
1333/// PassName '<' parameter-list '>'
1334///
1335/// Parameter list is being parsed by the parser callable argument, \p Parser,
1336/// It takes a string-ref of parameters and returns either StringError or a
1337/// parameter list in a form of a custom parameters type, all wrapped into
1338/// Expected<> template class.
1339///
1340template <typename ParametersParseCallableT>
1341auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1342 StringRef PassName) -> decltype(Parser(StringRef{})) {
1343 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1344
1345 StringRef Params = Name;
1346 if (!Params.consume_front(PassName)) {
1347 assert(false &&
1348 "unable to strip pass name from parametrized pass specification");
1349 }
1350 if (Params.empty())
1351 return ParametersT{};
1352 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1353 assert(false && "invalid format for parametrized pass name");
1354 }
1355
1356 Expected<ParametersT> Result = Parser(Params);
1357 assert((Result || Result.template errorIsA<StringError>()) &&
1358 "Pass parameter parser can only return StringErrors.");
1359 return std::move(Result);
1360}
1361
1362/// Parser of parameters for LoopUnroll pass.
1363Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1364 LoopUnrollOptions UnrollOpts;
1365 while (!Params.empty()) {
1366 StringRef ParamName;
1367 std::tie(ParamName, Params) = Params.split(';');
1368 int OptLevel = StringSwitch<int>(ParamName)
1369 .Case("O0", 0)
1370 .Case("O1", 1)
1371 .Case("O2", 2)
1372 .Case("O3", 3)
1373 .Default(-1);
1374 if (OptLevel >= 0) {
1375 UnrollOpts.setOptLevel(OptLevel);
1376 continue;
1377 }
1378
1379 bool Enable = !ParamName.consume_front("no-");
1380 if (ParamName == "partial") {
1381 UnrollOpts.setPartial(Enable);
1382 } else if (ParamName == "peeling") {
1383 UnrollOpts.setPeeling(Enable);
1384 } else if (ParamName == "runtime") {
1385 UnrollOpts.setRuntime(Enable);
1386 } else if (ParamName == "upperbound") {
1387 UnrollOpts.setUpperBound(Enable);
1388 } else {
1389 return make_error<StringError>(
1390 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1391 inconvertibleErrorCode());
1392 }
1393 }
1394 return UnrollOpts;
1395}
1396
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001397Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1398 MemorySanitizerOptions Result;
1399 while (!Params.empty()) {
1400 StringRef ParamName;
1401 std::tie(ParamName, Params) = Params.split(';');
1402
1403 if (ParamName == "recover") {
1404 Result.Recover = true;
1405 } else if (ParamName == "kernel") {
1406 Result.Kernel = true;
1407 } else if (ParamName.consume_front("track-origins=")) {
1408 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1409 return make_error<StringError>(
1410 formatv("invalid argument to MemorySanitizer pass track-origins "
1411 "parameter: '{0}' ",
1412 ParamName)
1413 .str(),
1414 inconvertibleErrorCode());
1415 } else {
1416 return make_error<StringError>(
1417 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1418 .str(),
1419 inconvertibleErrorCode());
1420 }
1421 }
1422 return Result;
1423}
1424
Fedor Sergeevb7871402019-01-10 10:01:53 +00001425} // namespace
1426
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001427/// Tests whether a pass name starts with a valid prefix for a default pipeline
1428/// alias.
1429static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1430 return Name.startswith("default") || Name.startswith("thinlto") ||
1431 Name.startswith("lto");
1432}
1433
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001434/// Tests whether registered callbacks will accept a given pass name.
1435///
1436/// When parsing a pipeline text, the type of the outermost pipeline may be
1437/// omitted, in which case the type is automatically determined from the first
1438/// pass name in the text. This may be a name that is handled through one of the
1439/// callbacks. We check this through the oridinary parsing callbacks by setting
1440/// up a dummy PassManager in order to not force the client to also handle this
1441/// type of query.
1442template <typename PassManagerT, typename CallbacksT>
1443static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1444 if (!Callbacks.empty()) {
1445 PassManagerT DummyPM;
1446 for (auto &CB : Callbacks)
1447 if (CB(Name, DummyPM, {}))
1448 return true;
1449 }
1450 return false;
1451}
1452
1453template <typename CallbacksT>
1454static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001455 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001456 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001457 return DefaultAliasRegex.match(Name);
1458
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001459 // Explicitly handle pass manager names.
1460 if (Name == "module")
1461 return true;
1462 if (Name == "cgscc")
1463 return true;
1464 if (Name == "function")
1465 return true;
1466
Chandler Carruth241bf242016-08-03 07:44:48 +00001467 // Explicitly handle custom-parsed pass names.
1468 if (parseRepeatPassName(Name))
1469 return true;
1470
Chandler Carruth74a8a222016-06-17 07:15:29 +00001471#define MODULE_PASS(NAME, CREATE_PASS) \
1472 if (Name == NAME) \
1473 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001474#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001475 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001476 return true;
1477#include "PassRegistry.def"
1478
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001479 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001480}
1481
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001482template <typename CallbacksT>
1483static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001484 // Explicitly handle pass manager names.
1485 if (Name == "cgscc")
1486 return true;
1487 if (Name == "function")
1488 return true;
1489
Chandler Carruth241bf242016-08-03 07:44:48 +00001490 // Explicitly handle custom-parsed pass names.
1491 if (parseRepeatPassName(Name))
1492 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001493 if (parseDevirtPassName(Name))
1494 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001495
Chandler Carruth74a8a222016-06-17 07:15:29 +00001496#define CGSCC_PASS(NAME, CREATE_PASS) \
1497 if (Name == NAME) \
1498 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001499#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001500 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001501 return true;
1502#include "PassRegistry.def"
1503
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001504 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001505}
1506
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001507template <typename CallbacksT>
1508static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001509 // Explicitly handle pass manager names.
1510 if (Name == "function")
1511 return true;
1512 if (Name == "loop")
1513 return true;
1514
Chandler Carruth241bf242016-08-03 07:44:48 +00001515 // Explicitly handle custom-parsed pass names.
1516 if (parseRepeatPassName(Name))
1517 return true;
1518
Chandler Carruth74a8a222016-06-17 07:15:29 +00001519#define FUNCTION_PASS(NAME, CREATE_PASS) \
1520 if (Name == NAME) \
1521 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001522#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1523 if (checkParametrizedPassName(Name, NAME)) \
1524 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001525#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001526 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001527 return true;
1528#include "PassRegistry.def"
1529
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001530 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001531}
1532
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001533template <typename CallbacksT>
1534static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001535 // Explicitly handle pass manager names.
1536 if (Name == "loop")
1537 return true;
1538
Chandler Carruth241bf242016-08-03 07:44:48 +00001539 // Explicitly handle custom-parsed pass names.
1540 if (parseRepeatPassName(Name))
1541 return true;
1542
Chandler Carruth74a8a222016-06-17 07:15:29 +00001543#define LOOP_PASS(NAME, CREATE_PASS) \
1544 if (Name == NAME) \
1545 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001546#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1547 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1548 return true;
1549#include "PassRegistry.def"
1550
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001551 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001552}
1553
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001554Optional<std::vector<PassBuilder::PipelineElement>>
1555PassBuilder::parsePipelineText(StringRef Text) {
1556 std::vector<PipelineElement> ResultPipeline;
1557
1558 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1559 &ResultPipeline};
1560 for (;;) {
1561 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1562 size_t Pos = Text.find_first_of(",()");
1563 Pipeline.push_back({Text.substr(0, Pos), {}});
1564
1565 // If we have a single terminating name, we're done.
1566 if (Pos == Text.npos)
1567 break;
1568
1569 char Sep = Text[Pos];
1570 Text = Text.substr(Pos + 1);
1571 if (Sep == ',')
1572 // Just a name ending in a comma, continue.
1573 continue;
1574
1575 if (Sep == '(') {
1576 // Push the inner pipeline onto the stack to continue processing.
1577 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1578 continue;
1579 }
1580
1581 assert(Sep == ')' && "Bogus separator!");
1582 // When handling the close parenthesis, we greedily consume them to avoid
1583 // empty strings in the pipeline.
1584 do {
1585 // If we try to pop the outer pipeline we have unbalanced parentheses.
1586 if (PipelineStack.size() == 1)
1587 return None;
1588
1589 PipelineStack.pop_back();
1590 } while (Text.consume_front(")"));
1591
1592 // Check if we've finished parsing.
1593 if (Text.empty())
1594 break;
1595
1596 // Otherwise, the end of an inner pipeline always has to be followed by
1597 // a comma, and then we can continue.
1598 if (!Text.consume_front(","))
1599 return None;
1600 }
1601
1602 if (PipelineStack.size() > 1)
1603 // Unbalanced paretheses.
1604 return None;
1605
1606 assert(PipelineStack.back() == &ResultPipeline &&
1607 "Wrong pipeline at the bottom of the stack!");
1608 return {std::move(ResultPipeline)};
1609}
1610
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001611Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1612 const PipelineElement &E,
1613 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001614 auto &Name = E.Name;
1615 auto &InnerPipeline = E.InnerPipeline;
1616
1617 // First handle complex passes like the pass managers which carry pipelines.
1618 if (!InnerPipeline.empty()) {
1619 if (Name == "module") {
1620 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001621 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1622 VerifyEachPass, DebugLogging))
1623 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001624 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001625 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001626 }
1627 if (Name == "cgscc") {
1628 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001629 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1630 DebugLogging))
1631 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001632 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001633 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001634 }
1635 if (Name == "function") {
1636 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001637 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1638 VerifyEachPass, DebugLogging))
1639 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001640 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001641 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001642 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001643 if (auto Count = parseRepeatPassName(Name)) {
1644 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001645 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1646 VerifyEachPass, DebugLogging))
1647 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001648 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001649 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001650 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001651
1652 for (auto &C : ModulePipelineParsingCallbacks)
1653 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001654 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001655
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001656 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001657 return make_error<StringError>(
1658 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1659 inconvertibleErrorCode());
1660 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001661 }
1662
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001663 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001664 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001665 SmallVector<StringRef, 3> Matches;
1666 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001667 return make_error<StringError>(
1668 formatv("unknown default pipeline alias '{0}'", Name).str(),
1669 inconvertibleErrorCode());
1670
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001671 assert(Matches.size() == 3 && "Must capture two matched strings!");
1672
Jordan Rosef85a95f2016-07-25 18:34:51 +00001673 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001674 .Case("O0", O0)
1675 .Case("O1", O1)
1676 .Case("O2", O2)
1677 .Case("O3", O3)
1678 .Case("Os", Os)
1679 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001680 if (L == O0)
1681 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001682 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001683
1684 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001685 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001686 } else if (Matches[1] == "thinlto-pre-link") {
1687 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1688 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001689 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001690 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001691 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001692 } else {
1693 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001694 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001695 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001696 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001697 }
1698
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001699 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001700#define MODULE_PASS(NAME, CREATE_PASS) \
1701 if (Name == NAME) { \
1702 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001703 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001704 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001705#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1706 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001707 MPM.addPass( \
1708 RequireAnalysisPass< \
1709 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001710 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001711 } \
1712 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001713 MPM.addPass(InvalidateAnalysisPass< \
1714 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001715 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001716 }
1717#include "PassRegistry.def"
1718
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001719 for (auto &C : ModulePipelineParsingCallbacks)
1720 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001721 return Error::success();
1722 return make_error<StringError>(
1723 formatv("unknown module pass '{0}'", Name).str(),
1724 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001725}
1726
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001727Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1728 const PipelineElement &E, bool VerifyEachPass,
1729 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001730 auto &Name = E.Name;
1731 auto &InnerPipeline = E.InnerPipeline;
1732
1733 // First handle complex passes like the pass managers which carry pipelines.
1734 if (!InnerPipeline.empty()) {
1735 if (Name == "cgscc") {
1736 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001737 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1738 VerifyEachPass, DebugLogging))
1739 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001740 // Add the nested pass manager with the appropriate adaptor.
1741 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001742 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001743 }
1744 if (Name == "function") {
1745 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001746 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1747 VerifyEachPass, DebugLogging))
1748 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001749 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001750 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001751 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001752 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001753 if (auto Count = parseRepeatPassName(Name)) {
1754 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001755 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1756 VerifyEachPass, DebugLogging))
1757 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001758 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001759 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001760 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001761 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1762 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001763 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1764 VerifyEachPass, DebugLogging))
1765 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001766 CGPM.addPass(
1767 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001768 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001769 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001770
1771 for (auto &C : CGSCCPipelineParsingCallbacks)
1772 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001773 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001774
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001775 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001776 return make_error<StringError>(
1777 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1778 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001779 }
1780
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001781// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001782#define CGSCC_PASS(NAME, CREATE_PASS) \
1783 if (Name == NAME) { \
1784 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001785 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001786 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001787#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1788 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001789 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001790 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001791 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1792 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001793 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001794 } \
1795 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001796 CGPM.addPass(InvalidateAnalysisPass< \
1797 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001798 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001799 }
1800#include "PassRegistry.def"
1801
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001802 for (auto &C : CGSCCPipelineParsingCallbacks)
1803 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001804 return Error::success();
1805 return make_error<StringError>(
1806 formatv("unknown cgscc pass '{0}'", Name).str(),
1807 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001808}
1809
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001810Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1811 const PipelineElement &E,
1812 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001813 auto &Name = E.Name;
1814 auto &InnerPipeline = E.InnerPipeline;
1815
1816 // First handle complex passes like the pass managers which carry pipelines.
1817 if (!InnerPipeline.empty()) {
1818 if (Name == "function") {
1819 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001820 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1821 VerifyEachPass, DebugLogging))
1822 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001823 // Add the nested pass manager with the appropriate adaptor.
1824 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001825 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001826 }
1827 if (Name == "loop") {
1828 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001829 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1830 DebugLogging))
1831 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001832 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001833 FPM.addPass(
1834 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001835 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001836 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001837 if (auto Count = parseRepeatPassName(Name)) {
1838 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001839 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1840 VerifyEachPass, DebugLogging))
1841 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001842 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001843 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001844 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001845
1846 for (auto &C : FunctionPipelineParsingCallbacks)
1847 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001848 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001849
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001850 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001851 return make_error<StringError>(
1852 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1853 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001854 }
1855
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001856// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001857#define FUNCTION_PASS(NAME, CREATE_PASS) \
1858 if (Name == NAME) { \
1859 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001860 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001861 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001862#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1863 if (checkParametrizedPassName(Name, NAME)) { \
1864 auto Params = parsePassParameters(PARSER, Name, NAME); \
1865 if (!Params) \
1866 return Params.takeError(); \
1867 FPM.addPass(CREATE_PASS(Params.get())); \
1868 return Error::success(); \
1869 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001870#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1871 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001872 FPM.addPass( \
1873 RequireAnalysisPass< \
1874 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001875 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001876 } \
1877 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001878 FPM.addPass(InvalidateAnalysisPass< \
1879 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001880 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001881 }
1882#include "PassRegistry.def"
1883
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001884 for (auto &C : FunctionPipelineParsingCallbacks)
1885 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001886 return Error::success();
1887 return make_error<StringError>(
1888 formatv("unknown function pass '{0}'", Name).str(),
1889 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001890}
1891
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001892Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1893 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001894 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001895 auto &InnerPipeline = E.InnerPipeline;
1896
1897 // First handle complex passes like the pass managers which carry pipelines.
1898 if (!InnerPipeline.empty()) {
1899 if (Name == "loop") {
1900 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001901 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1902 VerifyEachPass, DebugLogging))
1903 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001904 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001905 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001906 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001907 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001908 if (auto Count = parseRepeatPassName(Name)) {
1909 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001910 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1911 VerifyEachPass, DebugLogging))
1912 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001913 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001914 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001915 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001916
1917 for (auto &C : LoopPipelineParsingCallbacks)
1918 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001919 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001920
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001921 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001922 return make_error<StringError>(
1923 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1924 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001925 }
1926
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001927// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001928#define LOOP_PASS(NAME, CREATE_PASS) \
1929 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001930 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001931 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001932 }
1933#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1934 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001935 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001936 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1937 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1938 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001939 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001940 } \
1941 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001942 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001943 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001944 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001945 }
1946#include "PassRegistry.def"
1947
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001948 for (auto &C : LoopPipelineParsingCallbacks)
1949 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001950 return Error::success();
1951 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1952 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001953}
1954
Chandler Carruthedf59962016-02-18 09:45:17 +00001955bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001956#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1957 if (Name == NAME) { \
1958 AA.registerModuleAnalysis< \
1959 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1960 return true; \
1961 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001962#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1963 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001964 AA.registerFunctionAnalysis< \
1965 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001966 return true; \
1967 }
1968#include "PassRegistry.def"
1969
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001970 for (auto &C : AAParsingCallbacks)
1971 if (C(Name, AA))
1972 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001973 return false;
1974}
1975
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001976Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001977 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001978 bool VerifyEachPass,
1979 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001980 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001981 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1982 return Err;
1983 // FIXME: No verifier support for Loop passes!
1984 }
1985 return Error::success();
1986}
1987
1988Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1989 ArrayRef<PipelineElement> Pipeline,
1990 bool VerifyEachPass,
1991 bool DebugLogging) {
1992 for (const auto &Element : Pipeline) {
1993 if (auto Err =
1994 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1995 return Err;
1996 if (VerifyEachPass)
1997 FPM.addPass(VerifierPass());
1998 }
1999 return Error::success();
2000}
2001
2002Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2003 ArrayRef<PipelineElement> Pipeline,
2004 bool VerifyEachPass,
2005 bool DebugLogging) {
2006 for (const auto &Element : Pipeline) {
2007 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2008 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002009 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002010 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002011 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002012}
2013
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002014void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2015 FunctionAnalysisManager &FAM,
2016 CGSCCAnalysisManager &CGAM,
2017 ModuleAnalysisManager &MAM) {
2018 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2019 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002020 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2021 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2022 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2023 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2024 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2025}
2026
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002027Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2028 ArrayRef<PipelineElement> Pipeline,
2029 bool VerifyEachPass,
2030 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002031 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002032 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2033 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002034 if (VerifyEachPass)
2035 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002036 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002037 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002038}
2039
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002040// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002041// FIXME: Should this routine accept a TargetMachine or require the caller to
2042// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002043Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2044 StringRef PipelineText,
2045 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002046 auto Pipeline = parsePipelineText(PipelineText);
2047 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002048 return make_error<StringError>(
2049 formatv("invalid pipeline '{0}'", PipelineText).str(),
2050 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002051
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002052 // If the first name isn't at the module layer, wrap the pipeline up
2053 // automatically.
2054 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002055
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002056 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2057 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002058 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002059 } else if (isFunctionPassName(FirstName,
2060 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002061 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002062 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002063 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002064 } else {
2065 for (auto &C : TopLevelPipelineParsingCallbacks)
2066 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002067 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002068
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002069 // Unknown pass or pipeline name!
2070 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2071 return make_error<StringError>(
2072 formatv("unknown {0} name '{1}'",
2073 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2074 .str(),
2075 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002076 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002077 }
2078
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002079 if (auto Err =
2080 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2081 return Err;
2082 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002083}
Chandler Carruthedf59962016-02-18 09:45:17 +00002084
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002085// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002086Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2087 StringRef PipelineText,
2088 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002089 auto Pipeline = parsePipelineText(PipelineText);
2090 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002091 return make_error<StringError>(
2092 formatv("invalid pipeline '{0}'", PipelineText).str(),
2093 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002094
2095 StringRef FirstName = Pipeline->front().Name;
2096 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002097 return make_error<StringError>(
2098 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2099 PipelineText)
2100 .str(),
2101 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002102
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002103 if (auto Err =
2104 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2105 return Err;
2106 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002107}
2108
2109// Primary pass pipeline description parsing routine for a \c
2110// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002111Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2112 StringRef PipelineText,
2113 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002114 auto Pipeline = parsePipelineText(PipelineText);
2115 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002116 return make_error<StringError>(
2117 formatv("invalid pipeline '{0}'", PipelineText).str(),
2118 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002119
2120 StringRef FirstName = Pipeline->front().Name;
2121 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002122 return make_error<StringError>(
2123 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2124 PipelineText)
2125 .str(),
2126 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002127
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002128 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2129 DebugLogging))
2130 return Err;
2131 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002132}
2133
2134// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002135Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2136 StringRef PipelineText,
2137 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002138 auto Pipeline = parsePipelineText(PipelineText);
2139 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002140 return make_error<StringError>(
2141 formatv("invalid pipeline '{0}'", PipelineText).str(),
2142 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002143
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002144 if (auto Err =
2145 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2146 return Err;
2147
2148 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002149}
2150
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002151Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002152 // If the pipeline just consists of the word 'default' just replace the AA
2153 // manager with our default one.
2154 if (PipelineText == "default") {
2155 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002156 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002157 }
2158
Chandler Carruthedf59962016-02-18 09:45:17 +00002159 while (!PipelineText.empty()) {
2160 StringRef Name;
2161 std::tie(Name, PipelineText) = PipelineText.split(',');
2162 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002163 return make_error<StringError>(
2164 formatv("unknown alias analysis name '{0}'", Name).str(),
2165 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002166 }
2167
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002168 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002169}