blob: 92d6dbc2b5a7952279bb001b70afcbc6bfcbc70b [file] [log] [blame]
Chandler Carruth1ff77242015-03-07 09:02:36 +00001//===- Parsing, selection, and construction of pass pipelines -------------===//
Chandler Carruth66445382014-01-11 08:16:35 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chandler Carruth66445382014-01-11 08:16:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
9///
Chandler Carruth1ff77242015-03-07 09:02:36 +000010/// This file provides the implementation of the PassBuilder based on our
11/// static pass registry as well as related functionality. It also provides
12/// helpers to aid in analyzing, debugging, and testing passes and pass
13/// pipelines.
Chandler Carruth66445382014-01-11 08:16:35 +000014///
15//===----------------------------------------------------------------------===//
16
Chandler Carruth1ff77242015-03-07 09:02:36 +000017#include "llvm/Passes/PassBuilder.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000018#include "llvm/ADT/StringSwitch.h"
Chandler Carruth6f5770b102016-02-13 23:32:00 +000019#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth4f846a52016-02-20 03:46:03 +000020#include "llvm/Analysis/AliasAnalysisEvaluator.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000021#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthbece8d52016-02-13 23:46:24 +000022#include "llvm/Analysis/BasicAliasAnalysis.h"
Xinliang David Li28a93272016-05-05 21:13:27 +000023#include "llvm/Analysis/BlockFrequencyInfo.h"
Xinliang David Li6e5dd412016-05-05 02:59:57 +000024#include "llvm/Analysis/BranchProbabilityInfo.h"
Mehdi Amini27d23792016-09-16 16:56:30 +000025#include "llvm/Analysis/CFGPrinter.h"
George Burgess IVbfa401e2016-07-06 00:26:41 +000026#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
27#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
Chandler Carruth572e3402014-04-21 11:12:00 +000028#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruth4c660f72016-03-10 11:24:11 +000029#include "llvm/Analysis/CallGraph.h"
Michael Kupersteinde16b442016-04-18 23:55:01 +000030#include "llvm/Analysis/DemandedBits.h"
Chandler Carruth49c22192016-05-12 22:19:39 +000031#include "llvm/Analysis/DependenceAnalysis.h"
Hongbin Zheng751337f2016-02-25 17:54:15 +000032#include "llvm/Analysis/DominanceFrontier.h"
Chandler Carruth45a9c202016-03-11 09:15:11 +000033#include "llvm/Analysis/GlobalsModRef.h"
Dehao Chen1a444522016-07-16 22:51:33 +000034#include "llvm/Analysis/IVUsers.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000035#include "llvm/Analysis/LazyCallGraph.h"
Sean Silva687019f2016-06-13 22:01:25 +000036#include "llvm/Analysis/LazyValueInfo.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000037#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000038#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth61440d22016-03-10 00:55:30 +000039#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000040#include "llvm/Analysis/MemorySSA.h"
Teresa Johnsonf93b2462016-08-12 13:53:02 +000041#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000042#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawnbdbbd832018-06-28 14:13:06 +000043#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng3f978402016-02-25 17:54:07 +000044#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000045#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000046#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000047#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000048#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000049#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000050#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000051#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000052#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000053#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000054#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000055#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000056#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000057#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000058#include "llvm/IR/PassManager.h"
Fedor Sergeeva2ed4482019-03-31 10:15:39 +000059#include "llvm/IR/SafepointIRVerifier.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000060#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000061#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000062#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000063#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000064#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000065#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000066#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000067#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000068#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000069#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000070#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000071#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000072#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000073#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000074#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000075#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000076#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000077#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000078#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000079#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000080#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000081#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000082#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000083#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000084#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000085#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000086#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000087#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000088#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000089#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000090#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000091#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000092#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000093#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000094#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000095#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000096#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Manman Ren18295122019-02-28 20:13:38 +000097#include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000098#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000099#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +0000100#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +0000101#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000102#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000103#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000104#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000105#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000106#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000107#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000108#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000109#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000110#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000111#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000112#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000113#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000114#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000115#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000116#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000117#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000118#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000119#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000120#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000121#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000122#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000123#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000124#include "llvm/Transforms/Scalar/LoopDistribute.h"
Kit Barton3cdf8792019-04-17 18:53:27 +0000125#include "llvm/Transforms/Scalar/LoopFuse.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000126#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000127#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000128#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000129#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000130#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000131#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000132#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000133#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000134#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000135#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000136#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000137#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000138#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000139#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000140#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000141#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000142#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000143#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000144#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000145#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000146#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000147#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000148#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000149#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000150#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000151#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000152#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000153#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000154#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000155#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000156#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000157#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000158#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000159#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000160#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000161#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000162#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000163#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000164#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000165#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000166#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000167#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000168#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000169#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000170#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000171#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000172#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000173
Chandler Carruth66445382014-01-11 08:16:35 +0000174using namespace llvm;
175
Chandler Carruth719ffe12017-02-12 05:38:04 +0000176static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
177 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000178static cl::opt<bool>
179 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
180 cl::Hidden, cl::ZeroOrMore,
181 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000182
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000183static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000184 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000185 cl::Hidden, cl::ZeroOrMore,
186 cl::desc("Run NewGVN instead of GVN"));
187
Geoff Berry3cca1da2017-06-10 15:20:03 +0000188static cl::opt<bool> EnableEarlyCSEMemSSA(
Geoff Berry2573a192017-06-27 22:25:02 +0000189 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
190 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
Geoff Berry3cca1da2017-06-10 15:20:03 +0000191
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000192static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000193 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
194 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000195
Davide Italianobe1b6a92017-06-03 23:18:29 +0000196static cl::opt<bool> EnableGVNSink(
197 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
198 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
199
David Green963401d2018-07-01 12:47:30 +0000200static cl::opt<bool> EnableUnrollAndJam(
201 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
202 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
203
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000204static cl::opt<bool> EnableSyntheticCounts(
205 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
206 cl::desc("Run synthetic function entry count generation "
207 "pass"));
208
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000209static Regex DefaultAliasRegex(
210 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000211
Eric Christophereff3b6f2019-04-18 06:17:40 +0000212// This option is used in simplifying testing SampleFDO optimizations for
213// profile loading.
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000214static cl::opt<bool>
215 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
216 cl::desc("Enable control height reduction optimization (CHR)"));
217
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000218extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000219extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000220
Wei Mi3bcccdf2019-01-17 20:48:34 +0000221extern cl::opt<bool> FlattenedProfileUsed;
222
Chandler Carruthe3f50642016-12-22 06:59:15 +0000223static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
224 switch (Level) {
225 case PassBuilder::O0:
226 case PassBuilder::O1:
227 case PassBuilder::O2:
228 case PassBuilder::O3:
229 return false;
230
231 case PassBuilder::Os:
232 case PassBuilder::Oz:
233 return true;
234 }
235 llvm_unreachable("Invalid optimization level!");
236}
237
Chandler Carruth66445382014-01-11 08:16:35 +0000238namespace {
239
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000240/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000241struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000242 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000243 return PreservedAnalyses::all();
244 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000245 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000246};
247
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000248/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000249class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
250 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000251 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000252
253public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000254 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000255 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000256 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000257};
258
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000259/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000260struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000261 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
262 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000263 return PreservedAnalyses::all();
264 }
265 static StringRef name() { return "NoOpCGSCCPass"; }
266};
267
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000268/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000269class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
270 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000271 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000272
273public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000274 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000275 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000276 return Result();
277 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000278 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000279};
280
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000281/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000282struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000283 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000284 return PreservedAnalyses::all();
285 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000286 static StringRef name() { return "NoOpFunctionPass"; }
287};
288
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000289/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000290class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
291 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000292 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000293
294public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000295 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000296 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000297 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000298};
299
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000300/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000301struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000302 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
303 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000304 return PreservedAnalyses::all();
305 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000306 static StringRef name() { return "NoOpLoopPass"; }
307};
308
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000309/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000310class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
311 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000312 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000313
314public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000315 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000316 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
317 return Result();
318 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000319 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000320};
321
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000322AnalysisKey NoOpModuleAnalysis::Key;
323AnalysisKey NoOpCGSCCAnalysis::Key;
324AnalysisKey NoOpFunctionAnalysis::Key;
325AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000326
Chandler Carruth66445382014-01-11 08:16:35 +0000327} // End anonymous namespace.
328
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000329void PassBuilder::invokePeepholeEPCallbacks(
330 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
331 for (auto &C : PeepholeEPCallbacks)
332 C(FPM, Level);
333}
334
Chandler Carruth1ff77242015-03-07 09:02:36 +0000335void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000336#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000337 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000338#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000339
340 for (auto &C : ModuleAnalysisRegistrationCallbacks)
341 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000342}
343
Chandler Carruth1ff77242015-03-07 09:02:36 +0000344void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000345#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000346 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000347#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000348
349 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
350 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000351}
352
Chandler Carruth1ff77242015-03-07 09:02:36 +0000353void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000354#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000355 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000356#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000357
358 for (auto &C : FunctionAnalysisRegistrationCallbacks)
359 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000360}
361
Justin Bognereecc3c82016-02-25 07:23:08 +0000362void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000363#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000364 LAM.registerPass([&] { return CREATE_PASS; });
365#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000366
367 for (auto &C : LoopAnalysisRegistrationCallbacks)
368 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000369}
370
Chandler Carruthe3f50642016-12-22 06:59:15 +0000371FunctionPassManager
372PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000373 ThinLTOPhase Phase,
374 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000375 assert(Level != O0 && "Must request optimizations!");
376 FunctionPassManager FPM(DebugLogging);
377
378 // Form SSA out of local memory accesses after breaking apart aggregates into
379 // scalars.
380 FPM.addPass(SROA());
381
382 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000383 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000384
Davide Italianoc3688312017-06-01 23:08:14 +0000385 // Hoisting of scalars and load expressions.
386 if (EnableGVNHoist)
387 FPM.addPass(GVNHoistPass());
388
Davide Italianobe1b6a92017-06-03 23:18:29 +0000389 // Global value numbering based sinking.
390 if (EnableGVNSink) {
391 FPM.addPass(GVNSinkPass());
392 FPM.addPass(SimplifyCFGPass());
393 }
394
Chandler Carruthe3f50642016-12-22 06:59:15 +0000395 // Speculative execution if the target has divergent branches; otherwise nop.
396 FPM.addPass(SpeculativeExecutionPass());
397
398 // Optimize based on known information about branches, and cleanup afterward.
399 FPM.addPass(JumpThreadingPass());
400 FPM.addPass(CorrelatedValuePropagationPass());
401 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000402 if (Level == O3)
403 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000404 FPM.addPass(InstCombinePass());
405
406 if (!isOptimizingForSize(Level))
407 FPM.addPass(LibCallsShrinkWrapPass());
408
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000409 invokePeepholeEPCallbacks(FPM, Level);
410
Rong Xue1f42452017-10-23 22:21:29 +0000411 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
412 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000413 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000414 !isOptimizingForSize(Level))
415 FPM.addPass(PGOMemOPSizeOpt());
416
Chandler Carruthe3f50642016-12-22 06:59:15 +0000417 FPM.addPass(TailCallElimPass());
418 FPM.addPass(SimplifyCFGPass());
419
420 // Form canonically associated expression trees, and simplify the trees using
421 // basic mathematical properties. For example, this will form (nearly)
422 // minimal multiplication trees.
423 FPM.addPass(ReassociatePass());
424
425 // Add the primary loop simplification pipeline.
426 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000427 // some function passes in between them. These can and should be removed
428 // and/or replaced by scheduling the loop pass equivalents in the correct
429 // positions. But those equivalent passes aren't powerful enough yet.
430 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
431 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
432 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
433 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000434 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
435
Chandler Carruth71fd2702018-05-30 02:46:45 +0000436 // Simplify the loop body. We do this initially to clean up after other loop
437 // passes run, either when iterating on a loop or on inner loops with
438 // implications on the outer loop.
439 LPM1.addPass(LoopInstSimplifyPass());
440 LPM1.addPass(LoopSimplifyCFGPass());
441
Chandler Carruthe3f50642016-12-22 06:59:15 +0000442 // Rotate Loop - disable header duplication at -Oz
443 LPM1.addPass(LoopRotatePass(Level != Oz));
444 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000445 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000446 LPM2.addPass(IndVarSimplifyPass());
447 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000448
449 for (auto &C : LateLoopOptimizationsEPCallbacks)
450 C(LPM2, Level);
451
Chandler Carruth79b733b2017-01-26 23:21:17 +0000452 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000453 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000454 // because it changes IR to makes profile annotation in back compile
455 // inaccurate.
Rong Xudb29a3a2019-03-04 20:21:27 +0000456 if (Phase != ThinLTOPhase::PreLink || !PGOOpt ||
457 PGOOpt->Action != PGOOptions::SampleUse)
Teresa Johnsonecd90132017-08-02 20:35:29 +0000458 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000459
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000460 for (auto &C : LoopOptimizerEndEPCallbacks)
461 C(LPM2, Level);
462
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000463 // We provide the opt remark emitter pass for LICM to use. We only need to do
464 // this once as it is immutable.
465 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000466 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000467 FPM.addPass(SimplifyCFGPass());
468 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000469 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000470
471 // Eliminate redundancies.
472 if (Level != O1) {
473 // These passes add substantial compile time so skip them at O1.
474 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000475 if (RunNewGVN)
476 FPM.addPass(NewGVNPass());
477 else
478 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000479 }
480
481 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
482 FPM.addPass(MemCpyOptPass());
483
484 // Sparse conditional constant propagation.
485 // FIXME: It isn't clear why we do this *after* loop passes rather than
486 // before...
487 FPM.addPass(SCCPPass());
488
489 // Delete dead bit computations (instcombine runs after to fold away the dead
490 // computations, and then ADCE will run later to exploit any new DCE
491 // opportunities that creates).
492 FPM.addPass(BDCEPass());
493
494 // Run instcombine after redundancy and dead bit elimination to exploit
495 // opportunities opened up by them.
496 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000497 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000498
499 // Re-consider control flow based optimizations after redundancy elimination,
500 // redo DCE, etc.
501 FPM.addPass(JumpThreadingPass());
502 FPM.addPass(CorrelatedValuePropagationPass());
503 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000504 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000505
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000506 for (auto &C : ScalarOptimizerLateEPCallbacks)
507 C(FPM, Level);
508
Chandler Carruthe3f50642016-12-22 06:59:15 +0000509 // Finally, do an expensive DCE pass to catch all the dead code exposed by
510 // the simplifications and basic cleanup after all the simplifications.
511 FPM.addPass(ADCEPass());
512 FPM.addPass(SimplifyCFGPass());
513 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000514 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000515
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000516 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000517 (PGOOpt->Action == PGOOptions::IRUse ||
518 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000519 FPM.addPass(ControlHeightReductionPass());
520
Chandler Carruthe3f50642016-12-22 06:59:15 +0000521 return FPM;
522}
523
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000524void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
525 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000526 bool RunProfileGen, bool IsCS,
527 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000528 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000529 // Generally running simplification passes and the inliner with an high
530 // threshold results in smaller executables, but there may be cases where
531 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000532 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
533 // IsCS is true).
534 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000535 InlineParams IP;
536
537 // In the old pass manager, this is a cl::opt. Should still this be one?
538 IP.DefaultThreshold = 75;
539
540 // FIXME: The hint threshold has the same value used by the regular inliner.
541 // This should probably be lowered after performance testing.
542 // FIXME: this comment is cargo culted from the old pass manager, revisit).
543 IP.HintThreshold = 325;
544
545 CGSCCPassManager CGPipeline(DebugLogging);
546
547 CGPipeline.addPass(InlinerPass(IP));
548
549 FunctionPassManager FPM;
550 FPM.addPass(SROA());
551 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
552 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
553 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000554 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000555
Davide Italiano513dfaa2017-02-13 15:26:22 +0000556 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
557
558 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
559 }
560
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000561 // Delete anything that is now dead to make sure that we don't instrument
562 // dead code. Instrumentation can end up keeping dead code around and
563 // dramatically increase code size.
564 MPM.addPass(GlobalDCEPass());
565
Davide Italiano513dfaa2017-02-13 15:26:22 +0000566 if (RunProfileGen) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000567 MPM.addPass(PGOInstrumentationGen(IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000568
Xinliang David Lib67530e2017-06-25 00:26:43 +0000569 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000570 FPM.addPass(
571 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000572 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
573
Davide Italiano513dfaa2017-02-13 15:26:22 +0000574 // Add the profile lowering pass.
575 InstrProfOptions Options;
Rong Xudb29a3a2019-03-04 20:21:27 +0000576 if (!ProfileFile.empty())
577 Options.InstrProfileOutput = ProfileFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000578 Options.DoCounterPromotion = true;
Rong Xudb29a3a2019-03-04 20:21:27 +0000579 Options.UseBFIInPromotion = IsCS;
580 MPM.addPass(InstrProfiling(Options, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000581 } else if (!ProfileFile.empty()) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000582 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000583 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
584 // RequireAnalysisPass for PSI before subsequent non-module passes.
585 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
586 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000587}
588
Easwaran Raman8249fac2017-06-28 13:33:49 +0000589static InlineParams
590getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
591 auto O3 = PassBuilder::O3;
592 unsigned OptLevel = Level > O3 ? 2 : Level;
593 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
594 return getInlineParams(OptLevel, SizeLevel);
595}
596
Chandler Carruthe3f50642016-12-22 06:59:15 +0000597ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000598PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000599 ThinLTOPhase Phase,
600 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000601 ModulePassManager MPM(DebugLogging);
602
Rong Xudb29a3a2019-03-04 20:21:27 +0000603 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000604
605 // In ThinLTO mode, when flattened profile is used, all the available
606 // profile information will be annotated in PreLink phase so there is
607 // no need to load the profile again in PostLink.
608 bool LoadSampleProfile =
609 HasSampleProfile &&
610 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
611
612 // During the ThinLTO backend phase we perform early indirect call promotion
613 // here, before globalopt. Otherwise imported available_externally functions
614 // look unreferenced and are removed. If we are going to load the sample
615 // profile then defer until later.
616 // TODO: See if we can move later and consolidate with the location where
617 // we perform ICP when we are loading a sample profile.
618 // TODO: We pass HasSampleProfile (whether there was a sample profile file
619 // passed to the compile) to the SamplePGO flag of ICP. This is used to
620 // determine whether the new direct calls are annotated with prof metadata.
621 // Ideally this should be determined from whether the IR is annotated with
622 // sample profile, and not whether the a sample profile was provided on the
623 // command line. E.g. for flattened profiles where we will not be reloading
624 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
625 // provide the sample profile file.
626 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
627 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
628
Chandler Carruthe3f50642016-12-22 06:59:15 +0000629 // Do basic inference of function attributes from known properties of system
630 // libraries and other oracles.
631 MPM.addPass(InferFunctionAttrsPass());
632
633 // Create an early function pass manager to cleanup the output of the
634 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000635 FunctionPassManager EarlyFPM(DebugLogging);
636 EarlyFPM.addPass(SimplifyCFGPass());
637 EarlyFPM.addPass(SROA());
638 EarlyFPM.addPass(EarlyCSEPass());
639 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000640 if (Level == O3)
641 EarlyFPM.addPass(CallSiteSplittingPass());
642
Dehao Chen08f88312017-08-07 20:23:20 +0000643 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
644 // to convert bitcast to direct calls so that they can be inlined during the
645 // profile annotation prepration step.
646 // More details about SamplePGO design can be found in:
647 // https://research.google.com/pubs/pub45290.html
648 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000649 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000650 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000651 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000652
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000653 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000654 // Annotate sample profile right after early FPM to ensure freshness of
655 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000656 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000657 PGOOpt->ProfileRemappingFile,
658 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000659 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
660 // RequireAnalysisPass for PSI before subsequent non-module passes.
661 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000662 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
663 // for the profile annotation to be accurate in the ThinLTO backend.
664 if (Phase != ThinLTOPhase::PreLink)
665 // We perform early indirect call promotion here, before globalopt.
666 // This is important for the ThinLTO backend phase because otherwise
667 // imported available_externally functions look unreferenced and are
668 // removed.
669 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000670 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000671 }
672
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000673 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000674 // and prior to optimizing globals.
675 // FIXME: This position in the pipeline hasn't been carefully considered in
676 // years, it should be re-analyzed.
677 MPM.addPass(IPSCCPPass());
678
Matthew Simpsoncb585582017-10-25 13:40:08 +0000679 // Attach metadata to indirect call sites indicating the set of functions
680 // they may target at run-time. This should follow IPSCCP.
681 MPM.addPass(CalledValuePropagationPass());
682
Chandler Carruthe3f50642016-12-22 06:59:15 +0000683 // Optimize globals to try and fold them into constants.
684 MPM.addPass(GlobalOptPass());
685
686 // Promote any localized globals to SSA registers.
687 // FIXME: Should this instead by a run of SROA?
688 // FIXME: We should probably run instcombine and simplify-cfg afterward to
689 // delete control flows that are dead once globals have been folded to
690 // constants.
691 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
692
693 // Remove any dead arguments exposed by cleanups and constand folding
694 // globals.
695 MPM.addPass(DeadArgumentEliminationPass());
696
697 // Create a small function pass pipeline to cleanup after all the global
698 // optimizations.
699 FunctionPassManager GlobalCleanupPM(DebugLogging);
700 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000701 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
702
Chandler Carruthe3f50642016-12-22 06:59:15 +0000703 GlobalCleanupPM.addPass(SimplifyCFGPass());
704 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
705
Dehao Chen89d32262017-08-02 01:28:31 +0000706 // Add all the requested passes for instrumentation PGO, if requested.
707 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000708 (PGOOpt->Action == PGOOptions::IRInstr ||
709 PGOOpt->Action == PGOOptions::IRUse)) {
710 addPGOInstrPasses(MPM, DebugLogging, Level,
711 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
712 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000713 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000714 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000715 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000716 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
717 PGOOpt->CSAction == PGOOptions::CSIRInstr)
718 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000719
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000720 // Synthesize function entry counts for non-PGO compilation.
721 if (EnableSyntheticCounts && !PGOOpt)
722 MPM.addPass(SyntheticCountsPropagation());
723
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000724 // Require the GlobalsAA analysis for the module so we can query it within
725 // the CGSCC pipeline.
726 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000727
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000728 // Require the ProfileSummaryAnalysis for the module so we can query it within
729 // the inliner pass.
730 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
731
Chandler Carruthe3f50642016-12-22 06:59:15 +0000732 // Now begin the main postorder CGSCC pipeline.
733 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
734 // manager and trying to emulate its precise behavior. Much of this doesn't
735 // make a lot of sense and we should revisit the core CGSCC structure.
736 CGSCCPassManager MainCGPipeline(DebugLogging);
737
738 // Note: historically, the PruneEH pass was run first to deduce nounwind and
739 // generally clean up exception handling overhead. It isn't clear this is
740 // valuable as the inliner doesn't currently care whether it is inlining an
741 // invoke or a call.
742
743 // Run the inliner first. The theory is that we are walking bottom-up and so
744 // the callees have already been fully optimized, and we want to inline them
745 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000746 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000747 // because it makes profile annotation in the backend inaccurate.
748 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000749 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
750 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000751 IP.HotCallSiteThreshold = 0;
752 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000753
754 // Now deduce any function attributes based in the current code.
755 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
756
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000757 // When at O3 add argument promotion to the pass pipeline.
758 // FIXME: It isn't at all clear why this should be limited to O3.
759 if (Level == O3)
760 MainCGPipeline.addPass(ArgumentPromotionPass());
761
Chandler Carruthe3f50642016-12-22 06:59:15 +0000762 // Lastly, add the core function simplification pipeline nested inside the
763 // CGSCC walk.
764 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000765 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000766
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000767 for (auto &C : CGSCCOptimizerLateEPCallbacks)
768 C(MainCGPipeline, Level);
769
Chandler Carruth719ffe12017-02-12 05:38:04 +0000770 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
771 // to detect when we devirtualize indirect calls and iterate the SCC passes
772 // in that case to try and catch knock-on inlining or function attrs
773 // opportunities. Then we add it to the module pipeline by walking the SCCs
774 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000775 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000776 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000777 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000778
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000779 return MPM;
780}
781
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000782ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
783 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000784 ModulePassManager MPM(DebugLogging);
785
786 // Optimize globals now that the module is fully simplified.
787 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000788 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000789
Xinliang David Li126157c2017-05-22 16:41:57 +0000790 // Run partial inlining pass to partially inline functions that have
791 // large bodies.
792 if (RunPartialInlining)
793 MPM.addPass(PartialInlinerPass());
794
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000795 // Remove avail extern fns and globals definitions since we aren't compiling
796 // an object file for later LTO. For LTO we want to preserve these so they
797 // are eligible for inlining at link-time. Note if they are unreferenced they
798 // will be removed by GlobalDCE later, so this only impacts referenced
799 // available externally globals. Eventually they will be suppressed during
800 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
801 // may make globals referenced by available external functions dead and saves
802 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000803 MPM.addPass(EliminateAvailableExternallyPass());
804
Manman Ren18295122019-02-28 20:13:38 +0000805 if (EnableOrderFileInstrumentation)
806 MPM.addPass(InstrOrderFilePass());
807
Chandler Carruthe3f50642016-12-22 06:59:15 +0000808 // Do RPO function attribute inference across the module to forward-propagate
809 // attributes where applicable.
810 // FIXME: Is this really an optimization rather than a canonicalization?
811 MPM.addPass(ReversePostOrderFunctionAttrsPass());
812
Rong Xudb29a3a2019-03-04 20:21:27 +0000813 // Do a post inline PGO instrumentation and use pass. This is a context
814 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
815 // cross-module inline has not been done yet. The context sensitive
816 // instrumentation is after all the inlines are done.
817 if (!LTOPreLink && PGOOpt) {
818 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
819 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
820 /* IsCS */ true, PGOOpt->CSProfileGenFile,
821 PGOOpt->ProfileRemappingFile);
822 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
823 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
824 /* IsCS */ true, PGOOpt->ProfileFile,
825 PGOOpt->ProfileRemappingFile);
826 }
827
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000828 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000829 // useful as the above will have inlined, DCE'ed, and function-attr
830 // propagated everything. We should at this point have a reasonably minimal
831 // and richly annotated call graph. By computing aliasing and mod/ref
832 // information for all local globals here, the late loop passes and notably
833 // the vectorizer will be able to use them to help recognize vectorizable
834 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000835 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000836
837 FunctionPassManager OptimizePM(DebugLogging);
838 OptimizePM.addPass(Float2IntPass());
839 // FIXME: We need to run some loop optimizations to re-rotate loops after
840 // simplify-cfg and others undo their rotation.
841
842 // Optimize the loop execution. These passes operate on entire loop nests
843 // rather than on each loop in an inside-out manner, and so they are actually
844 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000845
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000846 for (auto &C : VectorizerStartEPCallbacks)
847 C(OptimizePM, Level);
848
Chandler Carrutha95ff382017-01-27 00:50:21 +0000849 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000850 OptimizePM.addPass(
851 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000852
853 // Distribute loops to allow partial vectorization. I.e. isolate dependences
854 // into separate loop that would otherwise inhibit vectorization. This is
855 // currently only performed for loops marked with the metadata
856 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000857 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000858
859 // Now run the core loop vectorizer.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000860 OptimizePM.addPass(LoopVectorizePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000861
Chandler Carruthbaabda92017-01-27 01:32:26 +0000862 // Eliminate loads by forwarding stores from the previous iteration to loads
863 // of the current iteration.
864 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000865
866 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000867 OptimizePM.addPass(InstCombinePass());
868
Chandler Carrutha95ff382017-01-27 00:50:21 +0000869 // Now that we've formed fast to execute loop structures, we do further
870 // optimizations. These are run afterward as they might block doing complex
871 // analyses and transforms such as what are needed for loop vectorization.
872
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000873 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
874 // GVN, loop transforms, and others have already run, so it's now better to
875 // convert to more optimized IR using more aggressive simplify CFG options.
876 // The extra sinking transform can create larger basic blocks, so do this
877 // before SLP vectorization.
878 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
879 forwardSwitchCondToPhi(true).
880 convertSwitchToLookupTable(true).
881 needCanonicalLoops(false).
882 sinkCommonInsts(true)));
883
Chandler Carruthe3f50642016-12-22 06:59:15 +0000884 // Optimize parallel scalar instruction chains into SIMD instructions.
885 OptimizePM.addPass(SLPVectorizerPass());
886
Chandler Carruthe3f50642016-12-22 06:59:15 +0000887 OptimizePM.addPass(InstCombinePass());
888
889 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000890 // execution resources of an out-of-order processor. We also then need to
891 // clean up redundancies and loop invariant code.
892 // FIXME: It would be really good to use a loop-integrated instruction
893 // combiner for cleanup here so that the unrolling and LICM can be pipelined
894 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000895 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
896 if (EnableUnrollAndJam) {
897 OptimizePM.addPass(
898 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
899 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000900 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000901 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000902 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000903 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000904 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000905
906 // Now that we've vectorized and unrolled loops, we may have more refined
907 // alignment information, try to re-derive it here.
908 OptimizePM.addPass(AlignmentFromAssumptionsPass());
909
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000910 // Split out cold code. Splitting is done late to avoid hiding context from
911 // other optimizations and inadvertently regressing performance. The tradeoff
912 // is that this has a higher code size cost than splitting early.
913 if (EnableHotColdSplit && !LTOPreLink)
914 MPM.addPass(HotColdSplittingPass());
915
Chandler Carrutha95ff382017-01-27 00:50:21 +0000916 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
917 // canonicalization pass that enables other optimizations. As a result,
918 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
919 // result too early.
920 OptimizePM.addPass(LoopSinkPass());
921
922 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000923 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000924
Sanjay Patel6fd43912017-09-09 13:38:18 +0000925 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
926 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
927 // flattening of blocks.
928 OptimizePM.addPass(DivRemPairsPass());
929
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000930 // LoopSink (and other loop passes since the last simplifyCFG) might have
931 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
932 OptimizePM.addPass(SimplifyCFGPass());
933
Chandler Carruthc34f7892017-11-28 11:32:31 +0000934 // Optimize PHIs by speculating around them when profitable. Note that this
935 // pass needs to be run after any PRE or similar pass as it is essentially
936 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
937 OptimizePM.addPass(SpeculateAroundPHIsPass());
938
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000939 for (auto &C : OptimizerLastEPCallbacks)
940 C(OptimizePM, Level);
941
Chandler Carrutha95ff382017-01-27 00:50:21 +0000942 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000943 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
944
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000945 MPM.addPass(CGProfilePass());
946
Chandler Carruthe3f50642016-12-22 06:59:15 +0000947 // Now we need to do some global optimization transforms.
948 // FIXME: It would seem like these should come first in the optimization
949 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
950 // ordering here.
951 MPM.addPass(GlobalDCEPass());
952 MPM.addPass(ConstantMergePass());
953
954 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000955}
956
Chandler Carruthe3f50642016-12-22 06:59:15 +0000957ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000958PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000959 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000960 assert(Level != O0 && "Must request optimizations for the default pipeline!");
961
962 ModulePassManager MPM(DebugLogging);
963
964 // Force any function attributes we want the rest of the pipeline to observe.
965 MPM.addPass(ForceFunctionAttrsPass());
966
David Blaikie0c64f5a2018-01-23 01:25:20 +0000967 // Apply module pipeline start EP callback.
968 for (auto &C : PipelineStartEPCallbacks)
969 C(MPM);
970
Dehao Chen08f88312017-08-07 20:23:20 +0000971 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000972 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
973
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000974 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000975 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
976 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000977
978 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000979 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000980
981 return MPM;
982}
983
984ModulePassManager
985PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
986 bool DebugLogging) {
987 assert(Level != O0 && "Must request optimizations for the default pipeline!");
988
989 ModulePassManager MPM(DebugLogging);
990
991 // Force any function attributes we want the rest of the pipeline to observe.
992 MPM.addPass(ForceFunctionAttrsPass());
993
Dehao Chen08f88312017-08-07 20:23:20 +0000994 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000995 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
996
David Blaikie0c64f5a2018-01-23 01:25:20 +0000997 // Apply module pipeline start EP callback.
998 for (auto &C : PipelineStartEPCallbacks)
999 C(MPM);
1000
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001001 // If we are planning to perform ThinLTO later, we don't bloat the code with
1002 // unrolling/vectorization/... now. Just simplify the module as much as we
1003 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001004 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1005 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001006
1007 // Run partial inlining pass to partially inline functions that have
1008 // large bodies.
1009 // FIXME: It isn't clear whether this is really the right place to run this
1010 // in ThinLTO. Because there is another canonicalization and simplification
1011 // phase that will run after the thin link, running this here ends up with
1012 // less information than will be available later and it may grow functions in
1013 // ways that aren't beneficial.
1014 if (RunPartialInlining)
1015 MPM.addPass(PartialInlinerPass());
1016
1017 // Reduce the size of the IR as much as possible.
1018 MPM.addPass(GlobalOptPass());
1019
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001020 return MPM;
1021}
1022
Teresa Johnson28023db2018-07-19 14:51:32 +00001023ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1024 OptimizationLevel Level, bool DebugLogging,
1025 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001026 ModulePassManager MPM(DebugLogging);
1027
Teresa Johnson28023db2018-07-19 14:51:32 +00001028 if (ImportSummary) {
1029 // These passes import type identifier resolutions for whole-program
1030 // devirtualization and CFI. They must run early because other passes may
1031 // disturb the specific instruction patterns that these passes look for,
1032 // creating dependencies on resolutions that may not appear in the summary.
1033 //
1034 // For example, GVN may transform the pattern assume(type.test) appearing in
1035 // two basic blocks into assume(phi(type.test, type.test)), which would
1036 // transform a dependency on a WPD resolution into a dependency on a type
1037 // identifier resolution for CFI.
1038 //
1039 // Also, WPD has access to more precise information than ICP and can
1040 // devirtualize more effectively, so it should operate on the IR first.
1041 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1042 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1043 }
1044
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001045 // Force any function attributes we want the rest of the pipeline to observe.
1046 MPM.addPass(ForceFunctionAttrsPass());
1047
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001048 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001049 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1050 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001051
1052 // Now add the optimization pipeline.
1053 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1054
1055 return MPM;
1056}
1057
1058ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001059PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1060 bool DebugLogging) {
1061 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001062 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001063 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001064 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001065}
1066
Teresa Johnson28023db2018-07-19 14:51:32 +00001067ModulePassManager
1068PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1069 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001070 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1071 ModulePassManager MPM(DebugLogging);
1072
Rong Xudb29a3a2019-03-04 20:21:27 +00001073 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001074 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001075 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001076 PGOOpt->ProfileRemappingFile,
1077 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001078 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1079 // RequireAnalysisPass for PSI before subsequent non-module passes.
1080 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001081 }
1082
Davide Italiano089a9122017-01-24 00:57:39 +00001083 // Remove unused virtual tables to improve the quality of code generated by
1084 // whole-program devirtualization and bitset lowering.
1085 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001086
Davide Italiano089a9122017-01-24 00:57:39 +00001087 // Force any function attributes we want the rest of the pipeline to observe.
1088 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001089
Davide Italiano089a9122017-01-24 00:57:39 +00001090 // Do basic inference of function attributes from known properties of system
1091 // libraries and other oracles.
1092 MPM.addPass(InferFunctionAttrsPass());
1093
1094 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001095 FunctionPassManager EarlyFPM(DebugLogging);
1096 EarlyFPM.addPass(CallSiteSplittingPass());
1097 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1098
Davide Italiano089a9122017-01-24 00:57:39 +00001099 // Indirect call promotion. This should promote all the targets that are
1100 // left by the earlier promotion pass that promotes intra-module targets.
1101 // This two-step promotion is to save the compile time. For LTO, it should
1102 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001103 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001104 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001105 // Propagate constants at call sites into the functions they call. This
1106 // opens opportunities for globalopt (and inlining) by substituting function
1107 // pointers passed as arguments to direct uses of functions.
1108 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001109
1110 // Attach metadata to indirect call sites indicating the set of functions
1111 // they may target at run-time. This should follow IPSCCP.
1112 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001113 }
1114
1115 // Now deduce any function attributes based in the current code.
1116 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1117 PostOrderFunctionAttrsPass()));
1118
1119 // Do RPO function attribute inference across the module to forward-propagate
1120 // attributes where applicable.
1121 // FIXME: Is this really an optimization rather than a canonicalization?
1122 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1123
Eric Christopher721eaef2019-02-26 20:33:22 +00001124 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001125 MPM.addPass(GlobalSplitPass());
1126
1127 // Run whole program optimization of virtual call when the list of callees
1128 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001129 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001130
1131 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001132 if (Level == 1) {
1133 // The LowerTypeTestsPass needs to run to lower type metadata and the
1134 // type.test intrinsics. The pass does nothing if CFI is disabled.
1135 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001136 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001137 }
Davide Italiano089a9122017-01-24 00:57:39 +00001138
1139 // Optimize globals to try and fold them into constants.
1140 MPM.addPass(GlobalOptPass());
1141
1142 // Promote any localized globals to SSA registers.
1143 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1144
1145 // Linking modules together can lead to duplicate global constant, only
1146 // keep one copy of each constant.
1147 MPM.addPass(ConstantMergePass());
1148
1149 // Remove unused arguments from functions.
1150 MPM.addPass(DeadArgumentEliminationPass());
1151
1152 // Reduce the code after globalopt and ipsccp. Both can open up significant
1153 // simplification opportunities, and both can propagate functions through
1154 // function pointers. When this happens, we often have to resolve varargs
1155 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001156 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001157 if (Level == O3)
1158 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001159 PeepholeFPM.addPass(InstCombinePass());
1160 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1161
1162 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001163
1164 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1165 // generally clean up exception handling overhead. It isn't clear this is
1166 // valuable as the inliner doesn't currently care whether it is inlining an
1167 // invoke or a call.
1168 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001169 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1170 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001171
1172 // Optimize globals again after we ran the inliner.
1173 MPM.addPass(GlobalOptPass());
1174
1175 // Garbage collect dead functions.
1176 // FIXME: Add ArgumentPromotion pass after once it's ported.
1177 MPM.addPass(GlobalDCEPass());
1178
1179 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001180 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001181 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001182 invokePeepholeEPCallbacks(FPM, Level);
1183
Davide Italiano089a9122017-01-24 00:57:39 +00001184 FPM.addPass(JumpThreadingPass());
1185
Rong Xudb29a3a2019-03-04 20:21:27 +00001186 // Do a post inline PGO instrumentation and use pass. This is a context
1187 // sensitive PGO pass.
1188 if (PGOOpt) {
1189 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1190 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1191 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1192 PGOOpt->ProfileRemappingFile);
1193 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1194 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1195 /* IsCS */ true, PGOOpt->ProfileFile,
1196 PGOOpt->ProfileRemappingFile);
1197 }
1198
Davide Italiano089a9122017-01-24 00:57:39 +00001199 // Break up allocas
1200 FPM.addPass(SROA());
1201
Robert Lougherf2158a82019-03-20 19:08:18 +00001202 // LTO provides additional opportunities for tailcall elimination due to
1203 // link-time inlining, and visibility of nocapture attribute.
1204 FPM.addPass(TailCallElimPass());
1205
Davide Italiano089a9122017-01-24 00:57:39 +00001206 // Run a few AA driver optimizations here and now to cleanup the code.
1207 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1208
1209 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1210 PostOrderFunctionAttrsPass()));
1211 // FIXME: here we run IP alias analysis in the legacy PM.
1212
1213 FunctionPassManager MainFPM;
1214
1215 // FIXME: once we fix LoopPass Manager, add LICM here.
1216 // FIXME: once we provide support for enabling MLSM, add it here.
1217 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001218 if (RunNewGVN)
1219 MainFPM.addPass(NewGVNPass());
1220 else
1221 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001222
1223 // Remove dead memcpy()'s.
1224 MainFPM.addPass(MemCpyOptPass());
1225
1226 // Nuke dead stores.
1227 MainFPM.addPass(DSEPass());
1228
1229 // FIXME: at this point, we run a bunch of loop passes:
1230 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1231 // loopVectorize. Enable them once the remaining issue with LPM
1232 // are sorted out.
1233
1234 MainFPM.addPass(InstCombinePass());
1235 MainFPM.addPass(SimplifyCFGPass());
1236 MainFPM.addPass(SCCPPass());
1237 MainFPM.addPass(InstCombinePass());
1238 MainFPM.addPass(BDCEPass());
1239
1240 // FIXME: We may want to run SLPVectorizer here.
1241 // After vectorization, assume intrinsics may tell us more
1242 // about pointer alignments.
1243#if 0
1244 MainFPM.add(AlignmentFromAssumptionsPass());
1245#endif
1246
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001247 // FIXME: Conditionally run LoadCombine here, after it's ported
1248 // (in case we still have this pass, given its questionable usefulness).
1249
Davide Italiano089a9122017-01-24 00:57:39 +00001250 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001251 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001252 MainFPM.addPass(JumpThreadingPass());
1253 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1254
1255 // Create a function that performs CFI checks for cross-DSO calls with
1256 // targets in the current module.
1257 MPM.addPass(CrossDSOCFIPass());
1258
1259 // Lower type metadata and the type.test intrinsic. This pass supports
1260 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1261 // to be run at link time if CFI is enabled. This pass does nothing if
1262 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001263 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001264
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001265 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1266 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1267 if (EnableHotColdSplit)
1268 MPM.addPass(HotColdSplittingPass());
1269
Davide Italiano089a9122017-01-24 00:57:39 +00001270 // Add late LTO optimization passes.
1271 // Delete basic blocks, which optimization passes may have killed.
1272 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1273
1274 // Drop bodies of available eternally objects to improve GlobalDCE.
1275 MPM.addPass(EliminateAvailableExternallyPass());
1276
1277 // Now that we have optimized the program, discard unreachable functions.
1278 MPM.addPass(GlobalDCEPass());
1279
1280 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001281 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001282}
1283
Chandler Carruth060ad612016-12-23 20:38:19 +00001284AAManager PassBuilder::buildDefaultAAPipeline() {
1285 AAManager AA;
1286
1287 // The order in which these are registered determines their priority when
1288 // being queried.
1289
1290 // First we register the basic alias analysis that provides the majority of
1291 // per-function local AA logic. This is a stateless, on-demand local set of
1292 // AA techniques.
1293 AA.registerFunctionAnalysis<BasicAA>();
1294
1295 // Next we query fast, specialized alias analyses that wrap IR-embedded
1296 // information about aliasing.
1297 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1298 AA.registerFunctionAnalysis<TypeBasedAA>();
1299
1300 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001301 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1302 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001303 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001304 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001305
1306 return AA;
1307}
1308
Chandler Carruth241bf242016-08-03 07:44:48 +00001309static Optional<int> parseRepeatPassName(StringRef Name) {
1310 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1311 return None;
1312 int Count;
1313 if (Name.getAsInteger(0, Count) || Count <= 0)
1314 return None;
1315 return Count;
1316}
1317
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001318static Optional<int> parseDevirtPassName(StringRef Name) {
1319 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1320 return None;
1321 int Count;
1322 if (Name.getAsInteger(0, Count) || Count <= 0)
1323 return None;
1324 return Count;
1325}
1326
Fedor Sergeevb7871402019-01-10 10:01:53 +00001327static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1328 if (!Name.consume_front(PassName))
1329 return false;
1330 // normal pass name w/o parameters == default parameters
1331 if (Name.empty())
1332 return true;
1333 return Name.startswith("<") && Name.endswith(">");
1334}
1335
1336namespace {
1337
1338/// This performs customized parsing of pass name with parameters.
1339///
1340/// We do not need parametrization of passes in textual pipeline very often,
1341/// yet on a rare occasion ability to specify parameters right there can be
1342/// useful.
1343///
1344/// \p Name - parameterized specification of a pass from a textual pipeline
1345/// is a string in a form of :
1346/// PassName '<' parameter-list '>'
1347///
1348/// Parameter list is being parsed by the parser callable argument, \p Parser,
1349/// It takes a string-ref of parameters and returns either StringError or a
1350/// parameter list in a form of a custom parameters type, all wrapped into
1351/// Expected<> template class.
1352///
1353template <typename ParametersParseCallableT>
1354auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1355 StringRef PassName) -> decltype(Parser(StringRef{})) {
1356 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1357
1358 StringRef Params = Name;
1359 if (!Params.consume_front(PassName)) {
1360 assert(false &&
1361 "unable to strip pass name from parametrized pass specification");
1362 }
1363 if (Params.empty())
1364 return ParametersT{};
1365 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1366 assert(false && "invalid format for parametrized pass name");
1367 }
1368
1369 Expected<ParametersT> Result = Parser(Params);
1370 assert((Result || Result.template errorIsA<StringError>()) &&
1371 "Pass parameter parser can only return StringErrors.");
1372 return std::move(Result);
1373}
1374
1375/// Parser of parameters for LoopUnroll pass.
1376Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1377 LoopUnrollOptions UnrollOpts;
1378 while (!Params.empty()) {
1379 StringRef ParamName;
1380 std::tie(ParamName, Params) = Params.split(';');
1381 int OptLevel = StringSwitch<int>(ParamName)
1382 .Case("O0", 0)
1383 .Case("O1", 1)
1384 .Case("O2", 2)
1385 .Case("O3", 3)
1386 .Default(-1);
1387 if (OptLevel >= 0) {
1388 UnrollOpts.setOptLevel(OptLevel);
1389 continue;
1390 }
1391
1392 bool Enable = !ParamName.consume_front("no-");
1393 if (ParamName == "partial") {
1394 UnrollOpts.setPartial(Enable);
1395 } else if (ParamName == "peeling") {
1396 UnrollOpts.setPeeling(Enable);
1397 } else if (ParamName == "runtime") {
1398 UnrollOpts.setRuntime(Enable);
1399 } else if (ParamName == "upperbound") {
1400 UnrollOpts.setUpperBound(Enable);
1401 } else {
1402 return make_error<StringError>(
1403 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1404 inconvertibleErrorCode());
1405 }
1406 }
1407 return UnrollOpts;
1408}
1409
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001410Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1411 MemorySanitizerOptions Result;
1412 while (!Params.empty()) {
1413 StringRef ParamName;
1414 std::tie(ParamName, Params) = Params.split(';');
1415
1416 if (ParamName == "recover") {
1417 Result.Recover = true;
1418 } else if (ParamName == "kernel") {
1419 Result.Kernel = true;
1420 } else if (ParamName.consume_front("track-origins=")) {
1421 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1422 return make_error<StringError>(
1423 formatv("invalid argument to MemorySanitizer pass track-origins "
1424 "parameter: '{0}' ",
1425 ParamName)
1426 .str(),
1427 inconvertibleErrorCode());
1428 } else {
1429 return make_error<StringError>(
1430 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1431 .str(),
1432 inconvertibleErrorCode());
1433 }
1434 }
1435 return Result;
1436}
1437
Serguei Katkovf5432832019-04-15 08:57:53 +00001438/// Parser of parameters for SimplifyCFG pass.
1439Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1440 SimplifyCFGOptions Result;
1441 while (!Params.empty()) {
1442 StringRef ParamName;
1443 std::tie(ParamName, Params) = Params.split(';');
1444
1445 bool Enable = !ParamName.consume_front("no-");
1446 if (ParamName == "forward-switch-cond") {
1447 Result.forwardSwitchCondToPhi(Enable);
1448 } else if (ParamName == "switch-to-lookup") {
1449 Result.convertSwitchToLookupTable(Enable);
1450 } else if (ParamName == "keep-loops") {
1451 Result.needCanonicalLoops(Enable);
1452 } else if (ParamName == "sink-common-insts") {
1453 Result.sinkCommonInsts(Enable);
1454 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1455 APInt BonusInstThreshold;
1456 if (ParamName.getAsInteger(0, BonusInstThreshold))
1457 return make_error<StringError>(
1458 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1459 "parameter: '{0}' ",
1460 ParamName).str(),
1461 inconvertibleErrorCode());
1462 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1463 } else {
1464 return make_error<StringError>(
1465 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1466 inconvertibleErrorCode());
1467 }
1468 }
1469 return Result;
1470}
1471
Fedor Sergeevb7871402019-01-10 10:01:53 +00001472} // namespace
1473
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001474/// Tests whether a pass name starts with a valid prefix for a default pipeline
1475/// alias.
1476static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1477 return Name.startswith("default") || Name.startswith("thinlto") ||
1478 Name.startswith("lto");
1479}
1480
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001481/// Tests whether registered callbacks will accept a given pass name.
1482///
1483/// When parsing a pipeline text, the type of the outermost pipeline may be
1484/// omitted, in which case the type is automatically determined from the first
1485/// pass name in the text. This may be a name that is handled through one of the
1486/// callbacks. We check this through the oridinary parsing callbacks by setting
1487/// up a dummy PassManager in order to not force the client to also handle this
1488/// type of query.
1489template <typename PassManagerT, typename CallbacksT>
1490static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1491 if (!Callbacks.empty()) {
1492 PassManagerT DummyPM;
1493 for (auto &CB : Callbacks)
1494 if (CB(Name, DummyPM, {}))
1495 return true;
1496 }
1497 return false;
1498}
1499
1500template <typename CallbacksT>
1501static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001502 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001503 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001504 return DefaultAliasRegex.match(Name);
1505
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001506 // Explicitly handle pass manager names.
1507 if (Name == "module")
1508 return true;
1509 if (Name == "cgscc")
1510 return true;
1511 if (Name == "function")
1512 return true;
1513
Chandler Carruth241bf242016-08-03 07:44:48 +00001514 // Explicitly handle custom-parsed pass names.
1515 if (parseRepeatPassName(Name))
1516 return true;
1517
Chandler Carruth74a8a222016-06-17 07:15:29 +00001518#define MODULE_PASS(NAME, CREATE_PASS) \
1519 if (Name == NAME) \
1520 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001521#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001522 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001523 return true;
1524#include "PassRegistry.def"
1525
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001526 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001527}
1528
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001529template <typename CallbacksT>
1530static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001531 // Explicitly handle pass manager names.
1532 if (Name == "cgscc")
1533 return true;
1534 if (Name == "function")
1535 return true;
1536
Chandler Carruth241bf242016-08-03 07:44:48 +00001537 // Explicitly handle custom-parsed pass names.
1538 if (parseRepeatPassName(Name))
1539 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001540 if (parseDevirtPassName(Name))
1541 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001542
Chandler Carruth74a8a222016-06-17 07:15:29 +00001543#define CGSCC_PASS(NAME, CREATE_PASS) \
1544 if (Name == NAME) \
1545 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001546#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001547 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001548 return true;
1549#include "PassRegistry.def"
1550
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001551 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001552}
1553
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001554template <typename CallbacksT>
1555static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001556 // Explicitly handle pass manager names.
1557 if (Name == "function")
1558 return true;
1559 if (Name == "loop")
1560 return true;
1561
Chandler Carruth241bf242016-08-03 07:44:48 +00001562 // Explicitly handle custom-parsed pass names.
1563 if (parseRepeatPassName(Name))
1564 return true;
1565
Chandler Carruth74a8a222016-06-17 07:15:29 +00001566#define FUNCTION_PASS(NAME, CREATE_PASS) \
1567 if (Name == NAME) \
1568 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001569#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1570 if (checkParametrizedPassName(Name, NAME)) \
1571 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001572#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001573 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001574 return true;
1575#include "PassRegistry.def"
1576
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001577 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001578}
1579
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001580template <typename CallbacksT>
1581static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001582 // Explicitly handle pass manager names.
1583 if (Name == "loop")
1584 return true;
1585
Chandler Carruth241bf242016-08-03 07:44:48 +00001586 // Explicitly handle custom-parsed pass names.
1587 if (parseRepeatPassName(Name))
1588 return true;
1589
Chandler Carruth74a8a222016-06-17 07:15:29 +00001590#define LOOP_PASS(NAME, CREATE_PASS) \
1591 if (Name == NAME) \
1592 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001593#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1594 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1595 return true;
1596#include "PassRegistry.def"
1597
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001598 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001599}
1600
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001601Optional<std::vector<PassBuilder::PipelineElement>>
1602PassBuilder::parsePipelineText(StringRef Text) {
1603 std::vector<PipelineElement> ResultPipeline;
1604
1605 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1606 &ResultPipeline};
1607 for (;;) {
1608 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1609 size_t Pos = Text.find_first_of(",()");
1610 Pipeline.push_back({Text.substr(0, Pos), {}});
1611
1612 // If we have a single terminating name, we're done.
1613 if (Pos == Text.npos)
1614 break;
1615
1616 char Sep = Text[Pos];
1617 Text = Text.substr(Pos + 1);
1618 if (Sep == ',')
1619 // Just a name ending in a comma, continue.
1620 continue;
1621
1622 if (Sep == '(') {
1623 // Push the inner pipeline onto the stack to continue processing.
1624 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1625 continue;
1626 }
1627
1628 assert(Sep == ')' && "Bogus separator!");
1629 // When handling the close parenthesis, we greedily consume them to avoid
1630 // empty strings in the pipeline.
1631 do {
1632 // If we try to pop the outer pipeline we have unbalanced parentheses.
1633 if (PipelineStack.size() == 1)
1634 return None;
1635
1636 PipelineStack.pop_back();
1637 } while (Text.consume_front(")"));
1638
1639 // Check if we've finished parsing.
1640 if (Text.empty())
1641 break;
1642
1643 // Otherwise, the end of an inner pipeline always has to be followed by
1644 // a comma, and then we can continue.
1645 if (!Text.consume_front(","))
1646 return None;
1647 }
1648
1649 if (PipelineStack.size() > 1)
1650 // Unbalanced paretheses.
1651 return None;
1652
1653 assert(PipelineStack.back() == &ResultPipeline &&
1654 "Wrong pipeline at the bottom of the stack!");
1655 return {std::move(ResultPipeline)};
1656}
1657
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001658Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1659 const PipelineElement &E,
1660 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001661 auto &Name = E.Name;
1662 auto &InnerPipeline = E.InnerPipeline;
1663
1664 // First handle complex passes like the pass managers which carry pipelines.
1665 if (!InnerPipeline.empty()) {
1666 if (Name == "module") {
1667 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001668 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1669 VerifyEachPass, DebugLogging))
1670 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001671 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001672 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001673 }
1674 if (Name == "cgscc") {
1675 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001676 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1677 DebugLogging))
1678 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001679 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001680 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001681 }
1682 if (Name == "function") {
1683 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001684 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1685 VerifyEachPass, DebugLogging))
1686 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001687 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001688 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001689 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001690 if (auto Count = parseRepeatPassName(Name)) {
1691 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001692 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1693 VerifyEachPass, DebugLogging))
1694 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001695 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001696 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001697 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001698
1699 for (auto &C : ModulePipelineParsingCallbacks)
1700 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001701 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001702
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001703 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001704 return make_error<StringError>(
1705 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1706 inconvertibleErrorCode());
1707 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001708 }
1709
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001710 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001711 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001712 SmallVector<StringRef, 3> Matches;
1713 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001714 return make_error<StringError>(
1715 formatv("unknown default pipeline alias '{0}'", Name).str(),
1716 inconvertibleErrorCode());
1717
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001718 assert(Matches.size() == 3 && "Must capture two matched strings!");
1719
Jordan Rosef85a95f2016-07-25 18:34:51 +00001720 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001721 .Case("O0", O0)
1722 .Case("O1", O1)
1723 .Case("O2", O2)
1724 .Case("O3", O3)
1725 .Case("Os", Os)
1726 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001727 if (L == O0)
1728 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001729 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001730
1731 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001732 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001733 } else if (Matches[1] == "thinlto-pre-link") {
1734 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1735 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001736 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001737 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001738 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001739 } else {
1740 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001741 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001742 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001743 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001744 }
1745
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001746 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001747#define MODULE_PASS(NAME, CREATE_PASS) \
1748 if (Name == NAME) { \
1749 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001750 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001751 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001752#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1753 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001754 MPM.addPass( \
1755 RequireAnalysisPass< \
1756 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001757 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001758 } \
1759 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001760 MPM.addPass(InvalidateAnalysisPass< \
1761 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001762 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001763 }
1764#include "PassRegistry.def"
1765
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001766 for (auto &C : ModulePipelineParsingCallbacks)
1767 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001768 return Error::success();
1769 return make_error<StringError>(
1770 formatv("unknown module pass '{0}'", Name).str(),
1771 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001772}
1773
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001774Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1775 const PipelineElement &E, bool VerifyEachPass,
1776 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001777 auto &Name = E.Name;
1778 auto &InnerPipeline = E.InnerPipeline;
1779
1780 // First handle complex passes like the pass managers which carry pipelines.
1781 if (!InnerPipeline.empty()) {
1782 if (Name == "cgscc") {
1783 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001784 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1785 VerifyEachPass, DebugLogging))
1786 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001787 // Add the nested pass manager with the appropriate adaptor.
1788 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001789 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001790 }
1791 if (Name == "function") {
1792 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001793 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1794 VerifyEachPass, DebugLogging))
1795 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001796 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001797 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001798 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001799 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001800 if (auto Count = parseRepeatPassName(Name)) {
1801 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001802 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1803 VerifyEachPass, DebugLogging))
1804 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001805 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001806 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001807 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001808 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1809 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001810 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1811 VerifyEachPass, DebugLogging))
1812 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001813 CGPM.addPass(
1814 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001815 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001816 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001817
1818 for (auto &C : CGSCCPipelineParsingCallbacks)
1819 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001820 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001821
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001822 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001823 return make_error<StringError>(
1824 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1825 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001826 }
1827
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001828// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001829#define CGSCC_PASS(NAME, CREATE_PASS) \
1830 if (Name == NAME) { \
1831 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001832 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001833 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001834#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1835 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001836 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001837 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001838 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1839 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001840 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001841 } \
1842 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001843 CGPM.addPass(InvalidateAnalysisPass< \
1844 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001845 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001846 }
1847#include "PassRegistry.def"
1848
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001849 for (auto &C : CGSCCPipelineParsingCallbacks)
1850 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001851 return Error::success();
1852 return make_error<StringError>(
1853 formatv("unknown cgscc pass '{0}'", Name).str(),
1854 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001855}
1856
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001857Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1858 const PipelineElement &E,
1859 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001860 auto &Name = E.Name;
1861 auto &InnerPipeline = E.InnerPipeline;
1862
1863 // First handle complex passes like the pass managers which carry pipelines.
1864 if (!InnerPipeline.empty()) {
1865 if (Name == "function") {
1866 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001867 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1868 VerifyEachPass, DebugLogging))
1869 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001870 // Add the nested pass manager with the appropriate adaptor.
1871 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001872 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001873 }
1874 if (Name == "loop") {
1875 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001876 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1877 DebugLogging))
1878 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001879 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001880 FPM.addPass(
1881 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001882 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001883 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001884 if (auto Count = parseRepeatPassName(Name)) {
1885 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001886 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1887 VerifyEachPass, DebugLogging))
1888 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001889 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001890 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001891 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001892
1893 for (auto &C : FunctionPipelineParsingCallbacks)
1894 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001895 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001896
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001897 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001898 return make_error<StringError>(
1899 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1900 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001901 }
1902
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001903// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001904#define FUNCTION_PASS(NAME, CREATE_PASS) \
1905 if (Name == NAME) { \
1906 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001907 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001908 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001909#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1910 if (checkParametrizedPassName(Name, NAME)) { \
1911 auto Params = parsePassParameters(PARSER, Name, NAME); \
1912 if (!Params) \
1913 return Params.takeError(); \
1914 FPM.addPass(CREATE_PASS(Params.get())); \
1915 return Error::success(); \
1916 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001917#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1918 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001919 FPM.addPass( \
1920 RequireAnalysisPass< \
1921 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001922 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001923 } \
1924 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001925 FPM.addPass(InvalidateAnalysisPass< \
1926 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001927 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001928 }
1929#include "PassRegistry.def"
1930
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001931 for (auto &C : FunctionPipelineParsingCallbacks)
1932 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001933 return Error::success();
1934 return make_error<StringError>(
1935 formatv("unknown function pass '{0}'", Name).str(),
1936 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001937}
1938
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001939Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1940 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001941 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001942 auto &InnerPipeline = E.InnerPipeline;
1943
1944 // First handle complex passes like the pass managers which carry pipelines.
1945 if (!InnerPipeline.empty()) {
1946 if (Name == "loop") {
1947 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001948 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1949 VerifyEachPass, DebugLogging))
1950 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001951 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001952 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001953 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001954 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001955 if (auto Count = parseRepeatPassName(Name)) {
1956 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001957 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1958 VerifyEachPass, DebugLogging))
1959 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001960 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001961 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001962 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001963
1964 for (auto &C : LoopPipelineParsingCallbacks)
1965 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001966 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001967
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001968 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001969 return make_error<StringError>(
1970 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1971 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001972 }
1973
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001974// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00001975#define LOOP_PASS(NAME, CREATE_PASS) \
1976 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001977 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001978 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001979 }
1980#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1981 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001982 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001983 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1984 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1985 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001986 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001987 } \
1988 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001989 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00001990 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001991 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00001992 }
1993#include "PassRegistry.def"
1994
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001995 for (auto &C : LoopPipelineParsingCallbacks)
1996 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001997 return Error::success();
1998 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1999 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002000}
2001
Chandler Carruthedf59962016-02-18 09:45:17 +00002002bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002003#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2004 if (Name == NAME) { \
2005 AA.registerModuleAnalysis< \
2006 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2007 return true; \
2008 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002009#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2010 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002011 AA.registerFunctionAnalysis< \
2012 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002013 return true; \
2014 }
2015#include "PassRegistry.def"
2016
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002017 for (auto &C : AAParsingCallbacks)
2018 if (C(Name, AA))
2019 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002020 return false;
2021}
2022
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002023Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002024 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002025 bool VerifyEachPass,
2026 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002027 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002028 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2029 return Err;
2030 // FIXME: No verifier support for Loop passes!
2031 }
2032 return Error::success();
2033}
2034
2035Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2036 ArrayRef<PipelineElement> Pipeline,
2037 bool VerifyEachPass,
2038 bool DebugLogging) {
2039 for (const auto &Element : Pipeline) {
2040 if (auto Err =
2041 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2042 return Err;
2043 if (VerifyEachPass)
2044 FPM.addPass(VerifierPass());
2045 }
2046 return Error::success();
2047}
2048
2049Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2050 ArrayRef<PipelineElement> Pipeline,
2051 bool VerifyEachPass,
2052 bool DebugLogging) {
2053 for (const auto &Element : Pipeline) {
2054 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2055 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002056 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002057 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002058 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002059}
2060
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002061void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2062 FunctionAnalysisManager &FAM,
2063 CGSCCAnalysisManager &CGAM,
2064 ModuleAnalysisManager &MAM) {
2065 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2066 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002067 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2068 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2069 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2070 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2071 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2072}
2073
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002074Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2075 ArrayRef<PipelineElement> Pipeline,
2076 bool VerifyEachPass,
2077 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002078 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002079 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2080 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002081 if (VerifyEachPass)
2082 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002083 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002084 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002085}
2086
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002087// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002088// FIXME: Should this routine accept a TargetMachine or require the caller to
2089// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002090Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2091 StringRef PipelineText,
2092 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002093 auto Pipeline = parsePipelineText(PipelineText);
2094 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002095 return make_error<StringError>(
2096 formatv("invalid pipeline '{0}'", PipelineText).str(),
2097 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002098
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002099 // If the first name isn't at the module layer, wrap the pipeline up
2100 // automatically.
2101 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002102
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002103 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2104 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002105 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002106 } else if (isFunctionPassName(FirstName,
2107 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002108 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002109 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002110 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002111 } else {
2112 for (auto &C : TopLevelPipelineParsingCallbacks)
2113 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002114 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002115
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002116 // Unknown pass or pipeline name!
2117 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2118 return make_error<StringError>(
2119 formatv("unknown {0} name '{1}'",
2120 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2121 .str(),
2122 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002123 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002124 }
2125
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002126 if (auto Err =
2127 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2128 return Err;
2129 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002130}
Chandler Carruthedf59962016-02-18 09:45:17 +00002131
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002132// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002133Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2134 StringRef PipelineText,
2135 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002136 auto Pipeline = parsePipelineText(PipelineText);
2137 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002138 return make_error<StringError>(
2139 formatv("invalid pipeline '{0}'", PipelineText).str(),
2140 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002141
2142 StringRef FirstName = Pipeline->front().Name;
2143 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002144 return make_error<StringError>(
2145 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2146 PipelineText)
2147 .str(),
2148 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002149
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002150 if (auto Err =
2151 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2152 return Err;
2153 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002154}
2155
2156// Primary pass pipeline description parsing routine for a \c
2157// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002158Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2159 StringRef PipelineText,
2160 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002161 auto Pipeline = parsePipelineText(PipelineText);
2162 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002163 return make_error<StringError>(
2164 formatv("invalid pipeline '{0}'", PipelineText).str(),
2165 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002166
2167 StringRef FirstName = Pipeline->front().Name;
2168 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002169 return make_error<StringError>(
2170 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2171 PipelineText)
2172 .str(),
2173 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002174
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002175 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2176 DebugLogging))
2177 return Err;
2178 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002179}
2180
2181// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002182Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2183 StringRef PipelineText,
2184 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002185 auto Pipeline = parsePipelineText(PipelineText);
2186 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002187 return make_error<StringError>(
2188 formatv("invalid pipeline '{0}'", PipelineText).str(),
2189 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002190
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002191 if (auto Err =
2192 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2193 return Err;
2194
2195 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002196}
2197
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002198Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002199 // If the pipeline just consists of the word 'default' just replace the AA
2200 // manager with our default one.
2201 if (PipelineText == "default") {
2202 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002203 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002204 }
2205
Chandler Carruthedf59962016-02-18 09:45:17 +00002206 while (!PipelineText.empty()) {
2207 StringRef Name;
2208 std::tie(Name, PipelineText) = PipelineText.split(',');
2209 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002210 return make_error<StringError>(
2211 formatv("unknown alias analysis name '{0}'", Name).str(),
2212 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002213 }
2214
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002215 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002216}