blob: 045c8541c0d040093ebf1424002ebb17abfab025 [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 Kazantsevb9e65cb2018-12-07 14:39:46 +0000136#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000137#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000138#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000139#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000140#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000141#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000142#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000143#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000144#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000145#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000146#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000147#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000148#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000149#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000150#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000151#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000152#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000153#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000154#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000155#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000156#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000157#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000158#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000159#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000160#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000161#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000162#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000163#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000164#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000165#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000166#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000167#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000168
Chandler Carruth66445382014-01-11 08:16:35 +0000169using namespace llvm;
170
Chandler Carruth719ffe12017-02-12 05:38:04 +0000171static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
172 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000173static cl::opt<bool>
174 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
175 cl::Hidden, cl::ZeroOrMore,
176 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000177
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000178static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000179 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000180 cl::Hidden, cl::ZeroOrMore,
181 cl::desc("Run NewGVN instead of GVN"));
182
Geoff Berry3cca1da2017-06-10 15:20:03 +0000183static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000184 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
185 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000186
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000187static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000188 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
189 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000190
Davide Italianobe1b6a92017-06-03 23:18:29 +0000191static cl::opt<bool> EnableGVNSink(
192 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
193 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
194
David Green963401d2018-07-01 12:47:30 +0000195static cl::opt<bool> EnableUnrollAndJam(
196 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
197 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
198
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000199static cl::opt<bool> EnableSyntheticCounts(
200 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
201 cl::desc("Run synthetic function entry count generation "
202 "pass"));
203
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000204static Regex DefaultAliasRegex(
205 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000206
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000207static cl::opt<bool>
208 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
209 cl::desc("Enable control height reduction optimization (CHR)"));
210
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000211extern cl::opt<bool> EnableHotColdSplit;
212
Wei Mi3bcccdf2019-01-17 20:48:34 +0000213extern cl::opt<bool> FlattenedProfileUsed;
214
Chandler Carruthe3f50642016-12-22 06:59:15 +0000215static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
216 switch (Level) {
217 case PassBuilder::O0:
218 case PassBuilder::O1:
219 case PassBuilder::O2:
220 case PassBuilder::O3:
221 return false;
222
223 case PassBuilder::Os:
224 case PassBuilder::Oz:
225 return true;
226 }
227 llvm_unreachable("Invalid optimization level!");
228}
229
Chandler Carruth66445382014-01-11 08:16:35 +0000230namespace {
231
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000232/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000233struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000234 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000235 return PreservedAnalyses::all();
236 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000237 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000238};
239
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000240/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000241class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
242 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000243 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000244
245public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000246 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000247 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000248 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000249};
250
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000251/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000252struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000253 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
254 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000255 return PreservedAnalyses::all();
256 }
257 static StringRef name() { return "NoOpCGSCCPass"; }
258};
259
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000260/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000261class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
262 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000263 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000264
265public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000266 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000267 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000268 return Result();
269 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000270 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000271};
272
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000273/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000274struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000275 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000276 return PreservedAnalyses::all();
277 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000278 static StringRef name() { return "NoOpFunctionPass"; }
279};
280
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000281/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000282class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
283 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000284 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000285
286public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000287 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000288 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000289 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000290};
291
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000292/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000293struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000294 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
295 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000296 return PreservedAnalyses::all();
297 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000298 static StringRef name() { return "NoOpLoopPass"; }
299};
300
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000301/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000302class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
303 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000304 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000305
306public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000307 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000308 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
309 return Result();
310 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000311 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000312};
313
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000314AnalysisKey NoOpModuleAnalysis::Key;
315AnalysisKey NoOpCGSCCAnalysis::Key;
316AnalysisKey NoOpFunctionAnalysis::Key;
317AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000318
Chandler Carruth66445382014-01-11 08:16:35 +0000319} // End anonymous namespace.
320
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000321void PassBuilder::invokePeepholeEPCallbacks(
322 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
323 for (auto &C : PeepholeEPCallbacks)
324 C(FPM, Level);
325}
326
Chandler Carruth1ff77242015-03-07 09:02:36 +0000327void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000328#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000329 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000330#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000331
332 for (auto &C : ModuleAnalysisRegistrationCallbacks)
333 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000334}
335
Chandler Carruth1ff77242015-03-07 09:02:36 +0000336void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000337#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000338 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000339#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000340
341 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
342 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000343}
344
Chandler Carruth1ff77242015-03-07 09:02:36 +0000345void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000346#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000347 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000348#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000349
350 for (auto &C : FunctionAnalysisRegistrationCallbacks)
351 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000352}
353
Justin Bognereecc3c82016-02-25 07:23:08 +0000354void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000355#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000356 LAM.registerPass([&] { return CREATE_PASS; });
357#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000358
359 for (auto &C : LoopAnalysisRegistrationCallbacks)
360 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000361}
362
Chandler Carruthe3f50642016-12-22 06:59:15 +0000363FunctionPassManager
364PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000365 ThinLTOPhase Phase,
366 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000367 assert(Level != O0 && "Must request optimizations!");
368 FunctionPassManager FPM(DebugLogging);
369
370 // Form SSA out of local memory accesses after breaking apart aggregates into
371 // scalars.
372 FPM.addPass(SROA());
373
374 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000375 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000376
Davide Italianoc3688312017-06-01 23:08:14 +0000377 // Hoisting of scalars and load expressions.
378 if (EnableGVNHoist)
379 FPM.addPass(GVNHoistPass());
380
Davide Italianobe1b6a92017-06-03 23:18:29 +0000381 // Global value numbering based sinking.
382 if (EnableGVNSink) {
383 FPM.addPass(GVNSinkPass());
384 FPM.addPass(SimplifyCFGPass());
385 }
386
Chandler Carruthe3f50642016-12-22 06:59:15 +0000387 // Speculative execution if the target has divergent branches; otherwise nop.
388 FPM.addPass(SpeculativeExecutionPass());
389
390 // Optimize based on known information about branches, and cleanup afterward.
391 FPM.addPass(JumpThreadingPass());
392 FPM.addPass(CorrelatedValuePropagationPass());
393 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000394 if (Level == O3)
395 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000396 FPM.addPass(InstCombinePass());
397
398 if (!isOptimizingForSize(Level))
399 FPM.addPass(LibCallsShrinkWrapPass());
400
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000401 invokePeepholeEPCallbacks(FPM, Level);
402
Rong Xue1f42452017-10-23 22:21:29 +0000403 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
404 // using the size value profile. Don't perform this when optimizing for size.
405 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
406 !isOptimizingForSize(Level))
407 FPM.addPass(PGOMemOPSizeOpt());
408
Chandler Carruthe3f50642016-12-22 06:59:15 +0000409 FPM.addPass(TailCallElimPass());
410 FPM.addPass(SimplifyCFGPass());
411
412 // Form canonically associated expression trees, and simplify the trees using
413 // basic mathematical properties. For example, this will form (nearly)
414 // minimal multiplication trees.
415 FPM.addPass(ReassociatePass());
416
417 // Add the primary loop simplification pipeline.
418 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000419 // some function passes in between them. These can and should be removed
420 // and/or replaced by scheduling the loop pass equivalents in the correct
421 // positions. But those equivalent passes aren't powerful enough yet.
422 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
423 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
424 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
425 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000426 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
427
Chandler Carruth71fd2702018-05-30 02:46:45 +0000428 // Simplify the loop body. We do this initially to clean up after other loop
429 // passes run, either when iterating on a loop or on inner loops with
430 // implications on the outer loop.
431 LPM1.addPass(LoopInstSimplifyPass());
432 LPM1.addPass(LoopSimplifyCFGPass());
433
Chandler Carruthe3f50642016-12-22 06:59:15 +0000434 // Rotate Loop - disable header duplication at -Oz
435 LPM1.addPass(LoopRotatePass(Level != Oz));
436 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000437 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000438 LPM2.addPass(IndVarSimplifyPass());
439 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000440
441 for (auto &C : LateLoopOptimizationsEPCallbacks)
442 C(LPM2, Level);
443
Chandler Carruth79b733b2017-01-26 23:21:17 +0000444 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000445 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000446 // because it changes IR to makes profile annotation in back compile
447 // inaccurate.
Dehao Chen95f00302017-07-30 04:55:39 +0000448 if (Phase != ThinLTOPhase::PreLink ||
449 !PGOOpt || PGOOpt->SampleProfileFile.empty())
Teresa Johnsonecd90132017-08-02 20:35:29 +0000450 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000451
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000452 for (auto &C : LoopOptimizerEndEPCallbacks)
453 C(LPM2, Level);
454
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000455 // We provide the opt remark emitter pass for LICM to use. We only need to do
456 // this once as it is immutable.
457 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000458 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000459 FPM.addPass(SimplifyCFGPass());
460 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000461 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000462
463 // Eliminate redundancies.
464 if (Level != O1) {
465 // These passes add substantial compile time so skip them at O1.
466 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000467 if (RunNewGVN)
468 FPM.addPass(NewGVNPass());
469 else
470 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000471 }
472
473 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
474 FPM.addPass(MemCpyOptPass());
475
476 // Sparse conditional constant propagation.
477 // FIXME: It isn't clear why we do this *after* loop passes rather than
478 // before...
479 FPM.addPass(SCCPPass());
480
481 // Delete dead bit computations (instcombine runs after to fold away the dead
482 // computations, and then ADCE will run later to exploit any new DCE
483 // opportunities that creates).
484 FPM.addPass(BDCEPass());
485
486 // Run instcombine after redundancy and dead bit elimination to exploit
487 // opportunities opened up by them.
488 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000489 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000490
491 // Re-consider control flow based optimizations after redundancy elimination,
492 // redo DCE, etc.
493 FPM.addPass(JumpThreadingPass());
494 FPM.addPass(CorrelatedValuePropagationPass());
495 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000496 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000497
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000498 for (auto &C : ScalarOptimizerLateEPCallbacks)
499 C(FPM, Level);
500
Chandler Carruthe3f50642016-12-22 06:59:15 +0000501 // Finally, do an expensive DCE pass to catch all the dead code exposed by
502 // the simplifications and basic cleanup after all the simplifications.
503 FPM.addPass(ADCEPass());
504 FPM.addPass(SimplifyCFGPass());
505 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000506 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000507
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000508 if (EnableCHR && Level == O3 && PGOOpt &&
509 (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty()))
510 FPM.addPass(ControlHeightReductionPass());
511
Chandler Carruthe3f50642016-12-22 06:59:15 +0000512 return FPM;
513}
514
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000515void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
516 PassBuilder::OptimizationLevel Level,
517 bool RunProfileGen,
518 std::string ProfileGenFile,
Richard Smith6c676622018-10-10 23:13:47 +0000519 std::string ProfileUseFile,
520 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000521 // Generally running simplification passes and the inliner with an high
522 // threshold results in smaller executables, but there may be cases where
523 // the size grows, so let's be conservative here and skip this simplification
524 // at -Os/Oz.
525 if (!isOptimizingForSize(Level)) {
526 InlineParams IP;
527
528 // In the old pass manager, this is a cl::opt. Should still this be one?
529 IP.DefaultThreshold = 75;
530
531 // FIXME: The hint threshold has the same value used by the regular inliner.
532 // This should probably be lowered after performance testing.
533 // FIXME: this comment is cargo culted from the old pass manager, revisit).
534 IP.HintThreshold = 325;
535
536 CGSCCPassManager CGPipeline(DebugLogging);
537
538 CGPipeline.addPass(InlinerPass(IP));
539
540 FunctionPassManager FPM;
541 FPM.addPass(SROA());
542 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
543 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
544 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000545 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000546
Davide Italiano513dfaa2017-02-13 15:26:22 +0000547 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
548
549 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
550 }
551
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000552 // Delete anything that is now dead to make sure that we don't instrument
553 // dead code. Instrumentation can end up keeping dead code around and
554 // dramatically increase code size.
555 MPM.addPass(GlobalDCEPass());
556
Davide Italiano513dfaa2017-02-13 15:26:22 +0000557 if (RunProfileGen) {
558 MPM.addPass(PGOInstrumentationGen());
559
Xinliang David Lib67530e2017-06-25 00:26:43 +0000560 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000561 FPM.addPass(
562 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000563 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
564
Davide Italiano513dfaa2017-02-13 15:26:22 +0000565 // Add the profile lowering pass.
566 InstrProfOptions Options;
567 if (!ProfileGenFile.empty())
568 Options.InstrProfileOutput = ProfileGenFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000569 Options.DoCounterPromotion = true;
Davide Italiano513dfaa2017-02-13 15:26:22 +0000570 MPM.addPass(InstrProfiling(Options));
571 }
572
573 if (!ProfileUseFile.empty())
Richard Smith6c676622018-10-10 23:13:47 +0000574 MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000575}
576
Easwaran Raman8249fac2017-06-28 13:33:49 +0000577static InlineParams
578getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
579 auto O3 = PassBuilder::O3;
580 unsigned OptLevel = Level > O3 ? 2 : Level;
581 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
582 return getInlineParams(OptLevel, SizeLevel);
583}
584
Chandler Carruthe3f50642016-12-22 06:59:15 +0000585ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000586PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000587 ThinLTOPhase Phase,
588 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000589 ModulePassManager MPM(DebugLogging);
590
Chandler Carruthe3f50642016-12-22 06:59:15 +0000591 // Do basic inference of function attributes from known properties of system
592 // libraries and other oracles.
593 MPM.addPass(InferFunctionAttrsPass());
594
595 // Create an early function pass manager to cleanup the output of the
596 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000597 FunctionPassManager EarlyFPM(DebugLogging);
598 EarlyFPM.addPass(SimplifyCFGPass());
599 EarlyFPM.addPass(SROA());
600 EarlyFPM.addPass(EarlyCSEPass());
601 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000602 if (Level == O3)
603 EarlyFPM.addPass(CallSiteSplittingPass());
604
Dehao Chen08f88312017-08-07 20:23:20 +0000605 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
606 // to convert bitcast to direct calls so that they can be inlined during the
607 // profile annotation prepration step.
608 // More details about SamplePGO design can be found in:
609 // https://research.google.com/pubs/pub45290.html
610 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
611 if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
612 Phase == ThinLTOPhase::PostLink)
613 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000614 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000615
Dehao Chen08f88312017-08-07 20:23:20 +0000616 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
617 // Annotate sample profile right after early FPM to ensure freshness of
618 // the debug info.
Wei Mi3bcccdf2019-01-17 20:48:34 +0000619 // In ThinLTO mode, when flattened profile is used, all the available
620 // profile information will be annotated in PreLink phase so there is
621 // no need to load the profile again in PostLink.
622 if (!(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink))
623 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
624 PGOOpt->ProfileRemappingFile,
625 Phase == ThinLTOPhase::PreLink));
Dehao Chen08f88312017-08-07 20:23:20 +0000626 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
627 // for the profile annotation to be accurate in the ThinLTO backend.
628 if (Phase != ThinLTOPhase::PreLink)
629 // We perform early indirect call promotion here, before globalopt.
630 // This is important for the ThinLTO backend phase because otherwise
631 // imported available_externally functions look unreferenced and are
632 // removed.
633 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
634 true));
635 }
636
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000637 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000638 // and prior to optimizing globals.
639 // FIXME: This position in the pipeline hasn't been carefully considered in
640 // years, it should be re-analyzed.
641 MPM.addPass(IPSCCPPass());
642
Matthew Simpsoncb585582017-10-25 13:40:08 +0000643 // Attach metadata to indirect call sites indicating the set of functions
644 // they may target at run-time. This should follow IPSCCP.
645 MPM.addPass(CalledValuePropagationPass());
646
Chandler Carruthe3f50642016-12-22 06:59:15 +0000647 // Optimize globals to try and fold them into constants.
648 MPM.addPass(GlobalOptPass());
649
650 // Promote any localized globals to SSA registers.
651 // FIXME: Should this instead by a run of SROA?
652 // FIXME: We should probably run instcombine and simplify-cfg afterward to
653 // delete control flows that are dead once globals have been folded to
654 // constants.
655 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
656
657 // Remove any dead arguments exposed by cleanups and constand folding
658 // globals.
659 MPM.addPass(DeadArgumentEliminationPass());
660
Vedant Kumaref1ebed2019-01-24 18:55:49 +0000661 // Split out cold code. Splitting is done before inlining because 1) the most
662 // common kinds of cold regions can (a) be found before inlining and (b) do
663 // not grow after inlining, and 2) inhibiting inlining of cold code improves
664 // code size & compile time. Split after Mem2Reg to make code model estimates
665 // more accurate, but before InstCombine to allow it to clean things up.
666 if (EnableHotColdSplit && Phase != ThinLTOPhase::PostLink)
667 MPM.addPass(HotColdSplittingPass());
668
Chandler Carruthe3f50642016-12-22 06:59:15 +0000669 // Create a small function pass pipeline to cleanup after all the global
670 // optimizations.
671 FunctionPassManager GlobalCleanupPM(DebugLogging);
672 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000673 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
674
Chandler Carruthe3f50642016-12-22 06:59:15 +0000675 GlobalCleanupPM.addPass(SimplifyCFGPass());
676 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
677
Dehao Chen89d32262017-08-02 01:28:31 +0000678 // Add all the requested passes for instrumentation PGO, if requested.
679 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
680 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
681 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
Richard Smith6c676622018-10-10 23:13:47 +0000682 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
683 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000684 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000685 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000686
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000687 // Synthesize function entry counts for non-PGO compilation.
688 if (EnableSyntheticCounts && !PGOOpt)
689 MPM.addPass(SyntheticCountsPropagation());
690
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000691 // Require the GlobalsAA analysis for the module so we can query it within
692 // the CGSCC pipeline.
693 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000694
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000695 // Require the ProfileSummaryAnalysis for the module so we can query it within
696 // the inliner pass.
697 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
698
Chandler Carruthe3f50642016-12-22 06:59:15 +0000699 // Now begin the main postorder CGSCC pipeline.
700 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
701 // manager and trying to emulate its precise behavior. Much of this doesn't
702 // make a lot of sense and we should revisit the core CGSCC structure.
703 CGSCCPassManager MainCGPipeline(DebugLogging);
704
705 // Note: historically, the PruneEH pass was run first to deduce nounwind and
706 // generally clean up exception handling overhead. It isn't clear this is
707 // valuable as the inliner doesn't currently care whether it is inlining an
708 // invoke or a call.
709
710 // Run the inliner first. The theory is that we are walking bottom-up and so
711 // the callees have already been fully optimized, and we want to inline them
712 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000713 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000714 // because it makes profile annotation in the backend inaccurate.
715 InlineParams IP = getInlineParamsFromOptLevel(Level);
Dehao Chen95f00302017-07-30 04:55:39 +0000716 if (Phase == ThinLTOPhase::PreLink &&
717 PGOOpt && !PGOOpt->SampleProfileFile.empty())
Dehao Chen3a9861422017-07-07 20:53:10 +0000718 IP.HotCallSiteThreshold = 0;
719 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000720
721 // Now deduce any function attributes based in the current code.
722 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
723
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000724 // When at O3 add argument promotion to the pass pipeline.
725 // FIXME: It isn't at all clear why this should be limited to O3.
726 if (Level == O3)
727 MainCGPipeline.addPass(ArgumentPromotionPass());
728
Chandler Carruthe3f50642016-12-22 06:59:15 +0000729 // Lastly, add the core function simplification pipeline nested inside the
730 // CGSCC walk.
731 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000732 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000733
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000734 for (auto &C : CGSCCOptimizerLateEPCallbacks)
735 C(MainCGPipeline, Level);
736
Chandler Carruth719ffe12017-02-12 05:38:04 +0000737 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
738 // to detect when we devirtualize indirect calls and iterate the SCC passes
739 // in that case to try and catch knock-on inlining or function attrs
740 // opportunities. Then we add it to the module pipeline by walking the SCCs
741 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000742 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000743 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000744 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000745
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000746 return MPM;
747}
748
749ModulePassManager
750PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
751 bool DebugLogging) {
752 ModulePassManager MPM(DebugLogging);
753
754 // Optimize globals now that the module is fully simplified.
755 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000756 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000757
Xinliang David Li126157c2017-05-22 16:41:57 +0000758 // Run partial inlining pass to partially inline functions that have
759 // large bodies.
760 if (RunPartialInlining)
761 MPM.addPass(PartialInlinerPass());
762
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000763 // Remove avail extern fns and globals definitions since we aren't compiling
764 // an object file for later LTO. For LTO we want to preserve these so they
765 // are eligible for inlining at link-time. Note if they are unreferenced they
766 // will be removed by GlobalDCE later, so this only impacts referenced
767 // available externally globals. Eventually they will be suppressed during
768 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
769 // may make globals referenced by available external functions dead and saves
770 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000771 MPM.addPass(EliminateAvailableExternallyPass());
772
773 // Do RPO function attribute inference across the module to forward-propagate
774 // attributes where applicable.
775 // FIXME: Is this really an optimization rather than a canonicalization?
776 MPM.addPass(ReversePostOrderFunctionAttrsPass());
777
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000778 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000779 // useful as the above will have inlined, DCE'ed, and function-attr
780 // propagated everything. We should at this point have a reasonably minimal
781 // and richly annotated call graph. By computing aliasing and mod/ref
782 // information for all local globals here, the late loop passes and notably
783 // the vectorizer will be able to use them to help recognize vectorizable
784 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000785 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000786
787 FunctionPassManager OptimizePM(DebugLogging);
788 OptimizePM.addPass(Float2IntPass());
789 // FIXME: We need to run some loop optimizations to re-rotate loops after
790 // simplify-cfg and others undo their rotation.
791
792 // Optimize the loop execution. These passes operate on entire loop nests
793 // rather than on each loop in an inside-out manner, and so they are actually
794 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000795
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000796 for (auto &C : VectorizerStartEPCallbacks)
797 C(OptimizePM, Level);
798
Chandler Carrutha95ff382017-01-27 00:50:21 +0000799 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000800 OptimizePM.addPass(
801 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000802
803 // Distribute loops to allow partial vectorization. I.e. isolate dependences
804 // into separate loop that would otherwise inhibit vectorization. This is
805 // currently only performed for loops marked with the metadata
806 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000807 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000808
809 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000810 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000811
Chandler Carruthbaabda92017-01-27 01:32:26 +0000812 // Eliminate loads by forwarding stores from the previous iteration to loads
813 // of the current iteration.
814 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000815
816 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000817 OptimizePM.addPass(InstCombinePass());
818
Chandler Carrutha95ff382017-01-27 00:50:21 +0000819 // Now that we've formed fast to execute loop structures, we do further
820 // optimizations. These are run afterward as they might block doing complex
821 // analyses and transforms such as what are needed for loop vectorization.
822
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000823 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
824 // GVN, loop transforms, and others have already run, so it's now better to
825 // convert to more optimized IR using more aggressive simplify CFG options.
826 // The extra sinking transform can create larger basic blocks, so do this
827 // before SLP vectorization.
828 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
829 forwardSwitchCondToPhi(true).
830 convertSwitchToLookupTable(true).
831 needCanonicalLoops(false).
832 sinkCommonInsts(true)));
833
Chandler Carruthe3f50642016-12-22 06:59:15 +0000834 // Optimize parallel scalar instruction chains into SIMD instructions.
835 OptimizePM.addPass(SLPVectorizerPass());
836
Chandler Carruthe3f50642016-12-22 06:59:15 +0000837 OptimizePM.addPass(InstCombinePass());
838
839 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000840 // execution resources of an out-of-order processor. We also then need to
841 // clean up redundancies and loop invariant code.
842 // FIXME: It would be really good to use a loop-integrated instruction
843 // combiner for cleanup here so that the unrolling and LICM can be pipelined
844 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000845 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
846 if (EnableUnrollAndJam) {
847 OptimizePM.addPass(
848 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
849 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000850 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000851 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000852 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000853 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000854 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000855
856 // Now that we've vectorized and unrolled loops, we may have more refined
857 // alignment information, try to re-derive it here.
858 OptimizePM.addPass(AlignmentFromAssumptionsPass());
859
Chandler Carrutha95ff382017-01-27 00:50:21 +0000860 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
861 // canonicalization pass that enables other optimizations. As a result,
862 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
863 // result too early.
864 OptimizePM.addPass(LoopSinkPass());
865
866 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000867 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000868
Sanjay Patel6fd43912017-09-09 13:38:18 +0000869 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
870 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
871 // flattening of blocks.
872 OptimizePM.addPass(DivRemPairsPass());
873
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000874 // LoopSink (and other loop passes since the last simplifyCFG) might have
875 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
876 OptimizePM.addPass(SimplifyCFGPass());
877
Chandler Carruthc34f7892017-11-28 11:32:31 +0000878 // Optimize PHIs by speculating around them when profitable. Note that this
879 // pass needs to be run after any PRE or similar pass as it is essentially
880 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
881 OptimizePM.addPass(SpeculateAroundPHIsPass());
882
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000883 for (auto &C : OptimizerLastEPCallbacks)
884 C(OptimizePM, Level);
885
Chandler Carrutha95ff382017-01-27 00:50:21 +0000886 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000887 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
888
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000889 MPM.addPass(CGProfilePass());
890
Chandler Carruthe3f50642016-12-22 06:59:15 +0000891 // Now we need to do some global optimization transforms.
892 // FIXME: It would seem like these should come first in the optimization
893 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
894 // ordering here.
895 MPM.addPass(GlobalDCEPass());
896 MPM.addPass(ConstantMergePass());
897
898 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000899}
900
Chandler Carruthe3f50642016-12-22 06:59:15 +0000901ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000902PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
903 bool DebugLogging) {
904 assert(Level != O0 && "Must request optimizations for the default pipeline!");
905
906 ModulePassManager MPM(DebugLogging);
907
908 // Force any function attributes we want the rest of the pipeline to observe.
909 MPM.addPass(ForceFunctionAttrsPass());
910
David Blaikie0c64f5a2018-01-23 01:25:20 +0000911 // Apply module pipeline start EP callback.
912 for (auto &C : PipelineStartEPCallbacks)
913 C(MPM);
914
Dehao Chen08f88312017-08-07 20:23:20 +0000915 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000916 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
917
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000918 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000919 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
920 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000921
922 // Now add the optimization pipeline.
923 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
924
925 return MPM;
926}
927
928ModulePassManager
929PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
930 bool DebugLogging) {
931 assert(Level != O0 && "Must request optimizations for the default pipeline!");
932
933 ModulePassManager MPM(DebugLogging);
934
935 // Force any function attributes we want the rest of the pipeline to observe.
936 MPM.addPass(ForceFunctionAttrsPass());
937
Dehao Chen08f88312017-08-07 20:23:20 +0000938 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000939 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
940
David Blaikie0c64f5a2018-01-23 01:25:20 +0000941 // Apply module pipeline start EP callback.
942 for (auto &C : PipelineStartEPCallbacks)
943 C(MPM);
944
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000945 // If we are planning to perform ThinLTO later, we don't bloat the code with
946 // unrolling/vectorization/... now. Just simplify the module as much as we
947 // can.
Dehao Chen95f00302017-07-30 04:55:39 +0000948 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
949 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000950
951 // Run partial inlining pass to partially inline functions that have
952 // large bodies.
953 // FIXME: It isn't clear whether this is really the right place to run this
954 // in ThinLTO. Because there is another canonicalization and simplification
955 // phase that will run after the thin link, running this here ends up with
956 // less information than will be available later and it may grow functions in
957 // ways that aren't beneficial.
958 if (RunPartialInlining)
959 MPM.addPass(PartialInlinerPass());
960
961 // Reduce the size of the IR as much as possible.
962 MPM.addPass(GlobalOptPass());
963
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000964 return MPM;
965}
966
Teresa Johnson28023db2018-07-19 14:51:32 +0000967ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
968 OptimizationLevel Level, bool DebugLogging,
969 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000970 ModulePassManager MPM(DebugLogging);
971
Teresa Johnson28023db2018-07-19 14:51:32 +0000972 if (ImportSummary) {
973 // These passes import type identifier resolutions for whole-program
974 // devirtualization and CFI. They must run early because other passes may
975 // disturb the specific instruction patterns that these passes look for,
976 // creating dependencies on resolutions that may not appear in the summary.
977 //
978 // For example, GVN may transform the pattern assume(type.test) appearing in
979 // two basic blocks into assume(phi(type.test, type.test)), which would
980 // transform a dependency on a WPD resolution into a dependency on a type
981 // identifier resolution for CFI.
982 //
983 // Also, WPD has access to more precise information than ICP and can
984 // devirtualize more effectively, so it should operate on the IR first.
985 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
986 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
987 }
988
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000989 // Force any function attributes we want the rest of the pipeline to observe.
990 MPM.addPass(ForceFunctionAttrsPass());
991
992 // During the ThinLTO backend phase we perform early indirect call promotion
993 // here, before globalopt. Otherwise imported available_externally functions
994 // look unreferenced and are removed.
Dehao Chen08f88312017-08-07 20:23:20 +0000995 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
996 // with SamplePGO.
Dehao Chen2f4e2e22017-08-10 05:10:32 +0000997 if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
Dehao Chen08f88312017-08-07 20:23:20 +0000998 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
999 false /* SamplePGO */));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001000
1001 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001002 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1003 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001004
1005 // Now add the optimization pipeline.
1006 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1007
1008 return MPM;
1009}
1010
1011ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001012PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1013 bool DebugLogging) {
1014 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001015 // FIXME: We should use a customized pre-link pipeline!
Chandler Carruthe3f50642016-12-22 06:59:15 +00001016 return buildPerModuleDefaultPipeline(Level, DebugLogging);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001017}
1018
Teresa Johnson28023db2018-07-19 14:51:32 +00001019ModulePassManager
1020PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1021 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001022 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1023 ModulePassManager MPM(DebugLogging);
1024
Xin Tong642c8d32018-11-15 18:06:42 +00001025 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
1026 // Load sample profile before running the LTO optimization pipeline.
1027 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
1028 PGOOpt->ProfileRemappingFile,
1029 false /* ThinLTOPhase::PreLink */));
1030 }
1031
Davide Italiano089a9122017-01-24 00:57:39 +00001032 // Remove unused virtual tables to improve the quality of code generated by
1033 // whole-program devirtualization and bitset lowering.
1034 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001035
Davide Italiano089a9122017-01-24 00:57:39 +00001036 // Force any function attributes we want the rest of the pipeline to observe.
1037 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001038
Davide Italiano089a9122017-01-24 00:57:39 +00001039 // Do basic inference of function attributes from known properties of system
1040 // libraries and other oracles.
1041 MPM.addPass(InferFunctionAttrsPass());
1042
1043 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001044 FunctionPassManager EarlyFPM(DebugLogging);
1045 EarlyFPM.addPass(CallSiteSplittingPass());
1046 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1047
Davide Italiano089a9122017-01-24 00:57:39 +00001048 // Indirect call promotion. This should promote all the targets that are
1049 // left by the earlier promotion pass that promotes intra-module targets.
1050 // This two-step promotion is to save the compile time. For LTO, it should
1051 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001052 MPM.addPass(PGOIndirectCallPromotion(
1053 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
Davide Italiano089a9122017-01-24 00:57:39 +00001054 // Propagate constants at call sites into the functions they call. This
1055 // opens opportunities for globalopt (and inlining) by substituting function
1056 // pointers passed as arguments to direct uses of functions.
1057 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001058
1059 // Attach metadata to indirect call sites indicating the set of functions
1060 // they may target at run-time. This should follow IPSCCP.
1061 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001062 }
1063
1064 // Now deduce any function attributes based in the current code.
1065 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1066 PostOrderFunctionAttrsPass()));
1067
1068 // Do RPO function attribute inference across the module to forward-propagate
1069 // attributes where applicable.
1070 // FIXME: Is this really an optimization rather than a canonicalization?
1071 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1072
1073 // Use inragne annotations on GEP indices to split globals where beneficial.
1074 MPM.addPass(GlobalSplitPass());
1075
1076 // Run whole program optimization of virtual call when the list of callees
1077 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001078 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001079
1080 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001081 if (Level == 1) {
1082 // The LowerTypeTestsPass needs to run to lower type metadata and the
1083 // type.test intrinsics. The pass does nothing if CFI is disabled.
1084 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001085 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001086 }
Davide Italiano089a9122017-01-24 00:57:39 +00001087
1088 // Optimize globals to try and fold them into constants.
1089 MPM.addPass(GlobalOptPass());
1090
1091 // Promote any localized globals to SSA registers.
1092 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1093
1094 // Linking modules together can lead to duplicate global constant, only
1095 // keep one copy of each constant.
1096 MPM.addPass(ConstantMergePass());
1097
1098 // Remove unused arguments from functions.
1099 MPM.addPass(DeadArgumentEliminationPass());
1100
1101 // Reduce the code after globalopt and ipsccp. Both can open up significant
1102 // simplification opportunities, and both can propagate functions through
1103 // function pointers. When this happens, we often have to resolve varargs
1104 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001105 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001106 if (Level == O3)
1107 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001108 PeepholeFPM.addPass(InstCombinePass());
1109 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1110
1111 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001112
1113 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1114 // generally clean up exception handling overhead. It isn't clear this is
1115 // valuable as the inliner doesn't currently care whether it is inlining an
1116 // invoke or a call.
1117 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001118 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1119 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001120
1121 // Optimize globals again after we ran the inliner.
1122 MPM.addPass(GlobalOptPass());
1123
1124 // Garbage collect dead functions.
1125 // FIXME: Add ArgumentPromotion pass after once it's ported.
1126 MPM.addPass(GlobalDCEPass());
1127
1128 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001129 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001130 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001131 invokePeepholeEPCallbacks(FPM, Level);
1132
Davide Italiano089a9122017-01-24 00:57:39 +00001133 FPM.addPass(JumpThreadingPass());
1134
1135 // Break up allocas
1136 FPM.addPass(SROA());
1137
1138 // Run a few AA driver optimizations here and now to cleanup the code.
1139 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1140
1141 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1142 PostOrderFunctionAttrsPass()));
1143 // FIXME: here we run IP alias analysis in the legacy PM.
1144
1145 FunctionPassManager MainFPM;
1146
1147 // FIXME: once we fix LoopPass Manager, add LICM here.
1148 // FIXME: once we provide support for enabling MLSM, add it here.
1149 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001150 if (RunNewGVN)
1151 MainFPM.addPass(NewGVNPass());
1152 else
1153 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001154
1155 // Remove dead memcpy()'s.
1156 MainFPM.addPass(MemCpyOptPass());
1157
1158 // Nuke dead stores.
1159 MainFPM.addPass(DSEPass());
1160
1161 // FIXME: at this point, we run a bunch of loop passes:
1162 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1163 // loopVectorize. Enable them once the remaining issue with LPM
1164 // are sorted out.
1165
1166 MainFPM.addPass(InstCombinePass());
1167 MainFPM.addPass(SimplifyCFGPass());
1168 MainFPM.addPass(SCCPPass());
1169 MainFPM.addPass(InstCombinePass());
1170 MainFPM.addPass(BDCEPass());
1171
1172 // FIXME: We may want to run SLPVectorizer here.
1173 // After vectorization, assume intrinsics may tell us more
1174 // about pointer alignments.
1175#if 0
1176 MainFPM.add(AlignmentFromAssumptionsPass());
1177#endif
1178
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001179 // FIXME: Conditionally run LoadCombine here, after it's ported
1180 // (in case we still have this pass, given its questionable usefulness).
1181
Davide Italiano089a9122017-01-24 00:57:39 +00001182 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001183 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001184 MainFPM.addPass(JumpThreadingPass());
1185 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1186
1187 // Create a function that performs CFI checks for cross-DSO calls with
1188 // targets in the current module.
1189 MPM.addPass(CrossDSOCFIPass());
1190
1191 // Lower type metadata and the type.test intrinsic. This pass supports
1192 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1193 // to be run at link time if CFI is enabled. This pass does nothing if
1194 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001195 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001196
1197 // Add late LTO optimization passes.
1198 // Delete basic blocks, which optimization passes may have killed.
1199 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1200
1201 // Drop bodies of available eternally objects to improve GlobalDCE.
1202 MPM.addPass(EliminateAvailableExternallyPass());
1203
1204 // Now that we have optimized the program, discard unreachable functions.
1205 MPM.addPass(GlobalDCEPass());
1206
1207 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001208 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001209}
1210
Chandler Carruth060ad612016-12-23 20:38:19 +00001211AAManager PassBuilder::buildDefaultAAPipeline() {
1212 AAManager AA;
1213
1214 // The order in which these are registered determines their priority when
1215 // being queried.
1216
1217 // First we register the basic alias analysis that provides the majority of
1218 // per-function local AA logic. This is a stateless, on-demand local set of
1219 // AA techniques.
1220 AA.registerFunctionAnalysis<BasicAA>();
1221
1222 // Next we query fast, specialized alias analyses that wrap IR-embedded
1223 // information about aliasing.
1224 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1225 AA.registerFunctionAnalysis<TypeBasedAA>();
1226
1227 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001228 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1229 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001230 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001231 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001232
1233 return AA;
1234}
1235
Chandler Carruth241bf242016-08-03 07:44:48 +00001236static Optional<int> parseRepeatPassName(StringRef Name) {
1237 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1238 return None;
1239 int Count;
1240 if (Name.getAsInteger(0, Count) || Count <= 0)
1241 return None;
1242 return Count;
1243}
1244
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001245static Optional<int> parseDevirtPassName(StringRef Name) {
1246 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1247 return None;
1248 int Count;
1249 if (Name.getAsInteger(0, Count) || Count <= 0)
1250 return None;
1251 return Count;
1252}
1253
Fedor Sergeevb7871402019-01-10 10:01:53 +00001254static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1255 if (!Name.consume_front(PassName))
1256 return false;
1257 // normal pass name w/o parameters == default parameters
1258 if (Name.empty())
1259 return true;
1260 return Name.startswith("<") && Name.endswith(">");
1261}
1262
1263namespace {
1264
1265/// This performs customized parsing of pass name with parameters.
1266///
1267/// We do not need parametrization of passes in textual pipeline very often,
1268/// yet on a rare occasion ability to specify parameters right there can be
1269/// useful.
1270///
1271/// \p Name - parameterized specification of a pass from a textual pipeline
1272/// is a string in a form of :
1273/// PassName '<' parameter-list '>'
1274///
1275/// Parameter list is being parsed by the parser callable argument, \p Parser,
1276/// It takes a string-ref of parameters and returns either StringError or a
1277/// parameter list in a form of a custom parameters type, all wrapped into
1278/// Expected<> template class.
1279///
1280template <typename ParametersParseCallableT>
1281auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1282 StringRef PassName) -> decltype(Parser(StringRef{})) {
1283 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1284
1285 StringRef Params = Name;
1286 if (!Params.consume_front(PassName)) {
1287 assert(false &&
1288 "unable to strip pass name from parametrized pass specification");
1289 }
1290 if (Params.empty())
1291 return ParametersT{};
1292 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1293 assert(false && "invalid format for parametrized pass name");
1294 }
1295
1296 Expected<ParametersT> Result = Parser(Params);
1297 assert((Result || Result.template errorIsA<StringError>()) &&
1298 "Pass parameter parser can only return StringErrors.");
1299 return std::move(Result);
1300}
1301
1302/// Parser of parameters for LoopUnroll pass.
1303Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1304 LoopUnrollOptions UnrollOpts;
1305 while (!Params.empty()) {
1306 StringRef ParamName;
1307 std::tie(ParamName, Params) = Params.split(';');
1308 int OptLevel = StringSwitch<int>(ParamName)
1309 .Case("O0", 0)
1310 .Case("O1", 1)
1311 .Case("O2", 2)
1312 .Case("O3", 3)
1313 .Default(-1);
1314 if (OptLevel >= 0) {
1315 UnrollOpts.setOptLevel(OptLevel);
1316 continue;
1317 }
1318
1319 bool Enable = !ParamName.consume_front("no-");
1320 if (ParamName == "partial") {
1321 UnrollOpts.setPartial(Enable);
1322 } else if (ParamName == "peeling") {
1323 UnrollOpts.setPeeling(Enable);
1324 } else if (ParamName == "runtime") {
1325 UnrollOpts.setRuntime(Enable);
1326 } else if (ParamName == "upperbound") {
1327 UnrollOpts.setUpperBound(Enable);
1328 } else {
1329 return make_error<StringError>(
1330 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1331 inconvertibleErrorCode());
1332 }
1333 }
1334 return UnrollOpts;
1335}
1336
1337} // namespace
1338
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001339/// Tests whether a pass name starts with a valid prefix for a default pipeline
1340/// alias.
1341static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1342 return Name.startswith("default") || Name.startswith("thinlto") ||
1343 Name.startswith("lto");
1344}
1345
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001346/// Tests whether registered callbacks will accept a given pass name.
1347///
1348/// When parsing a pipeline text, the type of the outermost pipeline may be
1349/// omitted, in which case the type is automatically determined from the first
1350/// pass name in the text. This may be a name that is handled through one of the
1351/// callbacks. We check this through the oridinary parsing callbacks by setting
1352/// up a dummy PassManager in order to not force the client to also handle this
1353/// type of query.
1354template <typename PassManagerT, typename CallbacksT>
1355static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1356 if (!Callbacks.empty()) {
1357 PassManagerT DummyPM;
1358 for (auto &CB : Callbacks)
1359 if (CB(Name, DummyPM, {}))
1360 return true;
1361 }
1362 return false;
1363}
1364
1365template <typename CallbacksT>
1366static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001367 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001368 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001369 return DefaultAliasRegex.match(Name);
1370
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001371 // Explicitly handle pass manager names.
1372 if (Name == "module")
1373 return true;
1374 if (Name == "cgscc")
1375 return true;
1376 if (Name == "function")
1377 return true;
1378
Chandler Carruth241bf242016-08-03 07:44:48 +00001379 // Explicitly handle custom-parsed pass names.
1380 if (parseRepeatPassName(Name))
1381 return true;
1382
Chandler Carruth74a8a222016-06-17 07:15:29 +00001383#define MODULE_PASS(NAME, CREATE_PASS) \
1384 if (Name == NAME) \
1385 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001386#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001387 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001388 return true;
1389#include "PassRegistry.def"
1390
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001391 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001392}
1393
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001394template <typename CallbacksT>
1395static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001396 // Explicitly handle pass manager names.
1397 if (Name == "cgscc")
1398 return true;
1399 if (Name == "function")
1400 return true;
1401
Chandler Carruth241bf242016-08-03 07:44:48 +00001402 // Explicitly handle custom-parsed pass names.
1403 if (parseRepeatPassName(Name))
1404 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001405 if (parseDevirtPassName(Name))
1406 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001407
Chandler Carruth74a8a222016-06-17 07:15:29 +00001408#define CGSCC_PASS(NAME, CREATE_PASS) \
1409 if (Name == NAME) \
1410 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001411#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001412 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001413 return true;
1414#include "PassRegistry.def"
1415
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001416 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001417}
1418
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001419template <typename CallbacksT>
1420static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001421 // Explicitly handle pass manager names.
1422 if (Name == "function")
1423 return true;
1424 if (Name == "loop")
1425 return true;
1426
Chandler Carruth241bf242016-08-03 07:44:48 +00001427 // Explicitly handle custom-parsed pass names.
1428 if (parseRepeatPassName(Name))
1429 return true;
1430
Chandler Carruth74a8a222016-06-17 07:15:29 +00001431#define FUNCTION_PASS(NAME, CREATE_PASS) \
1432 if (Name == NAME) \
1433 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001434#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1435 if (checkParametrizedPassName(Name, NAME)) \
1436 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001437#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001438 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001439 return true;
1440#include "PassRegistry.def"
1441
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001442 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001443}
1444
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001445template <typename CallbacksT>
1446static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001447 // Explicitly handle pass manager names.
1448 if (Name == "loop")
1449 return true;
1450
Chandler Carruth241bf242016-08-03 07:44:48 +00001451 // Explicitly handle custom-parsed pass names.
1452 if (parseRepeatPassName(Name))
1453 return true;
1454
Chandler Carruth74a8a222016-06-17 07:15:29 +00001455#define LOOP_PASS(NAME, CREATE_PASS) \
1456 if (Name == NAME) \
1457 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001458#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1459 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1460 return true;
1461#include "PassRegistry.def"
1462
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001463 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001464}
1465
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001466Optional<std::vector<PassBuilder::PipelineElement>>
1467PassBuilder::parsePipelineText(StringRef Text) {
1468 std::vector<PipelineElement> ResultPipeline;
1469
1470 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1471 &ResultPipeline};
1472 for (;;) {
1473 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1474 size_t Pos = Text.find_first_of(",()");
1475 Pipeline.push_back({Text.substr(0, Pos), {}});
1476
1477 // If we have a single terminating name, we're done.
1478 if (Pos == Text.npos)
1479 break;
1480
1481 char Sep = Text[Pos];
1482 Text = Text.substr(Pos + 1);
1483 if (Sep == ',')
1484 // Just a name ending in a comma, continue.
1485 continue;
1486
1487 if (Sep == '(') {
1488 // Push the inner pipeline onto the stack to continue processing.
1489 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1490 continue;
1491 }
1492
1493 assert(Sep == ')' && "Bogus separator!");
1494 // When handling the close parenthesis, we greedily consume them to avoid
1495 // empty strings in the pipeline.
1496 do {
1497 // If we try to pop the outer pipeline we have unbalanced parentheses.
1498 if (PipelineStack.size() == 1)
1499 return None;
1500
1501 PipelineStack.pop_back();
1502 } while (Text.consume_front(")"));
1503
1504 // Check if we've finished parsing.
1505 if (Text.empty())
1506 break;
1507
1508 // Otherwise, the end of an inner pipeline always has to be followed by
1509 // a comma, and then we can continue.
1510 if (!Text.consume_front(","))
1511 return None;
1512 }
1513
1514 if (PipelineStack.size() > 1)
1515 // Unbalanced paretheses.
1516 return None;
1517
1518 assert(PipelineStack.back() == &ResultPipeline &&
1519 "Wrong pipeline at the bottom of the stack!");
1520 return {std::move(ResultPipeline)};
1521}
1522
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001523Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1524 const PipelineElement &E,
1525 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001526 auto &Name = E.Name;
1527 auto &InnerPipeline = E.InnerPipeline;
1528
1529 // First handle complex passes like the pass managers which carry pipelines.
1530 if (!InnerPipeline.empty()) {
1531 if (Name == "module") {
1532 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001533 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1534 VerifyEachPass, DebugLogging))
1535 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001536 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001537 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001538 }
1539 if (Name == "cgscc") {
1540 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001541 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1542 DebugLogging))
1543 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001544 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001545 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001546 }
1547 if (Name == "function") {
1548 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001549 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1550 VerifyEachPass, DebugLogging))
1551 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001552 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001553 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001554 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001555 if (auto Count = parseRepeatPassName(Name)) {
1556 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001557 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1558 VerifyEachPass, DebugLogging))
1559 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001560 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001561 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001562 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001563
1564 for (auto &C : ModulePipelineParsingCallbacks)
1565 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001566 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001567
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001568 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001569 return make_error<StringError>(
1570 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1571 inconvertibleErrorCode());
1572 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001573 }
1574
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001575 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001576 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001577 SmallVector<StringRef, 3> Matches;
1578 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001579 return make_error<StringError>(
1580 formatv("unknown default pipeline alias '{0}'", Name).str(),
1581 inconvertibleErrorCode());
1582
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001583 assert(Matches.size() == 3 && "Must capture two matched strings!");
1584
Jordan Rosef85a95f2016-07-25 18:34:51 +00001585 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001586 .Case("O0", O0)
1587 .Case("O1", O1)
1588 .Case("O2", O2)
1589 .Case("O3", O3)
1590 .Case("Os", Os)
1591 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001592 if (L == O0)
1593 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001594 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001595
1596 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001597 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001598 } else if (Matches[1] == "thinlto-pre-link") {
1599 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1600 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001601 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001602 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001603 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001604 } else {
1605 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001606 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001607 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001608 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001609 }
1610
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001611 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001612#define MODULE_PASS(NAME, CREATE_PASS) \
1613 if (Name == NAME) { \
1614 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001615 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001616 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001617#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1618 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001619 MPM.addPass( \
1620 RequireAnalysisPass< \
1621 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001622 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001623 } \
1624 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001625 MPM.addPass(InvalidateAnalysisPass< \
1626 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001627 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001628 }
1629#include "PassRegistry.def"
1630
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001631 for (auto &C : ModulePipelineParsingCallbacks)
1632 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001633 return Error::success();
1634 return make_error<StringError>(
1635 formatv("unknown module pass '{0}'", Name).str(),
1636 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001637}
1638
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001639Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1640 const PipelineElement &E, bool VerifyEachPass,
1641 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001642 auto &Name = E.Name;
1643 auto &InnerPipeline = E.InnerPipeline;
1644
1645 // First handle complex passes like the pass managers which carry pipelines.
1646 if (!InnerPipeline.empty()) {
1647 if (Name == "cgscc") {
1648 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001649 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1650 VerifyEachPass, DebugLogging))
1651 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001652 // Add the nested pass manager with the appropriate adaptor.
1653 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001654 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001655 }
1656 if (Name == "function") {
1657 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001658 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1659 VerifyEachPass, DebugLogging))
1660 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001661 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001662 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001663 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001664 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001665 if (auto Count = parseRepeatPassName(Name)) {
1666 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001667 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1668 VerifyEachPass, DebugLogging))
1669 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001670 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001671 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001672 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001673 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1674 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001675 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1676 VerifyEachPass, DebugLogging))
1677 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001678 CGPM.addPass(
1679 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001680 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001681 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001682
1683 for (auto &C : CGSCCPipelineParsingCallbacks)
1684 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001685 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001686
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001687 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001688 return make_error<StringError>(
1689 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1690 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001691 }
1692
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001693// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001694#define CGSCC_PASS(NAME, CREATE_PASS) \
1695 if (Name == NAME) { \
1696 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001697 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001698 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001699#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1700 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001701 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001702 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001703 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1704 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001705 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001706 } \
1707 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001708 CGPM.addPass(InvalidateAnalysisPass< \
1709 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001710 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001711 }
1712#include "PassRegistry.def"
1713
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001714 for (auto &C : CGSCCPipelineParsingCallbacks)
1715 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001716 return Error::success();
1717 return make_error<StringError>(
1718 formatv("unknown cgscc pass '{0}'", Name).str(),
1719 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001720}
1721
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001722Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1723 const PipelineElement &E,
1724 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001725 auto &Name = E.Name;
1726 auto &InnerPipeline = E.InnerPipeline;
1727
1728 // First handle complex passes like the pass managers which carry pipelines.
1729 if (!InnerPipeline.empty()) {
1730 if (Name == "function") {
1731 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001732 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1733 VerifyEachPass, DebugLogging))
1734 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001735 // Add the nested pass manager with the appropriate adaptor.
1736 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001737 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001738 }
1739 if (Name == "loop") {
1740 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001741 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1742 DebugLogging))
1743 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001744 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001745 FPM.addPass(
1746 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001747 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001748 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001749 if (auto Count = parseRepeatPassName(Name)) {
1750 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001751 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1752 VerifyEachPass, DebugLogging))
1753 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001754 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001755 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001756 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001757
1758 for (auto &C : FunctionPipelineParsingCallbacks)
1759 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001760 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001761
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001762 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001763 return make_error<StringError>(
1764 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1765 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001766 }
1767
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001768// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001769#define FUNCTION_PASS(NAME, CREATE_PASS) \
1770 if (Name == NAME) { \
1771 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001772 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001773 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001774#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1775 if (checkParametrizedPassName(Name, NAME)) { \
1776 auto Params = parsePassParameters(PARSER, Name, NAME); \
1777 if (!Params) \
1778 return Params.takeError(); \
1779 FPM.addPass(CREATE_PASS(Params.get())); \
1780 return Error::success(); \
1781 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001782#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1783 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001784 FPM.addPass( \
1785 RequireAnalysisPass< \
1786 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001787 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001788 } \
1789 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001790 FPM.addPass(InvalidateAnalysisPass< \
1791 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001792 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001793 }
1794#include "PassRegistry.def"
1795
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001796 for (auto &C : FunctionPipelineParsingCallbacks)
1797 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001798 return Error::success();
1799 return make_error<StringError>(
1800 formatv("unknown function pass '{0}'", Name).str(),
1801 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001802}
1803
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001804Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1805 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001806 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001807 auto &InnerPipeline = E.InnerPipeline;
1808
1809 // First handle complex passes like the pass managers which carry pipelines.
1810 if (!InnerPipeline.empty()) {
1811 if (Name == "loop") {
1812 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001813 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1814 VerifyEachPass, DebugLogging))
1815 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001816 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001817 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001818 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001819 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001820 if (auto Count = parseRepeatPassName(Name)) {
1821 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001822 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1823 VerifyEachPass, DebugLogging))
1824 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001825 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001826 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001827 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001828
1829 for (auto &C : LoopPipelineParsingCallbacks)
1830 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001831 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001832
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001833 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001834 return make_error<StringError>(
1835 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1836 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001837 }
1838
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001839// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001840#define LOOP_PASS(NAME, CREATE_PASS) \
1841 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001842 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001843 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001844 }
1845#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1846 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001847 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001848 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1849 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1850 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001851 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001852 } \
1853 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001854 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001855 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001856 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001857 }
1858#include "PassRegistry.def"
1859
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001860 for (auto &C : LoopPipelineParsingCallbacks)
1861 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001862 return Error::success();
1863 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1864 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00001865}
1866
Chandler Carruthedf59962016-02-18 09:45:17 +00001867bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00001868#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1869 if (Name == NAME) { \
1870 AA.registerModuleAnalysis< \
1871 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1872 return true; \
1873 }
Chandler Carruthedf59962016-02-18 09:45:17 +00001874#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1875 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00001876 AA.registerFunctionAnalysis< \
1877 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00001878 return true; \
1879 }
1880#include "PassRegistry.def"
1881
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001882 for (auto &C : AAParsingCallbacks)
1883 if (C(Name, AA))
1884 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00001885 return false;
1886}
1887
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001888Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001889 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00001890 bool VerifyEachPass,
1891 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001892 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001893 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1894 return Err;
1895 // FIXME: No verifier support for Loop passes!
1896 }
1897 return Error::success();
1898}
1899
1900Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1901 ArrayRef<PipelineElement> Pipeline,
1902 bool VerifyEachPass,
1903 bool DebugLogging) {
1904 for (const auto &Element : Pipeline) {
1905 if (auto Err =
1906 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1907 return Err;
1908 if (VerifyEachPass)
1909 FPM.addPass(VerifierPass());
1910 }
1911 return Error::success();
1912}
1913
1914Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1915 ArrayRef<PipelineElement> Pipeline,
1916 bool VerifyEachPass,
1917 bool DebugLogging) {
1918 for (const auto &Element : Pipeline) {
1919 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1920 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001921 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00001922 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001923 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00001924}
1925
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001926void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1927 FunctionAnalysisManager &FAM,
1928 CGSCCAnalysisManager &CGAM,
1929 ModuleAnalysisManager &MAM) {
1930 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1931 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00001932 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1933 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1934 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1935 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1936 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1937}
1938
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001939Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1940 ArrayRef<PipelineElement> Pipeline,
1941 bool VerifyEachPass,
1942 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001943 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001944 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1945 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001946 if (VerifyEachPass)
1947 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00001948 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001949 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001950}
1951
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001952// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00001953// FIXME: Should this routine accept a TargetMachine or require the caller to
1954// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001955Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1956 StringRef PipelineText,
1957 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001958 auto Pipeline = parsePipelineText(PipelineText);
1959 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001960 return make_error<StringError>(
1961 formatv("invalid pipeline '{0}'", PipelineText).str(),
1962 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001963
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001964 // If the first name isn't at the module layer, wrap the pipeline up
1965 // automatically.
1966 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00001967
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001968 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1969 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001970 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001971 } else if (isFunctionPassName(FirstName,
1972 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001973 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001974 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001975 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001976 } else {
1977 for (auto &C : TopLevelPipelineParsingCallbacks)
1978 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001979 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001980
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001981 // Unknown pass or pipeline name!
1982 auto &InnerPipeline = Pipeline->front().InnerPipeline;
1983 return make_error<StringError>(
1984 formatv("unknown {0} name '{1}'",
1985 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1986 .str(),
1987 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001988 }
Chandler Carruth572e3402014-04-21 11:12:00 +00001989 }
1990
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001991 if (auto Err =
1992 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1993 return Err;
1994 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00001995}
Chandler Carruthedf59962016-02-18 09:45:17 +00001996
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001997// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001998Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1999 StringRef PipelineText,
2000 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002001 auto Pipeline = parsePipelineText(PipelineText);
2002 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002003 return make_error<StringError>(
2004 formatv("invalid pipeline '{0}'", PipelineText).str(),
2005 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002006
2007 StringRef FirstName = Pipeline->front().Name;
2008 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002009 return make_error<StringError>(
2010 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2011 PipelineText)
2012 .str(),
2013 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002014
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002015 if (auto Err =
2016 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2017 return Err;
2018 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002019}
2020
2021// Primary pass pipeline description parsing routine for a \c
2022// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002023Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2024 StringRef PipelineText,
2025 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002026 auto Pipeline = parsePipelineText(PipelineText);
2027 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002028 return make_error<StringError>(
2029 formatv("invalid pipeline '{0}'", PipelineText).str(),
2030 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002031
2032 StringRef FirstName = Pipeline->front().Name;
2033 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002034 return make_error<StringError>(
2035 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2036 PipelineText)
2037 .str(),
2038 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002039
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002040 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2041 DebugLogging))
2042 return Err;
2043 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002044}
2045
2046// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002047Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2048 StringRef PipelineText,
2049 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002050 auto Pipeline = parsePipelineText(PipelineText);
2051 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002052 return make_error<StringError>(
2053 formatv("invalid pipeline '{0}'", PipelineText).str(),
2054 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002055
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002056 if (auto Err =
2057 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2058 return Err;
2059
2060 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002061}
2062
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002063Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002064 // If the pipeline just consists of the word 'default' just replace the AA
2065 // manager with our default one.
2066 if (PipelineText == "default") {
2067 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002068 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002069 }
2070
Chandler Carruthedf59962016-02-18 09:45:17 +00002071 while (!PipelineText.empty()) {
2072 StringRef Name;
2073 std::tie(Name, PipelineText) = PipelineText.split(',');
2074 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002075 return make_error<StringError>(
2076 formatv("unknown alias analysis name '{0}'", Name).str(),
2077 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002078 }
2079
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002080 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002081}