blob: de9e67ba5d7aff8ca278f97c2fbe9031d9e3bc43 [file] [log] [blame]
Chandler Carruth1ff77242015-03-07 09:02:36 +00001//===- Parsing, selection, and construction of pass pipelines -------------===//
Chandler Carruth66445382014-01-11 08:16:35 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chandler Carruth66445382014-01-11 08:16:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
9///
Chandler Carruth1ff77242015-03-07 09:02:36 +000010/// This file provides the implementation of the PassBuilder based on our
11/// static pass registry as well as related functionality. It also provides
12/// helpers to aid in analyzing, debugging, and testing passes and pass
13/// pipelines.
Chandler Carruth66445382014-01-11 08:16:35 +000014///
15//===----------------------------------------------------------------------===//
16
Chandler Carruth1ff77242015-03-07 09:02:36 +000017#include "llvm/Passes/PassBuilder.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000018#include "llvm/ADT/StringSwitch.h"
Chandler Carruth6f5770b102016-02-13 23:32:00 +000019#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth4f846a52016-02-20 03:46:03 +000020#include "llvm/Analysis/AliasAnalysisEvaluator.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000021#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthbece8d52016-02-13 23:46:24 +000022#include "llvm/Analysis/BasicAliasAnalysis.h"
Xinliang David Li28a93272016-05-05 21:13:27 +000023#include "llvm/Analysis/BlockFrequencyInfo.h"
Xinliang David Li6e5dd412016-05-05 02:59:57 +000024#include "llvm/Analysis/BranchProbabilityInfo.h"
Mehdi Amini27d23792016-09-16 16:56:30 +000025#include "llvm/Analysis/CFGPrinter.h"
George Burgess IVbfa401e2016-07-06 00:26:41 +000026#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
27#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
Chandler Carruth572e3402014-04-21 11:12:00 +000028#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruth4c660f72016-03-10 11:24:11 +000029#include "llvm/Analysis/CallGraph.h"
Michael Kupersteinde16b442016-04-18 23:55:01 +000030#include "llvm/Analysis/DemandedBits.h"
Chandler Carruth49c22192016-05-12 22:19:39 +000031#include "llvm/Analysis/DependenceAnalysis.h"
Hongbin Zheng751337f2016-02-25 17:54:15 +000032#include "llvm/Analysis/DominanceFrontier.h"
Chandler Carruth45a9c202016-03-11 09:15:11 +000033#include "llvm/Analysis/GlobalsModRef.h"
Dehao Chen1a444522016-07-16 22:51:33 +000034#include "llvm/Analysis/IVUsers.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000035#include "llvm/Analysis/LazyCallGraph.h"
Sean Silva687019f2016-06-13 22:01:25 +000036#include "llvm/Analysis/LazyValueInfo.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000037#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000038#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth61440d22016-03-10 00:55:30 +000039#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000040#include "llvm/Analysis/MemorySSA.h"
Teresa Johnsonf93b2462016-08-12 13:53:02 +000041#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000042#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawnbdbbd832018-06-28 14:13:06 +000043#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng3f978402016-02-25 17:54:07 +000044#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000045#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000046#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000047#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000048#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000049#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000050#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000051#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000052#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000053#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000054#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000055#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000056#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000057#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000058#include "llvm/IR/PassManager.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000059#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000060#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000061#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000062#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000063#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000064#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000065#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000066#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000067#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000068#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000069#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000070#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000071#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000072#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000073#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000074#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000075#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000076#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000077#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000078#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000079#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000080#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000081#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000082#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000083#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000084#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000085#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000086#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000087#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000088#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000089#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000090#include "llvm/Transforms/Instrumentation.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000091#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000092#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000093#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000094#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
95#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000096#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
Philip Pfaffe685c76d2019-01-16 09:28:01 +000097#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +000098#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Justin Bogner19b67992015-10-30 23:13:18 +000099#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000100#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000101#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000102#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000103#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000104#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000105#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000106#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000107#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000108#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000109#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000110#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000111#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000112#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000113#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000114#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000115#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000116#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000117#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000118#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000119#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000120#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000121#include "llvm/Transforms/Scalar/LoopDistribute.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000122#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000123#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000124#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000125#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000126#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000127#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000128#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000129#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000130#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000131#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000132#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000133#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000134#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000135#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000136#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000137#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000138#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000139#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000140#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000141#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000142#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000143#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000144#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000145#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000146#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000147#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000148#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000149#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000150#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000151#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000152#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000153#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000154#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000155#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000156#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000157#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000158#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000159#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000160#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000161#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000162#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000163#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000164#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000165#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000166#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000167#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000168#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000169
Chandler Carruth66445382014-01-11 08:16:35 +0000170using namespace llvm;
171
Chandler Carruth719ffe12017-02-12 05:38:04 +0000172static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
173 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000174static cl::opt<bool>
175 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
176 cl::Hidden, cl::ZeroOrMore,
177 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000178
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000179static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000180 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000181 cl::Hidden, cl::ZeroOrMore,
182 cl::desc("Run NewGVN instead of GVN"));
183
Geoff Berry3cca1da2017-06-10 15:20:03 +0000184static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000185 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
186 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000187
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000188static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000189 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
190 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000191
Davide Italianobe1b6a92017-06-03 23:18:29 +0000192static cl::opt<bool> EnableGVNSink(
193 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
194 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
195
David Green963401d2018-07-01 12:47:30 +0000196static cl::opt<bool> EnableUnrollAndJam(
197 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
198 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
199
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000200static cl::opt<bool> EnableSyntheticCounts(
201 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
202 cl::desc("Run synthetic function entry count generation "
203 "pass"));
204
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000205static Regex DefaultAliasRegex(
206 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000207
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000208static cl::opt<bool>
209 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
210 cl::desc("Enable control height reduction optimization (CHR)"));
211
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000212extern cl::opt<bool> EnableHotColdSplit;
213
Wei Mi3bcccdf2019-01-17 20:48:34 +0000214extern cl::opt<bool> FlattenedProfileUsed;
215
Chandler Carruthe3f50642016-12-22 06:59:15 +0000216static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
217 switch (Level) {
218 case PassBuilder::O0:
219 case PassBuilder::O1:
220 case PassBuilder::O2:
221 case PassBuilder::O3:
222 return false;
223
224 case PassBuilder::Os:
225 case PassBuilder::Oz:
226 return true;
227 }
228 llvm_unreachable("Invalid optimization level!");
229}
230
Chandler Carruth66445382014-01-11 08:16:35 +0000231namespace {
232
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000233/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000234struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000235 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000236 return PreservedAnalyses::all();
237 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000238 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000239};
240
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000241/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000242class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
243 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000244 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000245
246public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000247 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000248 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000249 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000250};
251
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000252/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000253struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000254 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
255 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000256 return PreservedAnalyses::all();
257 }
258 static StringRef name() { return "NoOpCGSCCPass"; }
259};
260
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000261/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000262class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
263 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000264 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000265
266public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000267 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000268 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000269 return Result();
270 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000271 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000272};
273
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000274/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000275struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000276 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000277 return PreservedAnalyses::all();
278 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000279 static StringRef name() { return "NoOpFunctionPass"; }
280};
281
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000282/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000283class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
284 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000285 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000286
287public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000288 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000289 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000290 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000291};
292
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000293/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000294struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000295 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
296 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000297 return PreservedAnalyses::all();
298 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000299 static StringRef name() { return "NoOpLoopPass"; }
300};
301
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000302/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000303class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
304 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000305 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000306
307public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000308 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000309 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
310 return Result();
311 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000312 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000313};
314
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000315AnalysisKey NoOpModuleAnalysis::Key;
316AnalysisKey NoOpCGSCCAnalysis::Key;
317AnalysisKey NoOpFunctionAnalysis::Key;
318AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000319
Chandler Carruth66445382014-01-11 08:16:35 +0000320} // End anonymous namespace.
321
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000322void PassBuilder::invokePeepholeEPCallbacks(
323 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
324 for (auto &C : PeepholeEPCallbacks)
325 C(FPM, Level);
326}
327
Chandler Carruth1ff77242015-03-07 09:02:36 +0000328void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000329#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000330 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000331#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000332
333 for (auto &C : ModuleAnalysisRegistrationCallbacks)
334 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000335}
336
Chandler Carruth1ff77242015-03-07 09:02:36 +0000337void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000338#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000339 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000340#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000341
342 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
343 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000344}
345
Chandler Carruth1ff77242015-03-07 09:02:36 +0000346void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000347#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000348 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000349#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000350
351 for (auto &C : FunctionAnalysisRegistrationCallbacks)
352 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000353}
354
Justin Bognereecc3c82016-02-25 07:23:08 +0000355void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000356#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000357 LAM.registerPass([&] { return CREATE_PASS; });
358#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000359
360 for (auto &C : LoopAnalysisRegistrationCallbacks)
361 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000362}
363
Chandler Carruthe3f50642016-12-22 06:59:15 +0000364FunctionPassManager
365PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000366 ThinLTOPhase Phase,
367 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000368 assert(Level != O0 && "Must request optimizations!");
369 FunctionPassManager FPM(DebugLogging);
370
371 // Form SSA out of local memory accesses after breaking apart aggregates into
372 // scalars.
373 FPM.addPass(SROA());
374
375 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000376 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000377
Davide Italianoc3688312017-06-01 23:08:14 +0000378 // Hoisting of scalars and load expressions.
379 if (EnableGVNHoist)
380 FPM.addPass(GVNHoistPass());
381
Davide Italianobe1b6a92017-06-03 23:18:29 +0000382 // Global value numbering based sinking.
383 if (EnableGVNSink) {
384 FPM.addPass(GVNSinkPass());
385 FPM.addPass(SimplifyCFGPass());
386 }
387
Chandler Carruthe3f50642016-12-22 06:59:15 +0000388 // Speculative execution if the target has divergent branches; otherwise nop.
389 FPM.addPass(SpeculativeExecutionPass());
390
391 // Optimize based on known information about branches, and cleanup afterward.
392 FPM.addPass(JumpThreadingPass());
393 FPM.addPass(CorrelatedValuePropagationPass());
394 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000395 if (Level == O3)
396 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000397 FPM.addPass(InstCombinePass());
398
399 if (!isOptimizingForSize(Level))
400 FPM.addPass(LibCallsShrinkWrapPass());
401
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000402 invokePeepholeEPCallbacks(FPM, Level);
403
Rong Xue1f42452017-10-23 22:21:29 +0000404 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
405 // using the size value profile. Don't perform this when optimizing for size.
406 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
407 !isOptimizingForSize(Level))
408 FPM.addPass(PGOMemOPSizeOpt());
409
Chandler Carruthe3f50642016-12-22 06:59:15 +0000410 FPM.addPass(TailCallElimPass());
411 FPM.addPass(SimplifyCFGPass());
412
413 // Form canonically associated expression trees, and simplify the trees using
414 // basic mathematical properties. For example, this will form (nearly)
415 // minimal multiplication trees.
416 FPM.addPass(ReassociatePass());
417
418 // Add the primary loop simplification pipeline.
419 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000420 // some function passes in between them. These can and should be removed
421 // and/or replaced by scheduling the loop pass equivalents in the correct
422 // positions. But those equivalent passes aren't powerful enough yet.
423 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
424 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
425 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
426 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000427 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
428
Chandler Carruth71fd2702018-05-30 02:46:45 +0000429 // Simplify the loop body. We do this initially to clean up after other loop
430 // passes run, either when iterating on a loop or on inner loops with
431 // implications on the outer loop.
432 LPM1.addPass(LoopInstSimplifyPass());
433 LPM1.addPass(LoopSimplifyCFGPass());
434
Chandler Carruthe3f50642016-12-22 06:59:15 +0000435 // Rotate Loop - disable header duplication at -Oz
436 LPM1.addPass(LoopRotatePass(Level != Oz));
437 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000438 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000439 LPM2.addPass(IndVarSimplifyPass());
440 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000441
442 for (auto &C : LateLoopOptimizationsEPCallbacks)
443 C(LPM2, Level);
444
Chandler Carruth79b733b2017-01-26 23:21:17 +0000445 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000446 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000447 // because it changes IR to makes profile annotation in back compile
448 // inaccurate.
Dehao Chen95f00302017-07-30 04:55:39 +0000449 if (Phase != ThinLTOPhase::PreLink ||
450 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnsonecd90132017-08-02 20:35:29 +0000451 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000452
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000453 for (auto &C : LoopOptimizerEndEPCallbacks)
454 C(LPM2, Level);
455
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000456 // We provide the opt remark emitter pass for LICM to use. We only need to do
457 // this once as it is immutable.
458 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000459 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000460 FPM.addPass(SimplifyCFGPass());
461 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000462 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000463
464 // Eliminate redundancies.
465 if (Level != O1) {
466 // These passes add substantial compile time so skip them at O1.
467 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000468 if (RunNewGVN)
469 FPM.addPass(NewGVNPass());
470 else
471 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000472 }
473
474 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
475 FPM.addPass(MemCpyOptPass());
476
477 // Sparse conditional constant propagation.
478 // FIXME: It isn't clear why we do this *after* loop passes rather than
479 // before...
480 FPM.addPass(SCCPPass());
481
482 // Delete dead bit computations (instcombine runs after to fold away the dead
483 // computations, and then ADCE will run later to exploit any new DCE
484 // opportunities that creates).
485 FPM.addPass(BDCEPass());
486
487 // Run instcombine after redundancy and dead bit elimination to exploit
488 // opportunities opened up by them.
489 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000490 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000491
492 // Re-consider control flow based optimizations after redundancy elimination,
493 // redo DCE, etc.
494 FPM.addPass(JumpThreadingPass());
495 FPM.addPass(CorrelatedValuePropagationPass());
496 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000497 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000498
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000499 for (auto &C : ScalarOptimizerLateEPCallbacks)
500 C(FPM, Level);
501
Chandler Carruthe3f50642016-12-22 06:59:15 +0000502 // Finally, do an expensive DCE pass to catch all the dead code exposed by
503 // the simplifications and basic cleanup after all the simplifications.
504 FPM.addPass(ADCEPass());
505 FPM.addPass(SimplifyCFGPass());
506 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000507 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000508
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000509 if (EnableCHR && Level == O3 && PGOOpt &&
510 (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty()))
511 FPM.addPass(ControlHeightReductionPass());
512
Chandler Carruthe3f50642016-12-22 06:59:15 +0000513 return FPM;
514}
515
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000516void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
517 PassBuilder::OptimizationLevel Level,
518 bool RunProfileGen,
519 std::string ProfileGenFile,
Richard Smith6c676622018-10-10 23:13:47 +0000520 std::string ProfileUseFile,
521 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000522 // Generally running simplification passes and the inliner with an high
523 // threshold results in smaller executables, but there may be cases where
524 // the size grows, so let's be conservative here and skip this simplification
525 // at -Os/Oz.
526 if (!isOptimizingForSize(Level)) {
527 InlineParams IP;
528
529 // In the old pass manager, this is a cl::opt. Should still this be one?
530 IP.DefaultThreshold = 75;
531
532 // FIXME: The hint threshold has the same value used by the regular inliner.
533 // This should probably be lowered after performance testing.
534 // FIXME: this comment is cargo culted from the old pass manager, revisit).
535 IP.HintThreshold = 325;
536
537 CGSCCPassManager CGPipeline(DebugLogging);
538
539 CGPipeline.addPass(InlinerPass(IP));
540
541 FunctionPassManager FPM;
542 FPM.addPass(SROA());
543 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
544 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
545 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000546 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000547
Davide Italiano513dfaa2017-02-13 15:26:22 +0000548 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
549
550 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
551 }
552
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000553 // Delete anything that is now dead to make sure that we don't instrument
554 // dead code. Instrumentation can end up keeping dead code around and
555 // dramatically increase code size.
556 MPM.addPass(GlobalDCEPass());
557
Davide Italiano513dfaa2017-02-13 15:26:22 +0000558 if (RunProfileGen) {
559 MPM.addPass(PGOInstrumentationGen());
560
Xinliang David Lib67530e2017-06-25 00:26:43 +0000561 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000562 FPM.addPass(
563 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000564 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
565
Davide Italiano513dfaa2017-02-13 15:26:22 +0000566 // Add the profile lowering pass.
567 InstrProfOptions Options;
568 if (!ProfileGenFile.empty())
569 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000570 Options.DoCounterPromotion = true;
Davide Italiano513dfaa2017-02-13 15:26:22 +0000571 MPM.addPass(InstrProfiling(Options));
572 }
573
574 if (!ProfileUseFile.empty())
Richard Smith6c676622018-10-10 23:13:47 +0000575 MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000576}
577
Easwaran Raman8249fac2017-06-28 13:33:49 +0000578static InlineParams
579getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
580 auto O3 = PassBuilder::O3;
581 unsigned OptLevel = Level > O3 ? 2 : Level;
582 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
583 return getInlineParams(OptLevel, SizeLevel);
584}
585
Chandler Carruthe3f50642016-12-22 06:59:15 +0000586ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000587PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000588 ThinLTOPhase Phase,
589 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000590 ModulePassManager MPM(DebugLogging);
591
Chandler Carruthe3f50642016-12-22 06:59:15 +0000592 // Do basic inference of function attributes from known properties of system
593 // libraries and other oracles.
594 MPM.addPass(InferFunctionAttrsPass());
595
596 // Create an early function pass manager to cleanup the output of the
597 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000598 FunctionPassManager EarlyFPM(DebugLogging);
599 EarlyFPM.addPass(SimplifyCFGPass());
600 EarlyFPM.addPass(SROA());
601 EarlyFPM.addPass(EarlyCSEPass());
602 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000603 if (Level == O3)
604 EarlyFPM.addPass(CallSiteSplittingPass());
605
Dehao Chen08f88312017-08-07 20:23:20 +0000606 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
607 // to convert bitcast to direct calls so that they can be inlined during the
608 // profile annotation prepration step.
609 // More details about SamplePGO design can be found in:
610 // https://research.google.com/pubs/pub45290.html
611 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
612 if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
613 Phase == ThinLTOPhase::PostLink)
614 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000615 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000616
Dehao Chen08f88312017-08-07 20:23:20 +0000617 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
618 // Annotate sample profile right after early FPM to ensure freshness of
619 // the debug info.
Wei Mi3bcccdf2019-01-17 20:48:34 +0000620 // In ThinLTO mode, when flattened profile is used, all the available
621 // profile information will be annotated in PreLink phase so there is
622 // no need to load the profile again in PostLink.
623 if (!(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink))
624 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
625 PGOOpt->ProfileRemappingFile,
626 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000627 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
628 // for the profile annotation to be accurate in the ThinLTO backend.
629 if (Phase != ThinLTOPhase::PreLink)
630 // We perform early indirect call promotion here, before globalopt.
631 // This is important for the ThinLTO backend phase because otherwise
632 // imported available_externally functions look unreferenced and are
633 // removed.
634 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
635 true));
636 }
637
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000638 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000639 // and prior to optimizing globals.
640 // FIXME: This position in the pipeline hasn't been carefully considered in
641 // years, it should be re-analyzed.
642 MPM.addPass(IPSCCPPass());
643
Matthew Simpsoncb585582017-10-25 13:40:08 +0000644 // Attach metadata to indirect call sites indicating the set of functions
645 // they may target at run-time. This should follow IPSCCP.
646 MPM.addPass(CalledValuePropagationPass());
647
Chandler Carruthe3f50642016-12-22 06:59:15 +0000648 // Optimize globals to try and fold them into constants.
649 MPM.addPass(GlobalOptPass());
650
651 // Promote any localized globals to SSA registers.
652 // FIXME: Should this instead by a run of SROA?
653 // FIXME: We should probably run instcombine and simplify-cfg afterward to
654 // delete control flows that are dead once globals have been folded to
655 // constants.
656 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
657
658 // Remove any dead arguments exposed by cleanups and constand folding
659 // globals.
660 MPM.addPass(DeadArgumentEliminationPass());
661
Vedant Kumaref1ebed2019-01-24 18:55:49 +0000662 // Split out cold code. Splitting is done before inlining because 1) the most
663 // common kinds of cold regions can (a) be found before inlining and (b) do
664 // not grow after inlining, and 2) inhibiting inlining of cold code improves
665 // code size & compile time. Split after Mem2Reg to make code model estimates
666 // more accurate, but before InstCombine to allow it to clean things up.
667 if (EnableHotColdSplit && Phase != ThinLTOPhase::PostLink)
668 MPM.addPass(HotColdSplittingPass());
669
Chandler Carruthe3f50642016-12-22 06:59:15 +0000670 // Create a small function pass pipeline to cleanup after all the global
671 // optimizations.
672 FunctionPassManager GlobalCleanupPM(DebugLogging);
673 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000674 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
675
Chandler Carruthe3f50642016-12-22 06:59:15 +0000676 GlobalCleanupPM.addPass(SimplifyCFGPass());
677 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
678
Dehao Chen89d32262017-08-02 01:28:31 +0000679 // Add all the requested passes for instrumentation PGO, if requested.
680 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
681 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
682 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
Richard Smith6c676622018-10-10 23:13:47 +0000683 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
684 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000685 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000686 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000687
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000688 // Synthesize function entry counts for non-PGO compilation.
689 if (EnableSyntheticCounts && !PGOOpt)
690 MPM.addPass(SyntheticCountsPropagation());
691
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000692 // Require the GlobalsAA analysis for the module so we can query it within
693 // the CGSCC pipeline.
694 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000695
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000696 // Require the ProfileSummaryAnalysis for the module so we can query it within
697 // the inliner pass.
698 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
699
Chandler Carruthe3f50642016-12-22 06:59:15 +0000700 // Now begin the main postorder CGSCC pipeline.
701 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
702 // manager and trying to emulate its precise behavior. Much of this doesn't
703 // make a lot of sense and we should revisit the core CGSCC structure.
704 CGSCCPassManager MainCGPipeline(DebugLogging);
705
706 // Note: historically, the PruneEH pass was run first to deduce nounwind and
707 // generally clean up exception handling overhead. It isn't clear this is
708 // valuable as the inliner doesn't currently care whether it is inlining an
709 // invoke or a call.
710
711 // Run the inliner first. The theory is that we are walking bottom-up and so
712 // the callees have already been fully optimized, and we want to inline them
713 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000714 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000715 // because it makes profile annotation in the backend inaccurate.
716 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000717 if (Phase == ThinLTOPhase::PreLink &&
718 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000719 IP.HotCallSiteThreshold = 0;
720 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000721
722 // Now deduce any function attributes based in the current code.
723 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
724
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000725 // When at O3 add argument promotion to the pass pipeline.
726 // FIXME: It isn't at all clear why this should be limited to O3.
727 if (Level == O3)
728 MainCGPipeline.addPass(ArgumentPromotionPass());
729
Chandler Carruthe3f50642016-12-22 06:59:15 +0000730 // Lastly, add the core function simplification pipeline nested inside the
731 // CGSCC walk.
732 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000733 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000734
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000735 for (auto &C : CGSCCOptimizerLateEPCallbacks)
736 C(MainCGPipeline, Level);
737
Chandler Carruth719ffe12017-02-12 05:38:04 +0000738 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
739 // to detect when we devirtualize indirect calls and iterate the SCC passes
740 // in that case to try and catch knock-on inlining or function attrs
741 // opportunities. Then we add it to the module pipeline by walking the SCCs
742 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000743 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000744 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000745 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000746
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000747 return MPM;
748}
749
750ModulePassManager
751PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
752 bool DebugLogging) {
753 ModulePassManager MPM(DebugLogging);
754
755 // Optimize globals now that the module is fully simplified.
756 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000757 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000758
Xinliang David Li126157c2017-05-22 16:41:57 +0000759 // Run partial inlining pass to partially inline functions that have
760 // large bodies.
761 if (RunPartialInlining)
762 MPM.addPass(PartialInlinerPass());
763
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000764 // Remove avail extern fns and globals definitions since we aren't compiling
765 // an object file for later LTO. For LTO we want to preserve these so they
766 // are eligible for inlining at link-time. Note if they are unreferenced they
767 // will be removed by GlobalDCE later, so this only impacts referenced
768 // available externally globals. Eventually they will be suppressed during
769 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
770 // may make globals referenced by available external functions dead and saves
771 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000772 MPM.addPass(EliminateAvailableExternallyPass());
773
774 // Do RPO function attribute inference across the module to forward-propagate
775 // attributes where applicable.
776 // FIXME: Is this really an optimization rather than a canonicalization?
777 MPM.addPass(ReversePostOrderFunctionAttrsPass());
778
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000779 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000780 // useful as the above will have inlined, DCE'ed, and function-attr
781 // propagated everything. We should at this point have a reasonably minimal
782 // and richly annotated call graph. By computing aliasing and mod/ref
783 // information for all local globals here, the late loop passes and notably
784 // the vectorizer will be able to use them to help recognize vectorizable
785 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000786 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000787
788 FunctionPassManager OptimizePM(DebugLogging);
789 OptimizePM.addPass(Float2IntPass());
790 // FIXME: We need to run some loop optimizations to re-rotate loops after
791 // simplify-cfg and others undo their rotation.
792
793 // Optimize the loop execution. These passes operate on entire loop nests
794 // rather than on each loop in an inside-out manner, and so they are actually
795 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000796
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000797 for (auto &C : VectorizerStartEPCallbacks)
798 C(OptimizePM, Level);
799
Chandler Carrutha95ff382017-01-27 00:50:21 +0000800 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000801 OptimizePM.addPass(
802 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000803
804 // Distribute loops to allow partial vectorization. I.e. isolate dependences
805 // into separate loop that would otherwise inhibit vectorization. This is
806 // currently only performed for loops marked with the metadata
807 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000808 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000809
810 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000811 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000812
Chandler Carruthbaabda92017-01-27 01:32:26 +0000813 // Eliminate loads by forwarding stores from the previous iteration to loads
814 // of the current iteration.
815 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000816
817 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000818 OptimizePM.addPass(InstCombinePass());
819
Chandler Carrutha95ff382017-01-27 00:50:21 +0000820 // Now that we've formed fast to execute loop structures, we do further
821 // optimizations. These are run afterward as they might block doing complex
822 // analyses and transforms such as what are needed for loop vectorization.
823
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000824 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
825 // GVN, loop transforms, and others have already run, so it's now better to
826 // convert to more optimized IR using more aggressive simplify CFG options.
827 // The extra sinking transform can create larger basic blocks, so do this
828 // before SLP vectorization.
829 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
830 forwardSwitchCondToPhi(true).
831 convertSwitchToLookupTable(true).
832 needCanonicalLoops(false).
833 sinkCommonInsts(true)));
834
Chandler Carruthe3f50642016-12-22 06:59:15 +0000835 // Optimize parallel scalar instruction chains into SIMD instructions.
836 OptimizePM.addPass(SLPVectorizerPass());
837
Chandler Carruthe3f50642016-12-22 06:59:15 +0000838 OptimizePM.addPass(InstCombinePass());
839
840 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000841 // execution resources of an out-of-order processor. We also then need to
842 // clean up redundancies and loop invariant code.
843 // FIXME: It would be really good to use a loop-integrated instruction
844 // combiner for cleanup here so that the unrolling and LICM can be pipelined
845 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000846 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
847 if (EnableUnrollAndJam) {
848 OptimizePM.addPass(
849 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
850 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000851 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000852 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000853 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000854 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000855 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000856
857 // Now that we've vectorized and unrolled loops, we may have more refined
858 // alignment information, try to re-derive it here.
859 OptimizePM.addPass(AlignmentFromAssumptionsPass());
860
Chandler Carrutha95ff382017-01-27 00:50:21 +0000861 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
862 // canonicalization pass that enables other optimizations. As a result,
863 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
864 // result too early.
865 OptimizePM.addPass(LoopSinkPass());
866
867 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000868 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000869
Sanjay Patel6fd43912017-09-09 13:38:18 +0000870 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
871 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
872 // flattening of blocks.
873 OptimizePM.addPass(DivRemPairsPass());
874
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000875 // LoopSink (and other loop passes since the last simplifyCFG) might have
876 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
877 OptimizePM.addPass(SimplifyCFGPass());
878
Chandler Carruthc34f7892017-11-28 11:32:31 +0000879 // Optimize PHIs by speculating around them when profitable. Note that this
880 // pass needs to be run after any PRE or similar pass as it is essentially
881 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
882 OptimizePM.addPass(SpeculateAroundPHIsPass());
883
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000884 for (auto &C : OptimizerLastEPCallbacks)
885 C(OptimizePM, Level);
886
Chandler Carrutha95ff382017-01-27 00:50:21 +0000887 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000888 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
889
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000890 MPM.addPass(CGProfilePass());
891
Chandler Carruthe3f50642016-12-22 06:59:15 +0000892 // Now we need to do some global optimization transforms.
893 // FIXME: It would seem like these should come first in the optimization
894 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
895 // ordering here.
896 MPM.addPass(GlobalDCEPass());
897 MPM.addPass(ConstantMergePass());
898
899 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000900}
901
Chandler Carruthe3f50642016-12-22 06:59:15 +0000902ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000903PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
904 bool DebugLogging) {
905 assert(Level != O0 && "Must request optimizations for the default pipeline!");
906
907 ModulePassManager MPM(DebugLogging);
908
909 // Force any function attributes we want the rest of the pipeline to observe.
910 MPM.addPass(ForceFunctionAttrsPass());
911
David Blaikie0c64f5a2018-01-23 01:25:20 +0000912 // Apply module pipeline start EP callback.
913 for (auto &C : PipelineStartEPCallbacks)
914 C(MPM);
915
Dehao Chen08f88312017-08-07 20:23:20 +0000916 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000917 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
918
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000919 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000920 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
921 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000922
923 // Now add the optimization pipeline.
924 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
925
926 return MPM;
927}
928
929ModulePassManager
930PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
931 bool DebugLogging) {
932 assert(Level != O0 && "Must request optimizations for the default pipeline!");
933
934 ModulePassManager MPM(DebugLogging);
935
936 // Force any function attributes we want the rest of the pipeline to observe.
937 MPM.addPass(ForceFunctionAttrsPass());
938
Dehao Chen08f88312017-08-07 20:23:20 +0000939 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000940 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
941
David Blaikie0c64f5a2018-01-23 01:25:20 +0000942 // Apply module pipeline start EP callback.
943 for (auto &C : PipelineStartEPCallbacks)
944 C(MPM);
945
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000946 // If we are planning to perform ThinLTO later, we don't bloat the code with
947 // unrolling/vectorization/... now. Just simplify the module as much as we
948 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000949 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
950 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000951
952 // Run partial inlining pass to partially inline functions that have
953 // large bodies.
954 // FIXME: It isn't clear whether this is really the right place to run this
955 // in ThinLTO. Because there is another canonicalization and simplification
956 // phase that will run after the thin link, running this here ends up with
957 // less information than will be available later and it may grow functions in
958 // ways that aren't beneficial.
959 if (RunPartialInlining)
960 MPM.addPass(PartialInlinerPass());
961
962 // Reduce the size of the IR as much as possible.
963 MPM.addPass(GlobalOptPass());
964
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000965 return MPM;
966}
967
Teresa Johnson28023db2018-07-19 14:51:32 +0000968ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
969 OptimizationLevel Level, bool DebugLogging,
970 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000971 ModulePassManager MPM(DebugLogging);
972
Teresa Johnson28023db2018-07-19 14:51:32 +0000973 if (ImportSummary) {
974 // These passes import type identifier resolutions for whole-program
975 // devirtualization and CFI. They must run early because other passes may
976 // disturb the specific instruction patterns that these passes look for,
977 // creating dependencies on resolutions that may not appear in the summary.
978 //
979 // For example, GVN may transform the pattern assume(type.test) appearing in
980 // two basic blocks into assume(phi(type.test, type.test)), which would
981 // transform a dependency on a WPD resolution into a dependency on a type
982 // identifier resolution for CFI.
983 //
984 // Also, WPD has access to more precise information than ICP and can
985 // devirtualize more effectively, so it should operate on the IR first.
986 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
987 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
988 }
989
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000990 // Force any function attributes we want the rest of the pipeline to observe.
991 MPM.addPass(ForceFunctionAttrsPass());
992
993 // During the ThinLTO backend phase we perform early indirect call promotion
994 // here, before globalopt. Otherwise imported available_externally functions
995 // look unreferenced and are removed.
Dehao Chen08f88312017-08-07 20:23:20 +0000996 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
997 // with SamplePGO.
Dehao Chen2f4e2e22017-08-10 05:10:32 +0000998 if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
Dehao Chen08f88312017-08-07 20:23:20 +0000999 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
1000 false /* SamplePGO */));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001001
1002 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001003 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1004 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001005
1006 // Now add the optimization pipeline.
1007 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1008
1009 return MPM;
1010}
1011
1012ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001013PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1014 bool DebugLogging) {
1015 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001016 // FIXME: We should use a customized pre-link pipeline!
Chandler Carruthe3f50642016-12-22 06:59:15 +00001017 return buildPerModuleDefaultPipeline(Level, DebugLogging);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001018}
1019
Teresa Johnson28023db2018-07-19 14:51:32 +00001020ModulePassManager
1021PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1022 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001023 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1024 ModulePassManager MPM(DebugLogging);
1025
Xin Tong642c8d32018-11-15 18:06:42 +00001026 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
1027 // Load sample profile before running the LTO optimization pipeline.
1028 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
1029 PGOOpt->ProfileRemappingFile,
1030 false /* ThinLTOPhase::PreLink */));
1031 }
1032
Davide Italiano089a9122017-01-24 00:57:39 +00001033 // Remove unused virtual tables to improve the quality of code generated by
1034 // whole-program devirtualization and bitset lowering.
1035 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001036
Davide Italiano089a9122017-01-24 00:57:39 +00001037 // Force any function attributes we want the rest of the pipeline to observe.
1038 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001039
Davide Italiano089a9122017-01-24 00:57:39 +00001040 // Do basic inference of function attributes from known properties of system
1041 // libraries and other oracles.
1042 MPM.addPass(InferFunctionAttrsPass());
1043
1044 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001045 FunctionPassManager EarlyFPM(DebugLogging);
1046 EarlyFPM.addPass(CallSiteSplittingPass());
1047 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1048
Davide Italiano089a9122017-01-24 00:57:39 +00001049 // Indirect call promotion. This should promote all the targets that are
1050 // left by the earlier promotion pass that promotes intra-module targets.
1051 // This two-step promotion is to save the compile time. For LTO, it should
1052 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001053 MPM.addPass(PGOIndirectCallPromotion(
1054 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +00001055 // Propagate constants at call sites into the functions they call. This
1056 // opens opportunities for globalopt (and inlining) by substituting function
1057 // pointers passed as arguments to direct uses of functions.
1058 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001059
1060 // Attach metadata to indirect call sites indicating the set of functions
1061 // they may target at run-time. This should follow IPSCCP.
1062 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001063 }
1064
1065 // Now deduce any function attributes based in the current code.
1066 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1067 PostOrderFunctionAttrsPass()));
1068
1069 // Do RPO function attribute inference across the module to forward-propagate
1070 // attributes where applicable.
1071 // FIXME: Is this really an optimization rather than a canonicalization?
1072 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1073
1074 // Use inragne annotations on GEP indices to split globals where beneficial.
1075 MPM.addPass(GlobalSplitPass());
1076
1077 // Run whole program optimization of virtual call when the list of callees
1078 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001079 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001080
1081 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001082 if (Level == 1) {
1083 // The LowerTypeTestsPass needs to run to lower type metadata and the
1084 // type.test intrinsics. The pass does nothing if CFI is disabled.
1085 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001086 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001087 }
Davide Italiano089a9122017-01-24 00:57:39 +00001088
1089 // Optimize globals to try and fold them into constants.
1090 MPM.addPass(GlobalOptPass());
1091
1092 // Promote any localized globals to SSA registers.
1093 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1094
1095 // Linking modules together can lead to duplicate global constant, only
1096 // keep one copy of each constant.
1097 MPM.addPass(ConstantMergePass());
1098
1099 // Remove unused arguments from functions.
1100 MPM.addPass(DeadArgumentEliminationPass());
1101
1102 // Reduce the code after globalopt and ipsccp. Both can open up significant
1103 // simplification opportunities, and both can propagate functions through
1104 // function pointers. When this happens, we often have to resolve varargs
1105 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001106 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001107 if (Level == O3)
1108 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001109 PeepholeFPM.addPass(InstCombinePass());
1110 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1111
1112 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001113
1114 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1115 // generally clean up exception handling overhead. It isn't clear this is
1116 // valuable as the inliner doesn't currently care whether it is inlining an
1117 // invoke or a call.
1118 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001119 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1120 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001121
1122 // Optimize globals again after we ran the inliner.
1123 MPM.addPass(GlobalOptPass());
1124
1125 // Garbage collect dead functions.
1126 // FIXME: Add ArgumentPromotion pass after once it's ported.
1127 MPM.addPass(GlobalDCEPass());
1128
1129 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001130 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001131 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001132 invokePeepholeEPCallbacks(FPM, Level);
1133
Davide Italiano089a9122017-01-24 00:57:39 +00001134 FPM.addPass(JumpThreadingPass());
1135
1136 // Break up allocas
1137 FPM.addPass(SROA());
1138
1139 // Run a few AA driver optimizations here and now to cleanup the code.
1140 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1141
1142 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1143 PostOrderFunctionAttrsPass()));
1144 // FIXME: here we run IP alias analysis in the legacy PM.
1145
1146 FunctionPassManager MainFPM;
1147
1148 // FIXME: once we fix LoopPass Manager, add LICM here.
1149 // FIXME: once we provide support for enabling MLSM, add it here.
1150 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001151 if (RunNewGVN)
1152 MainFPM.addPass(NewGVNPass());
1153 else
1154 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001155
1156 // Remove dead memcpy()'s.
1157 MainFPM.addPass(MemCpyOptPass());
1158
1159 // Nuke dead stores.
1160 MainFPM.addPass(DSEPass());
1161
1162 // FIXME: at this point, we run a bunch of loop passes:
1163 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1164 // loopVectorize. Enable them once the remaining issue with LPM
1165 // are sorted out.
1166
1167 MainFPM.addPass(InstCombinePass());
1168 MainFPM.addPass(SimplifyCFGPass());
1169 MainFPM.addPass(SCCPPass());
1170 MainFPM.addPass(InstCombinePass());
1171 MainFPM.addPass(BDCEPass());
1172
1173 // FIXME: We may want to run SLPVectorizer here.
1174 // After vectorization, assume intrinsics may tell us more
1175 // about pointer alignments.
1176#if 0
1177 MainFPM.add(AlignmentFromAssumptionsPass());
1178#endif
1179
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001180 // FIXME: Conditionally run LoadCombine here, after it's ported
1181 // (in case we still have this pass, given its questionable usefulness).
1182
Davide Italiano089a9122017-01-24 00:57:39 +00001183 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001184 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001185 MainFPM.addPass(JumpThreadingPass());
1186 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1187
1188 // Create a function that performs CFI checks for cross-DSO calls with
1189 // targets in the current module.
1190 MPM.addPass(CrossDSOCFIPass());
1191
1192 // Lower type metadata and the type.test intrinsic. This pass supports
1193 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1194 // to be run at link time if CFI is enabled. This pass does nothing if
1195 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001196 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001197
1198 // Add late LTO optimization passes.
1199 // Delete basic blocks, which optimization passes may have killed.
1200 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1201
1202 // Drop bodies of available eternally objects to improve GlobalDCE.
1203 MPM.addPass(EliminateAvailableExternallyPass());
1204
1205 // Now that we have optimized the program, discard unreachable functions.
1206 MPM.addPass(GlobalDCEPass());
1207
1208 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001209 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001210}
1211
Chandler Carruth060ad612016-12-23 20:38:19 +00001212AAManager PassBuilder::buildDefaultAAPipeline() {
1213 AAManager AA;
1214
1215 // The order in which these are registered determines their priority when
1216 // being queried.
1217
1218 // First we register the basic alias analysis that provides the majority of
1219 // per-function local AA logic. This is a stateless, on-demand local set of
1220 // AA techniques.
1221 AA.registerFunctionAnalysis<BasicAA>();
1222
1223 // Next we query fast, specialized alias analyses that wrap IR-embedded
1224 // information about aliasing.
1225 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1226 AA.registerFunctionAnalysis<TypeBasedAA>();
1227
1228 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001229 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1230 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001231 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001232 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001233
1234 return AA;
1235}
1236
Chandler Carruth241bf242016-08-03 07:44:48 +00001237static Optional<int> parseRepeatPassName(StringRef Name) {
1238 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1239 return None;
1240 int Count;
1241 if (Name.getAsInteger(0, Count) || Count <= 0)
1242 return None;
1243 return Count;
1244}
1245
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001246static Optional<int> parseDevirtPassName(StringRef Name) {
1247 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1248 return None;
1249 int Count;
1250 if (Name.getAsInteger(0, Count) || Count <= 0)
1251 return None;
1252 return Count;
1253}
1254
Fedor Sergeevb7871402019-01-10 10:01:53 +00001255static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1256 if (!Name.consume_front(PassName))
1257 return false;
1258 // normal pass name w/o parameters == default parameters
1259 if (Name.empty())
1260 return true;
1261 return Name.startswith("<") && Name.endswith(">");
1262}
1263
1264namespace {
1265
1266/// This performs customized parsing of pass name with parameters.
1267///
1268/// We do not need parametrization of passes in textual pipeline very often,
1269/// yet on a rare occasion ability to specify parameters right there can be
1270/// useful.
1271///
1272/// \p Name - parameterized specification of a pass from a textual pipeline
1273/// is a string in a form of :
1274/// PassName '<' parameter-list '>'
1275///
1276/// Parameter list is being parsed by the parser callable argument, \p Parser,
1277/// It takes a string-ref of parameters and returns either StringError or a
1278/// parameter list in a form of a custom parameters type, all wrapped into
1279/// Expected<> template class.
1280///
1281template <typename ParametersParseCallableT>
1282auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1283 StringRef PassName) -> decltype(Parser(StringRef{})) {
1284 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1285
1286 StringRef Params = Name;
1287 if (!Params.consume_front(PassName)) {
1288 assert(false &&
1289 "unable to strip pass name from parametrized pass specification");
1290 }
1291 if (Params.empty())
1292 return ParametersT{};
1293 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1294 assert(false && "invalid format for parametrized pass name");
1295 }
1296
1297 Expected<ParametersT> Result = Parser(Params);
1298 assert((Result || Result.template errorIsA<StringError>()) &&
1299 "Pass parameter parser can only return StringErrors.");
1300 return std::move(Result);
1301}
1302
1303/// Parser of parameters for LoopUnroll pass.
1304Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1305 LoopUnrollOptions UnrollOpts;
1306 while (!Params.empty()) {
1307 StringRef ParamName;
1308 std::tie(ParamName, Params) = Params.split(';');
1309 int OptLevel = StringSwitch<int>(ParamName)
1310 .Case("O0", 0)
1311 .Case("O1", 1)
1312 .Case("O2", 2)
1313 .Case("O3", 3)
1314 .Default(-1);
1315 if (OptLevel >= 0) {
1316 UnrollOpts.setOptLevel(OptLevel);
1317 continue;
1318 }
1319
1320 bool Enable = !ParamName.consume_front("no-");
1321 if (ParamName == "partial") {
1322 UnrollOpts.setPartial(Enable);
1323 } else if (ParamName == "peeling") {
1324 UnrollOpts.setPeeling(Enable);
1325 } else if (ParamName == "runtime") {
1326 UnrollOpts.setRuntime(Enable);
1327 } else if (ParamName == "upperbound") {
1328 UnrollOpts.setUpperBound(Enable);
1329 } else {
1330 return make_error<StringError>(
1331 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1332 inconvertibleErrorCode());
1333 }
1334 }
1335 return UnrollOpts;
1336}
1337
1338} // namespace
1339
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001340/// Tests whether a pass name starts with a valid prefix for a default pipeline
1341/// alias.
1342static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1343 return Name.startswith("default") || Name.startswith("thinlto") ||
1344 Name.startswith("lto");
1345}
1346
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001347/// Tests whether registered callbacks will accept a given pass name.
1348///
1349/// When parsing a pipeline text, the type of the outermost pipeline may be
1350/// omitted, in which case the type is automatically determined from the first
1351/// pass name in the text. This may be a name that is handled through one of the
1352/// callbacks. We check this through the oridinary parsing callbacks by setting
1353/// up a dummy PassManager in order to not force the client to also handle this
1354/// type of query.
1355template <typename PassManagerT, typename CallbacksT>
1356static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1357 if (!Callbacks.empty()) {
1358 PassManagerT DummyPM;
1359 for (auto &CB : Callbacks)
1360 if (CB(Name, DummyPM, {}))
1361 return true;
1362 }
1363 return false;
1364}
1365
1366template <typename CallbacksT>
1367static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001368 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001369 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001370 return DefaultAliasRegex.match(Name);
1371
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001372 // Explicitly handle pass manager names.
1373 if (Name == "module")
1374 return true;
1375 if (Name == "cgscc")
1376 return true;
1377 if (Name == "function")
1378 return true;
1379
Chandler Carruth241bf242016-08-03 07:44:48 +00001380 // Explicitly handle custom-parsed pass names.
1381 if (parseRepeatPassName(Name))
1382 return true;
1383
Chandler Carruth74a8a222016-06-17 07:15:29 +00001384#define MODULE_PASS(NAME, CREATE_PASS) \
1385 if (Name == NAME) \
1386 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001387#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001388 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001389 return true;
1390#include "PassRegistry.def"
1391
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001392 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001393}
1394
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001395template <typename CallbacksT>
1396static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001397 // Explicitly handle pass manager names.
1398 if (Name == "cgscc")
1399 return true;
1400 if (Name == "function")
1401 return true;
1402
Chandler Carruth241bf242016-08-03 07:44:48 +00001403 // Explicitly handle custom-parsed pass names.
1404 if (parseRepeatPassName(Name))
1405 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001406 if (parseDevirtPassName(Name))
1407 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001408
Chandler Carruth74a8a222016-06-17 07:15:29 +00001409#define CGSCC_PASS(NAME, CREATE_PASS) \
1410 if (Name == NAME) \
1411 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001412#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001413 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001414 return true;
1415#include "PassRegistry.def"
1416
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001417 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001418}
1419
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001420template <typename CallbacksT>
1421static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001422 // Explicitly handle pass manager names.
1423 if (Name == "function")
1424 return true;
1425 if (Name == "loop")
1426 return true;
1427
Chandler Carruth241bf242016-08-03 07:44:48 +00001428 // Explicitly handle custom-parsed pass names.
1429 if (parseRepeatPassName(Name))
1430 return true;
1431
Chandler Carruth74a8a222016-06-17 07:15:29 +00001432#define FUNCTION_PASS(NAME, CREATE_PASS) \
1433 if (Name == NAME) \
1434 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001435#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1436 if (checkParametrizedPassName(Name, NAME)) \
1437 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001438#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001439 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001440 return true;
1441#include "PassRegistry.def"
1442
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001443 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001444}
1445
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001446template <typename CallbacksT>
1447static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001448 // Explicitly handle pass manager names.
1449 if (Name == "loop")
1450 return true;
1451
Chandler Carruth241bf242016-08-03 07:44:48 +00001452 // Explicitly handle custom-parsed pass names.
1453 if (parseRepeatPassName(Name))
1454 return true;
1455
Chandler Carruth74a8a222016-06-17 07:15:29 +00001456#define LOOP_PASS(NAME, CREATE_PASS) \
1457 if (Name == NAME) \
1458 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001459#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1460 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1461 return true;
1462#include "PassRegistry.def"
1463
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001464 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001465}
1466
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001467Optional<std::vector<PassBuilder::PipelineElement>>
1468PassBuilder::parsePipelineText(StringRef Text) {
1469 std::vector<PipelineElement> ResultPipeline;
1470
1471 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1472 &ResultPipeline};
1473 for (;;) {
1474 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1475 size_t Pos = Text.find_first_of(",()");
1476 Pipeline.push_back({Text.substr(0, Pos), {}});
1477
1478 // If we have a single terminating name, we're done.
1479 if (Pos == Text.npos)
1480 break;
1481
1482 char Sep = Text[Pos];
1483 Text = Text.substr(Pos + 1);
1484 if (Sep == ',')
1485 // Just a name ending in a comma, continue.
1486 continue;
1487
1488 if (Sep == '(') {
1489 // Push the inner pipeline onto the stack to continue processing.
1490 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1491 continue;
1492 }
1493
1494 assert(Sep == ')' && "Bogus separator!");
1495 // When handling the close parenthesis, we greedily consume them to avoid
1496 // empty strings in the pipeline.
1497 do {
1498 // If we try to pop the outer pipeline we have unbalanced parentheses.
1499 if (PipelineStack.size() == 1)
1500 return None;
1501
1502 PipelineStack.pop_back();
1503 } while (Text.consume_front(")"));
1504
1505 // Check if we've finished parsing.
1506 if (Text.empty())
1507 break;
1508
1509 // Otherwise, the end of an inner pipeline always has to be followed by
1510 // a comma, and then we can continue.
1511 if (!Text.consume_front(","))
1512 return None;
1513 }
1514
1515 if (PipelineStack.size() > 1)
1516 // Unbalanced paretheses.
1517 return None;
1518
1519 assert(PipelineStack.back() == &ResultPipeline &&
1520 "Wrong pipeline at the bottom of the stack!");
1521 return {std::move(ResultPipeline)};
1522}
1523
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001524Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1525 const PipelineElement &E,
1526 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001527 auto &Name = E.Name;
1528 auto &InnerPipeline = E.InnerPipeline;
1529
1530 // First handle complex passes like the pass managers which carry pipelines.
1531 if (!InnerPipeline.empty()) {
1532 if (Name == "module") {
1533 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001534 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1535 VerifyEachPass, DebugLogging))
1536 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001537 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001538 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001539 }
1540 if (Name == "cgscc") {
1541 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001542 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1543 DebugLogging))
1544 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001545 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001546 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001547 }
1548 if (Name == "function") {
1549 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001550 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1551 VerifyEachPass, DebugLogging))
1552 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001553 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001554 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001555 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001556 if (auto Count = parseRepeatPassName(Name)) {
1557 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001558 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1559 VerifyEachPass, DebugLogging))
1560 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001561 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001562 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001563 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001564
1565 for (auto &C : ModulePipelineParsingCallbacks)
1566 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001567 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001568
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001569 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001570 return make_error<StringError>(
1571 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1572 inconvertibleErrorCode());
1573 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001574 }
1575
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001576 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001577 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001578 SmallVector<StringRef, 3> Matches;
1579 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001580 return make_error<StringError>(
1581 formatv("unknown default pipeline alias '{0}'", Name).str(),
1582 inconvertibleErrorCode());
1583
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001584 assert(Matches.size() == 3 && "Must capture two matched strings!");
1585
Jordan Rosef85a95f2016-07-25 18:34:51 +00001586 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001587 .Case("O0", O0)
1588 .Case("O1", O1)
1589 .Case("O2", O2)
1590 .Case("O3", O3)
1591 .Case("Os", Os)
1592 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001593 if (L == O0)
1594 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001595 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001596
1597 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001598 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001599 } else if (Matches[1] == "thinlto-pre-link") {
1600 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1601 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001602 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001603 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001604 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001605 } else {
1606 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001607 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001608 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001609 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001610 }
1611
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001612 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001613#define MODULE_PASS(NAME, CREATE_PASS) \
1614 if (Name == NAME) { \
1615 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001616 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001617 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001618#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1619 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001620 MPM.addPass( \
1621 RequireAnalysisPass< \
1622 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001623 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001624 } \
1625 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001626 MPM.addPass(InvalidateAnalysisPass< \
1627 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001628 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001629 }
1630#include "PassRegistry.def"
1631
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001632 for (auto &C : ModulePipelineParsingCallbacks)
1633 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001634 return Error::success();
1635 return make_error<StringError>(
1636 formatv("unknown module pass '{0}'", Name).str(),
1637 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001638}
1639
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001640Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1641 const PipelineElement &E, bool VerifyEachPass,
1642 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001643 auto &Name = E.Name;
1644 auto &InnerPipeline = E.InnerPipeline;
1645
1646 // First handle complex passes like the pass managers which carry pipelines.
1647 if (!InnerPipeline.empty()) {
1648 if (Name == "cgscc") {
1649 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001650 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1651 VerifyEachPass, DebugLogging))
1652 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001653 // Add the nested pass manager with the appropriate adaptor.
1654 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001655 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001656 }
1657 if (Name == "function") {
1658 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001659 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1660 VerifyEachPass, DebugLogging))
1661 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001662 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001663 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001664 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001665 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001666 if (auto Count = parseRepeatPassName(Name)) {
1667 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001668 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1669 VerifyEachPass, DebugLogging))
1670 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001671 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001672 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001673 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001674 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1675 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001676 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1677 VerifyEachPass, DebugLogging))
1678 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001679 CGPM.addPass(
1680 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001681 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001682 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001683
1684 for (auto &C : CGSCCPipelineParsingCallbacks)
1685 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001686 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001687
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001688 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001689 return make_error<StringError>(
1690 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1691 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001692 }
1693
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001694// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001695#define CGSCC_PASS(NAME, CREATE_PASS) \
1696 if (Name == NAME) { \
1697 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001698 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001699 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001700#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1701 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001702 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001703 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001704 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1705 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001706 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001707 } \
1708 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001709 CGPM.addPass(InvalidateAnalysisPass< \
1710 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001711 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001712 }
1713#include "PassRegistry.def"
1714
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001715 for (auto &C : CGSCCPipelineParsingCallbacks)
1716 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001717 return Error::success();
1718 return make_error<StringError>(
1719 formatv("unknown cgscc pass '{0}'", Name).str(),
1720 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001721}
1722
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001723Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1724 const PipelineElement &E,
1725 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001726 auto &Name = E.Name;
1727 auto &InnerPipeline = E.InnerPipeline;
1728
1729 // First handle complex passes like the pass managers which carry pipelines.
1730 if (!InnerPipeline.empty()) {
1731 if (Name == "function") {
1732 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001733 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1734 VerifyEachPass, DebugLogging))
1735 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001736 // Add the nested pass manager with the appropriate adaptor.
1737 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001738 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001739 }
1740 if (Name == "loop") {
1741 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001742 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1743 DebugLogging))
1744 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001745 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001746 FPM.addPass(
1747 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001748 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001749 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001750 if (auto Count = parseRepeatPassName(Name)) {
1751 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001752 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1753 VerifyEachPass, DebugLogging))
1754 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001755 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001756 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001757 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001758
1759 for (auto &C : FunctionPipelineParsingCallbacks)
1760 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001761 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001762
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001763 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001764 return make_error<StringError>(
1765 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1766 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001767 }
1768
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001769// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001770#define FUNCTION_PASS(NAME, CREATE_PASS) \
1771 if (Name == NAME) { \
1772 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001773 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001774 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001775#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1776 if (checkParametrizedPassName(Name, NAME)) { \
1777 auto Params = parsePassParameters(PARSER, Name, NAME); \
1778 if (!Params) \
1779 return Params.takeError(); \
1780 FPM.addPass(CREATE_PASS(Params.get())); \
1781 return Error::success(); \
1782 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001783#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1784 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001785 FPM.addPass( \
1786 RequireAnalysisPass< \
1787 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001788 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001789 } \
1790 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001791 FPM.addPass(InvalidateAnalysisPass< \
1792 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001793 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001794 }
1795#include "PassRegistry.def"
1796
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001797 for (auto &C : FunctionPipelineParsingCallbacks)
1798 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001799 return Error::success();
1800 return make_error<StringError>(
1801 formatv("unknown function pass '{0}'", Name).str(),
1802 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001803}
1804
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001805Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1806 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001807 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001808 auto &InnerPipeline = E.InnerPipeline;
1809
1810 // First handle complex passes like the pass managers which carry pipelines.
1811 if (!InnerPipeline.empty()) {
1812 if (Name == "loop") {
1813 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001814 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1815 VerifyEachPass, DebugLogging))
1816 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001817 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001818 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001819 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001820 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001821 if (auto Count = parseRepeatPassName(Name)) {
1822 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001823 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1824 VerifyEachPass, DebugLogging))
1825 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001826 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001827 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001828 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001829
1830 for (auto &C : LoopPipelineParsingCallbacks)
1831 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001832 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001833
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001834 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001835 return make_error<StringError>(
1836 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1837 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001838 }
1839
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001840// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001841#define LOOP_PASS(NAME, CREATE_PASS) \
1842 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001843 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001844 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001845 }
1846#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1847 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001848 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001849 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1850 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1851 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001852 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001853 } \
1854 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001855 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001856 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001857 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001858 }
1859#include "PassRegistry.def"
1860
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001861 for (auto &C : LoopPipelineParsingCallbacks)
1862 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001863 return Error::success();
1864 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1865 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001866}
1867
Chandler Carruthedf59962016-02-18 09:45:17 +00001868bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001869#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1870 if (Name == NAME) { \
1871 AA.registerModuleAnalysis< \
1872 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1873 return true; \
1874 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001875#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1876 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001877 AA.registerFunctionAnalysis< \
1878 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001879 return true; \
1880 }
1881#include "PassRegistry.def"
1882
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001883 for (auto &C : AAParsingCallbacks)
1884 if (C(Name, AA))
1885 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001886 return false;
1887}
1888
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001889Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001890 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001891 bool VerifyEachPass,
1892 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001893 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001894 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1895 return Err;
1896 // FIXME: No verifier support for Loop passes!
1897 }
1898 return Error::success();
1899}
1900
1901Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1902 ArrayRef<PipelineElement> Pipeline,
1903 bool VerifyEachPass,
1904 bool DebugLogging) {
1905 for (const auto &Element : Pipeline) {
1906 if (auto Err =
1907 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1908 return Err;
1909 if (VerifyEachPass)
1910 FPM.addPass(VerifierPass());
1911 }
1912 return Error::success();
1913}
1914
1915Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1916 ArrayRef<PipelineElement> Pipeline,
1917 bool VerifyEachPass,
1918 bool DebugLogging) {
1919 for (const auto &Element : Pipeline) {
1920 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1921 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001922 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001923 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001924 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00001925}
1926
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001927void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1928 FunctionAnalysisManager &FAM,
1929 CGSCCAnalysisManager &CGAM,
1930 ModuleAnalysisManager &MAM) {
1931 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1932 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001933 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1934 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1935 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1936 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1937 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1938}
1939
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001940Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1941 ArrayRef<PipelineElement> Pipeline,
1942 bool VerifyEachPass,
1943 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001944 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001945 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1946 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001947 if (VerifyEachPass)
1948 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001949 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001950 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001951}
1952
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001953// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00001954// FIXME: Should this routine accept a TargetMachine or require the caller to
1955// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001956Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1957 StringRef PipelineText,
1958 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001959 auto Pipeline = parsePipelineText(PipelineText);
1960 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001961 return make_error<StringError>(
1962 formatv("invalid pipeline '{0}'", PipelineText).str(),
1963 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001964
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001965 // If the first name isn't at the module layer, wrap the pipeline up
1966 // automatically.
1967 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00001968
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001969 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1970 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001971 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001972 } else if (isFunctionPassName(FirstName,
1973 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001974 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001975 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001976 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001977 } else {
1978 for (auto &C : TopLevelPipelineParsingCallbacks)
1979 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001980 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001981
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001982 // Unknown pass or pipeline name!
1983 auto &InnerPipeline = Pipeline->front().InnerPipeline;
1984 return make_error<StringError>(
1985 formatv("unknown {0} name '{1}'",
1986 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1987 .str(),
1988 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001989 }
Chandler Carruth572e3402014-04-21 11:12:00 +00001990 }
1991
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001992 if (auto Err =
1993 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1994 return Err;
1995 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001996}
Chandler Carruthedf59962016-02-18 09:45:17 +00001997
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001998// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001999Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2000 StringRef PipelineText,
2001 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002002 auto Pipeline = parsePipelineText(PipelineText);
2003 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002004 return make_error<StringError>(
2005 formatv("invalid pipeline '{0}'", PipelineText).str(),
2006 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002007
2008 StringRef FirstName = Pipeline->front().Name;
2009 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002010 return make_error<StringError>(
2011 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2012 PipelineText)
2013 .str(),
2014 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002015
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002016 if (auto Err =
2017 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2018 return Err;
2019 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002020}
2021
2022// Primary pass pipeline description parsing routine for a \c
2023// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002024Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2025 StringRef PipelineText,
2026 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002027 auto Pipeline = parsePipelineText(PipelineText);
2028 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002029 return make_error<StringError>(
2030 formatv("invalid pipeline '{0}'", PipelineText).str(),
2031 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002032
2033 StringRef FirstName = Pipeline->front().Name;
2034 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002035 return make_error<StringError>(
2036 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2037 PipelineText)
2038 .str(),
2039 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002040
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002041 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2042 DebugLogging))
2043 return Err;
2044 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002045}
2046
2047// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002048Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2049 StringRef PipelineText,
2050 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002051 auto Pipeline = parsePipelineText(PipelineText);
2052 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002053 return make_error<StringError>(
2054 formatv("invalid pipeline '{0}'", PipelineText).str(),
2055 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002056
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002057 if (auto Err =
2058 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2059 return Err;
2060
2061 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002062}
2063
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002064Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002065 // If the pipeline just consists of the word 'default' just replace the AA
2066 // manager with our default one.
2067 if (PipelineText == "default") {
2068 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002069 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002070 }
2071
Chandler Carruthedf59962016-02-18 09:45:17 +00002072 while (!PipelineText.empty()) {
2073 StringRef Name;
2074 std::tie(Name, PipelineText) = PipelineText.split(',');
2075 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002076 return make_error<StringError>(
2077 formatv("unknown alias analysis name '{0}'", Name).str(),
2078 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002079 }
2080
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002081 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002082}