blob: 75a73efb906cb4e2099856c15dc6d974c012ee81 [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
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000218PipelineTuningOptions::PipelineTuningOptions() {
219 LoopInterleaving = EnableLoopInterleaving;
220 LoopVectorization = EnableLoopVectorization;
221}
222
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000223extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000224extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000225
Wei Mi3bcccdf2019-01-17 20:48:34 +0000226extern cl::opt<bool> FlattenedProfileUsed;
227
Chandler Carruthe3f50642016-12-22 06:59:15 +0000228static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
229 switch (Level) {
230 case PassBuilder::O0:
231 case PassBuilder::O1:
232 case PassBuilder::O2:
233 case PassBuilder::O3:
234 return false;
235
236 case PassBuilder::Os:
237 case PassBuilder::Oz:
238 return true;
239 }
240 llvm_unreachable("Invalid optimization level!");
241}
242
Chandler Carruth66445382014-01-11 08:16:35 +0000243namespace {
244
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000245/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000246struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000247 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000248 return PreservedAnalyses::all();
249 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000250 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000251};
252
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000253/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000254class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
255 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000256 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000257
258public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000259 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000260 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000261 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000262};
263
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000264/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000265struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000266 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
267 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000268 return PreservedAnalyses::all();
269 }
270 static StringRef name() { return "NoOpCGSCCPass"; }
271};
272
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000273/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000274class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
275 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000276 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000277
278public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000279 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000280 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000281 return Result();
282 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000283 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000284};
285
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000286/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000287struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000288 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000289 return PreservedAnalyses::all();
290 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000291 static StringRef name() { return "NoOpFunctionPass"; }
292};
293
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000294/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000295class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
296 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000297 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000298
299public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000300 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000301 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000302 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000303};
304
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000305/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000306struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000307 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
308 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000309 return PreservedAnalyses::all();
310 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000311 static StringRef name() { return "NoOpLoopPass"; }
312};
313
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000314/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000315class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
316 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000317 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000318
319public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000320 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000321 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
322 return Result();
323 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000324 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000325};
326
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000327AnalysisKey NoOpModuleAnalysis::Key;
328AnalysisKey NoOpCGSCCAnalysis::Key;
329AnalysisKey NoOpFunctionAnalysis::Key;
330AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000331
Chandler Carruth66445382014-01-11 08:16:35 +0000332} // End anonymous namespace.
333
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000334void PassBuilder::invokePeepholeEPCallbacks(
335 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
336 for (auto &C : PeepholeEPCallbacks)
337 C(FPM, Level);
338}
339
Chandler Carruth1ff77242015-03-07 09:02:36 +0000340void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000341#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000342 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000343#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000344
345 for (auto &C : ModuleAnalysisRegistrationCallbacks)
346 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000347}
348
Chandler Carruth1ff77242015-03-07 09:02:36 +0000349void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000350#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000351 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000352#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000353
354 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
355 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000356}
357
Chandler Carruth1ff77242015-03-07 09:02:36 +0000358void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000359#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000360 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000361#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000362
363 for (auto &C : FunctionAnalysisRegistrationCallbacks)
364 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000365}
366
Justin Bognereecc3c82016-02-25 07:23:08 +0000367void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000368#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000369 LAM.registerPass([&] { return CREATE_PASS; });
370#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000371
372 for (auto &C : LoopAnalysisRegistrationCallbacks)
373 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000374}
375
Chandler Carruthe3f50642016-12-22 06:59:15 +0000376FunctionPassManager
377PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000378 ThinLTOPhase Phase,
379 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000380 assert(Level != O0 && "Must request optimizations!");
381 FunctionPassManager FPM(DebugLogging);
382
383 // Form SSA out of local memory accesses after breaking apart aggregates into
384 // scalars.
385 FPM.addPass(SROA());
386
387 // Catch trivial redundancies
Geoff Berry3cca1da2017-06-10 15:20:03 +0000388 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000389
Davide Italianoc3688312017-06-01 23:08:14 +0000390 // Hoisting of scalars and load expressions.
391 if (EnableGVNHoist)
392 FPM.addPass(GVNHoistPass());
393
Davide Italianobe1b6a92017-06-03 23:18:29 +0000394 // Global value numbering based sinking.
395 if (EnableGVNSink) {
396 FPM.addPass(GVNSinkPass());
397 FPM.addPass(SimplifyCFGPass());
398 }
399
Chandler Carruthe3f50642016-12-22 06:59:15 +0000400 // Speculative execution if the target has divergent branches; otherwise nop.
401 FPM.addPass(SpeculativeExecutionPass());
402
403 // Optimize based on known information about branches, and cleanup afterward.
404 FPM.addPass(JumpThreadingPass());
405 FPM.addPass(CorrelatedValuePropagationPass());
406 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000407 if (Level == O3)
408 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000409 FPM.addPass(InstCombinePass());
410
411 if (!isOptimizingForSize(Level))
412 FPM.addPass(LibCallsShrinkWrapPass());
413
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000414 invokePeepholeEPCallbacks(FPM, Level);
415
Rong Xue1f42452017-10-23 22:21:29 +0000416 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
417 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000418 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000419 !isOptimizingForSize(Level))
420 FPM.addPass(PGOMemOPSizeOpt());
421
Chandler Carruthe3f50642016-12-22 06:59:15 +0000422 FPM.addPass(TailCallElimPass());
423 FPM.addPass(SimplifyCFGPass());
424
425 // Form canonically associated expression trees, and simplify the trees using
426 // basic mathematical properties. For example, this will form (nearly)
427 // minimal multiplication trees.
428 FPM.addPass(ReassociatePass());
429
430 // Add the primary loop simplification pipeline.
431 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000432 // some function passes in between them. These can and should be removed
433 // and/or replaced by scheduling the loop pass equivalents in the correct
434 // positions. But those equivalent passes aren't powerful enough yet.
435 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
436 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
437 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
438 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000439 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
440
Chandler Carruth71fd2702018-05-30 02:46:45 +0000441 // Simplify the loop body. We do this initially to clean up after other loop
442 // passes run, either when iterating on a loop or on inner loops with
443 // implications on the outer loop.
444 LPM1.addPass(LoopInstSimplifyPass());
445 LPM1.addPass(LoopSimplifyCFGPass());
446
Chandler Carruthe3f50642016-12-22 06:59:15 +0000447 // Rotate Loop - disable header duplication at -Oz
448 LPM1.addPass(LoopRotatePass(Level != Oz));
449 LPM1.addPass(LICMPass());
Chandler Carruth86248d52017-05-26 01:24:11 +0000450 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000451 LPM2.addPass(IndVarSimplifyPass());
452 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000453
454 for (auto &C : LateLoopOptimizationsEPCallbacks)
455 C(LPM2, Level);
456
Chandler Carruth79b733b2017-01-26 23:21:17 +0000457 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000458 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000459 // because it changes IR to makes profile annotation in back compile
460 // inaccurate.
Rong Xudb29a3a2019-03-04 20:21:27 +0000461 if (Phase != ThinLTOPhase::PreLink || !PGOOpt ||
462 PGOOpt->Action != PGOOptions::SampleUse)
Teresa Johnsonecd90132017-08-02 20:35:29 +0000463 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000464
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000465 for (auto &C : LoopOptimizerEndEPCallbacks)
466 C(LPM2, Level);
467
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000468 // We provide the opt remark emitter pass for LICM to use. We only need to do
469 // this once as it is immutable.
470 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000471 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000472 FPM.addPass(SimplifyCFGPass());
473 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000474 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000475
476 // Eliminate redundancies.
477 if (Level != O1) {
478 // These passes add substantial compile time so skip them at O1.
479 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000480 if (RunNewGVN)
481 FPM.addPass(NewGVNPass());
482 else
483 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000484 }
485
486 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
487 FPM.addPass(MemCpyOptPass());
488
489 // Sparse conditional constant propagation.
490 // FIXME: It isn't clear why we do this *after* loop passes rather than
491 // before...
492 FPM.addPass(SCCPPass());
493
494 // Delete dead bit computations (instcombine runs after to fold away the dead
495 // computations, and then ADCE will run later to exploit any new DCE
496 // opportunities that creates).
497 FPM.addPass(BDCEPass());
498
499 // Run instcombine after redundancy and dead bit elimination to exploit
500 // opportunities opened up by them.
501 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000502 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000503
504 // Re-consider control flow based optimizations after redundancy elimination,
505 // redo DCE, etc.
506 FPM.addPass(JumpThreadingPass());
507 FPM.addPass(CorrelatedValuePropagationPass());
508 FPM.addPass(DSEPass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000509 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000510
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000511 for (auto &C : ScalarOptimizerLateEPCallbacks)
512 C(FPM, Level);
513
Chandler Carruthe3f50642016-12-22 06:59:15 +0000514 // Finally, do an expensive DCE pass to catch all the dead code exposed by
515 // the simplifications and basic cleanup after all the simplifications.
516 FPM.addPass(ADCEPass());
517 FPM.addPass(SimplifyCFGPass());
518 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000519 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000520
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000521 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000522 (PGOOpt->Action == PGOOptions::IRUse ||
523 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000524 FPM.addPass(ControlHeightReductionPass());
525
Chandler Carruthe3f50642016-12-22 06:59:15 +0000526 return FPM;
527}
528
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000529void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
530 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000531 bool RunProfileGen, bool IsCS,
532 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000533 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000534 // Generally running simplification passes and the inliner with an high
535 // threshold results in smaller executables, but there may be cases where
536 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000537 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
538 // IsCS is true).
539 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000540 InlineParams IP;
541
542 // In the old pass manager, this is a cl::opt. Should still this be one?
543 IP.DefaultThreshold = 75;
544
545 // FIXME: The hint threshold has the same value used by the regular inliner.
546 // This should probably be lowered after performance testing.
547 // FIXME: this comment is cargo culted from the old pass manager, revisit).
548 IP.HintThreshold = 325;
549
550 CGSCCPassManager CGPipeline(DebugLogging);
551
552 CGPipeline.addPass(InlinerPass(IP));
553
554 FunctionPassManager FPM;
555 FPM.addPass(SROA());
556 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
557 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
558 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000559 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000560
Davide Italiano513dfaa2017-02-13 15:26:22 +0000561 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
562
563 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
564 }
565
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000566 // Delete anything that is now dead to make sure that we don't instrument
567 // dead code. Instrumentation can end up keeping dead code around and
568 // dramatically increase code size.
569 MPM.addPass(GlobalDCEPass());
570
Davide Italiano513dfaa2017-02-13 15:26:22 +0000571 if (RunProfileGen) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000572 MPM.addPass(PGOInstrumentationGen(IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000573
Xinliang David Lib67530e2017-06-25 00:26:43 +0000574 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000575 FPM.addPass(
576 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000577 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
578
Davide Italiano513dfaa2017-02-13 15:26:22 +0000579 // Add the profile lowering pass.
580 InstrProfOptions Options;
Rong Xudb29a3a2019-03-04 20:21:27 +0000581 if (!ProfileFile.empty())
582 Options.InstrProfileOutput = ProfileFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000583 Options.DoCounterPromotion = true;
Rong Xudb29a3a2019-03-04 20:21:27 +0000584 Options.UseBFIInPromotion = IsCS;
585 MPM.addPass(InstrProfiling(Options, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000586 } else if (!ProfileFile.empty()) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000587 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000588 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
589 // RequireAnalysisPass for PSI before subsequent non-module passes.
590 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
591 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000592}
593
Easwaran Raman8249fac2017-06-28 13:33:49 +0000594static InlineParams
595getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
596 auto O3 = PassBuilder::O3;
597 unsigned OptLevel = Level > O3 ? 2 : Level;
598 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
599 return getInlineParams(OptLevel, SizeLevel);
600}
601
Chandler Carruthe3f50642016-12-22 06:59:15 +0000602ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000603PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000604 ThinLTOPhase Phase,
605 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000606 ModulePassManager MPM(DebugLogging);
607
Rong Xudb29a3a2019-03-04 20:21:27 +0000608 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000609
610 // In ThinLTO mode, when flattened profile is used, all the available
611 // profile information will be annotated in PreLink phase so there is
612 // no need to load the profile again in PostLink.
613 bool LoadSampleProfile =
614 HasSampleProfile &&
615 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
616
617 // During the ThinLTO backend phase we perform early indirect call promotion
618 // here, before globalopt. Otherwise imported available_externally functions
619 // look unreferenced and are removed. If we are going to load the sample
620 // profile then defer until later.
621 // TODO: See if we can move later and consolidate with the location where
622 // we perform ICP when we are loading a sample profile.
623 // TODO: We pass HasSampleProfile (whether there was a sample profile file
624 // passed to the compile) to the SamplePGO flag of ICP. This is used to
625 // determine whether the new direct calls are annotated with prof metadata.
626 // Ideally this should be determined from whether the IR is annotated with
627 // sample profile, and not whether the a sample profile was provided on the
628 // command line. E.g. for flattened profiles where we will not be reloading
629 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
630 // provide the sample profile file.
631 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
632 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
633
Chandler Carruthe3f50642016-12-22 06:59:15 +0000634 // Do basic inference of function attributes from known properties of system
635 // libraries and other oracles.
636 MPM.addPass(InferFunctionAttrsPass());
637
638 // Create an early function pass manager to cleanup the output of the
639 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000640 FunctionPassManager EarlyFPM(DebugLogging);
641 EarlyFPM.addPass(SimplifyCFGPass());
642 EarlyFPM.addPass(SROA());
643 EarlyFPM.addPass(EarlyCSEPass());
644 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000645 if (Level == O3)
646 EarlyFPM.addPass(CallSiteSplittingPass());
647
Dehao Chen08f88312017-08-07 20:23:20 +0000648 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
649 // to convert bitcast to direct calls so that they can be inlined during the
650 // profile annotation prepration step.
651 // More details about SamplePGO design can be found in:
652 // https://research.google.com/pubs/pub45290.html
653 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000654 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000655 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000656 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000657
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000658 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000659 // Annotate sample profile right after early FPM to ensure freshness of
660 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000661 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000662 PGOOpt->ProfileRemappingFile,
663 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000664 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
665 // RequireAnalysisPass for PSI before subsequent non-module passes.
666 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000667 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
668 // for the profile annotation to be accurate in the ThinLTO backend.
669 if (Phase != ThinLTOPhase::PreLink)
670 // We perform early indirect call promotion here, before globalopt.
671 // This is important for the ThinLTO backend phase because otherwise
672 // imported available_externally functions look unreferenced and are
673 // removed.
674 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000675 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000676 }
677
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000678 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000679 // and prior to optimizing globals.
680 // FIXME: This position in the pipeline hasn't been carefully considered in
681 // years, it should be re-analyzed.
682 MPM.addPass(IPSCCPPass());
683
Matthew Simpsoncb585582017-10-25 13:40:08 +0000684 // Attach metadata to indirect call sites indicating the set of functions
685 // they may target at run-time. This should follow IPSCCP.
686 MPM.addPass(CalledValuePropagationPass());
687
Chandler Carruthe3f50642016-12-22 06:59:15 +0000688 // Optimize globals to try and fold them into constants.
689 MPM.addPass(GlobalOptPass());
690
691 // Promote any localized globals to SSA registers.
692 // FIXME: Should this instead by a run of SROA?
693 // FIXME: We should probably run instcombine and simplify-cfg afterward to
694 // delete control flows that are dead once globals have been folded to
695 // constants.
696 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
697
698 // Remove any dead arguments exposed by cleanups and constand folding
699 // globals.
700 MPM.addPass(DeadArgumentEliminationPass());
701
702 // Create a small function pass pipeline to cleanup after all the global
703 // optimizations.
704 FunctionPassManager GlobalCleanupPM(DebugLogging);
705 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000706 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
707
Chandler Carruthe3f50642016-12-22 06:59:15 +0000708 GlobalCleanupPM.addPass(SimplifyCFGPass());
709 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
710
Dehao Chen89d32262017-08-02 01:28:31 +0000711 // Add all the requested passes for instrumentation PGO, if requested.
712 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000713 (PGOOpt->Action == PGOOptions::IRInstr ||
714 PGOOpt->Action == PGOOptions::IRUse)) {
715 addPGOInstrPasses(MPM, DebugLogging, Level,
716 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
717 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000718 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000719 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000720 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000721 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
722 PGOOpt->CSAction == PGOOptions::CSIRInstr)
723 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000724
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000725 // Synthesize function entry counts for non-PGO compilation.
726 if (EnableSyntheticCounts && !PGOOpt)
727 MPM.addPass(SyntheticCountsPropagation());
728
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000729 // Require the GlobalsAA analysis for the module so we can query it within
730 // the CGSCC pipeline.
731 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000732
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000733 // Require the ProfileSummaryAnalysis for the module so we can query it within
734 // the inliner pass.
735 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
736
Chandler Carruthe3f50642016-12-22 06:59:15 +0000737 // Now begin the main postorder CGSCC pipeline.
738 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
739 // manager and trying to emulate its precise behavior. Much of this doesn't
740 // make a lot of sense and we should revisit the core CGSCC structure.
741 CGSCCPassManager MainCGPipeline(DebugLogging);
742
743 // Note: historically, the PruneEH pass was run first to deduce nounwind and
744 // generally clean up exception handling overhead. It isn't clear this is
745 // valuable as the inliner doesn't currently care whether it is inlining an
746 // invoke or a call.
747
748 // Run the inliner first. The theory is that we are walking bottom-up and so
749 // the callees have already been fully optimized, and we want to inline them
750 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000751 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000752 // because it makes profile annotation in the backend inaccurate.
753 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000754 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
755 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000756 IP.HotCallSiteThreshold = 0;
757 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000758
759 // Now deduce any function attributes based in the current code.
760 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
761
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000762 // When at O3 add argument promotion to the pass pipeline.
763 // FIXME: It isn't at all clear why this should be limited to O3.
764 if (Level == O3)
765 MainCGPipeline.addPass(ArgumentPromotionPass());
766
Chandler Carruthe3f50642016-12-22 06:59:15 +0000767 // Lastly, add the core function simplification pipeline nested inside the
768 // CGSCC walk.
769 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000770 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000771
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000772 for (auto &C : CGSCCOptimizerLateEPCallbacks)
773 C(MainCGPipeline, Level);
774
Chandler Carruth719ffe12017-02-12 05:38:04 +0000775 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
776 // to detect when we devirtualize indirect calls and iterate the SCC passes
777 // in that case to try and catch knock-on inlining or function attrs
778 // opportunities. Then we add it to the module pipeline by walking the SCCs
779 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000780 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000781 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000782 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000783
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000784 return MPM;
785}
786
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000787ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
788 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000789 ModulePassManager MPM(DebugLogging);
790
791 // Optimize globals now that the module is fully simplified.
792 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000793 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000794
Xinliang David Li126157c2017-05-22 16:41:57 +0000795 // Run partial inlining pass to partially inline functions that have
796 // large bodies.
797 if (RunPartialInlining)
798 MPM.addPass(PartialInlinerPass());
799
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000800 // Remove avail extern fns and globals definitions since we aren't compiling
801 // an object file for later LTO. For LTO we want to preserve these so they
802 // are eligible for inlining at link-time. Note if they are unreferenced they
803 // will be removed by GlobalDCE later, so this only impacts referenced
804 // available externally globals. Eventually they will be suppressed during
805 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
806 // may make globals referenced by available external functions dead and saves
807 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000808 MPM.addPass(EliminateAvailableExternallyPass());
809
Manman Ren18295122019-02-28 20:13:38 +0000810 if (EnableOrderFileInstrumentation)
811 MPM.addPass(InstrOrderFilePass());
812
Chandler Carruthe3f50642016-12-22 06:59:15 +0000813 // Do RPO function attribute inference across the module to forward-propagate
814 // attributes where applicable.
815 // FIXME: Is this really an optimization rather than a canonicalization?
816 MPM.addPass(ReversePostOrderFunctionAttrsPass());
817
Rong Xudb29a3a2019-03-04 20:21:27 +0000818 // Do a post inline PGO instrumentation and use pass. This is a context
819 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
820 // cross-module inline has not been done yet. The context sensitive
821 // instrumentation is after all the inlines are done.
822 if (!LTOPreLink && PGOOpt) {
823 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
824 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
825 /* IsCS */ true, PGOOpt->CSProfileGenFile,
826 PGOOpt->ProfileRemappingFile);
827 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
828 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
829 /* IsCS */ true, PGOOpt->ProfileFile,
830 PGOOpt->ProfileRemappingFile);
831 }
832
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000833 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000834 // useful as the above will have inlined, DCE'ed, and function-attr
835 // propagated everything. We should at this point have a reasonably minimal
836 // and richly annotated call graph. By computing aliasing and mod/ref
837 // information for all local globals here, the late loop passes and notably
838 // the vectorizer will be able to use them to help recognize vectorizable
839 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000840 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000841
842 FunctionPassManager OptimizePM(DebugLogging);
843 OptimizePM.addPass(Float2IntPass());
844 // FIXME: We need to run some loop optimizations to re-rotate loops after
845 // simplify-cfg and others undo their rotation.
846
847 // Optimize the loop execution. These passes operate on entire loop nests
848 // rather than on each loop in an inside-out manner, and so they are actually
849 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000850
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000851 for (auto &C : VectorizerStartEPCallbacks)
852 C(OptimizePM, Level);
853
Chandler Carrutha95ff382017-01-27 00:50:21 +0000854 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000855 OptimizePM.addPass(
856 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000857
858 // Distribute loops to allow partial vectorization. I.e. isolate dependences
859 // into separate loop that would otherwise inhibit vectorization. This is
860 // currently only performed for loops marked with the metadata
861 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000862 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000863
864 // Now run the core loop vectorizer.
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000865 OptimizePM.addPass(LoopVectorizePass(
866 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000867
Chandler Carruthbaabda92017-01-27 01:32:26 +0000868 // Eliminate loads by forwarding stores from the previous iteration to loads
869 // of the current iteration.
870 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000871
872 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000873 OptimizePM.addPass(InstCombinePass());
874
Chandler Carrutha95ff382017-01-27 00:50:21 +0000875 // Now that we've formed fast to execute loop structures, we do further
876 // optimizations. These are run afterward as they might block doing complex
877 // analyses and transforms such as what are needed for loop vectorization.
878
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000879 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
880 // GVN, loop transforms, and others have already run, so it's now better to
881 // convert to more optimized IR using more aggressive simplify CFG options.
882 // The extra sinking transform can create larger basic blocks, so do this
883 // before SLP vectorization.
884 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
885 forwardSwitchCondToPhi(true).
886 convertSwitchToLookupTable(true).
887 needCanonicalLoops(false).
888 sinkCommonInsts(true)));
889
Chandler Carruthe3f50642016-12-22 06:59:15 +0000890 // Optimize parallel scalar instruction chains into SIMD instructions.
891 OptimizePM.addPass(SLPVectorizerPass());
892
Chandler Carruthe3f50642016-12-22 06:59:15 +0000893 OptimizePM.addPass(InstCombinePass());
894
895 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000896 // execution resources of an out-of-order processor. We also then need to
897 // clean up redundancies and loop invariant code.
898 // FIXME: It would be really good to use a loop-integrated instruction
899 // combiner for cleanup here so that the unrolling and LICM can be pipelined
900 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000901 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
902 if (EnableUnrollAndJam) {
903 OptimizePM.addPass(
904 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
905 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000906 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000907 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000908 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000909 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000910 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000911
912 // Now that we've vectorized and unrolled loops, we may have more refined
913 // alignment information, try to re-derive it here.
914 OptimizePM.addPass(AlignmentFromAssumptionsPass());
915
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000916 // Split out cold code. Splitting is done late to avoid hiding context from
917 // other optimizations and inadvertently regressing performance. The tradeoff
918 // is that this has a higher code size cost than splitting early.
919 if (EnableHotColdSplit && !LTOPreLink)
920 MPM.addPass(HotColdSplittingPass());
921
Chandler Carrutha95ff382017-01-27 00:50:21 +0000922 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
923 // canonicalization pass that enables other optimizations. As a result,
924 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
925 // result too early.
926 OptimizePM.addPass(LoopSinkPass());
927
928 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000929 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000930
Sanjay Patel6fd43912017-09-09 13:38:18 +0000931 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
932 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
933 // flattening of blocks.
934 OptimizePM.addPass(DivRemPairsPass());
935
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000936 // LoopSink (and other loop passes since the last simplifyCFG) might have
937 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
938 OptimizePM.addPass(SimplifyCFGPass());
939
Chandler Carruthc34f7892017-11-28 11:32:31 +0000940 // Optimize PHIs by speculating around them when profitable. Note that this
941 // pass needs to be run after any PRE or similar pass as it is essentially
942 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
943 OptimizePM.addPass(SpeculateAroundPHIsPass());
944
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000945 for (auto &C : OptimizerLastEPCallbacks)
946 C(OptimizePM, Level);
947
Chandler Carrutha95ff382017-01-27 00:50:21 +0000948 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000949 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
950
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000951 MPM.addPass(CGProfilePass());
952
Chandler Carruthe3f50642016-12-22 06:59:15 +0000953 // Now we need to do some global optimization transforms.
954 // FIXME: It would seem like these should come first in the optimization
955 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
956 // ordering here.
957 MPM.addPass(GlobalDCEPass());
958 MPM.addPass(ConstantMergePass());
959
960 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000961}
962
Chandler Carruthe3f50642016-12-22 06:59:15 +0000963ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000964PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000965 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000966 assert(Level != O0 && "Must request optimizations for the default pipeline!");
967
968 ModulePassManager MPM(DebugLogging);
969
970 // Force any function attributes we want the rest of the pipeline to observe.
971 MPM.addPass(ForceFunctionAttrsPass());
972
David Blaikie0c64f5a2018-01-23 01:25:20 +0000973 // Apply module pipeline start EP callback.
974 for (auto &C : PipelineStartEPCallbacks)
975 C(MPM);
976
Dehao Chen08f88312017-08-07 20:23:20 +0000977 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000978 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
979
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000980 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000981 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
982 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000983
984 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000985 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000986
987 return MPM;
988}
989
990ModulePassManager
991PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
992 bool DebugLogging) {
993 assert(Level != O0 && "Must request optimizations for the default pipeline!");
994
995 ModulePassManager MPM(DebugLogging);
996
997 // Force any function attributes we want the rest of the pipeline to observe.
998 MPM.addPass(ForceFunctionAttrsPass());
999
Dehao Chen08f88312017-08-07 20:23:20 +00001000 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001001 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1002
David Blaikie0c64f5a2018-01-23 01:25:20 +00001003 // Apply module pipeline start EP callback.
1004 for (auto &C : PipelineStartEPCallbacks)
1005 C(MPM);
1006
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001007 // If we are planning to perform ThinLTO later, we don't bloat the code with
1008 // unrolling/vectorization/... now. Just simplify the module as much as we
1009 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001010 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1011 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001012
1013 // Run partial inlining pass to partially inline functions that have
1014 // large bodies.
1015 // FIXME: It isn't clear whether this is really the right place to run this
1016 // in ThinLTO. Because there is another canonicalization and simplification
1017 // phase that will run after the thin link, running this here ends up with
1018 // less information than will be available later and it may grow functions in
1019 // ways that aren't beneficial.
1020 if (RunPartialInlining)
1021 MPM.addPass(PartialInlinerPass());
1022
1023 // Reduce the size of the IR as much as possible.
1024 MPM.addPass(GlobalOptPass());
1025
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001026 return MPM;
1027}
1028
Teresa Johnson28023db2018-07-19 14:51:32 +00001029ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1030 OptimizationLevel Level, bool DebugLogging,
1031 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001032 ModulePassManager MPM(DebugLogging);
1033
Teresa Johnson28023db2018-07-19 14:51:32 +00001034 if (ImportSummary) {
1035 // These passes import type identifier resolutions for whole-program
1036 // devirtualization and CFI. They must run early because other passes may
1037 // disturb the specific instruction patterns that these passes look for,
1038 // creating dependencies on resolutions that may not appear in the summary.
1039 //
1040 // For example, GVN may transform the pattern assume(type.test) appearing in
1041 // two basic blocks into assume(phi(type.test, type.test)), which would
1042 // transform a dependency on a WPD resolution into a dependency on a type
1043 // identifier resolution for CFI.
1044 //
1045 // Also, WPD has access to more precise information than ICP and can
1046 // devirtualize more effectively, so it should operate on the IR first.
1047 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1048 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1049 }
1050
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001051 // Force any function attributes we want the rest of the pipeline to observe.
1052 MPM.addPass(ForceFunctionAttrsPass());
1053
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001054 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001055 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1056 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001057
1058 // Now add the optimization pipeline.
1059 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1060
1061 return MPM;
1062}
1063
1064ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001065PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1066 bool DebugLogging) {
1067 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001068 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001069 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001070 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001071}
1072
Teresa Johnson28023db2018-07-19 14:51:32 +00001073ModulePassManager
1074PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1075 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001076 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1077 ModulePassManager MPM(DebugLogging);
1078
Rong Xudb29a3a2019-03-04 20:21:27 +00001079 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001080 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001081 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001082 PGOOpt->ProfileRemappingFile,
1083 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001084 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1085 // RequireAnalysisPass for PSI before subsequent non-module passes.
1086 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001087 }
1088
Davide Italiano089a9122017-01-24 00:57:39 +00001089 // Remove unused virtual tables to improve the quality of code generated by
1090 // whole-program devirtualization and bitset lowering.
1091 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001092
Davide Italiano089a9122017-01-24 00:57:39 +00001093 // Force any function attributes we want the rest of the pipeline to observe.
1094 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001095
Davide Italiano089a9122017-01-24 00:57:39 +00001096 // Do basic inference of function attributes from known properties of system
1097 // libraries and other oracles.
1098 MPM.addPass(InferFunctionAttrsPass());
1099
1100 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001101 FunctionPassManager EarlyFPM(DebugLogging);
1102 EarlyFPM.addPass(CallSiteSplittingPass());
1103 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1104
Davide Italiano089a9122017-01-24 00:57:39 +00001105 // Indirect call promotion. This should promote all the targets that are
1106 // left by the earlier promotion pass that promotes intra-module targets.
1107 // This two-step promotion is to save the compile time. For LTO, it should
1108 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001109 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001110 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001111 // Propagate constants at call sites into the functions they call. This
1112 // opens opportunities for globalopt (and inlining) by substituting function
1113 // pointers passed as arguments to direct uses of functions.
1114 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001115
1116 // Attach metadata to indirect call sites indicating the set of functions
1117 // they may target at run-time. This should follow IPSCCP.
1118 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001119 }
1120
1121 // Now deduce any function attributes based in the current code.
1122 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1123 PostOrderFunctionAttrsPass()));
1124
1125 // Do RPO function attribute inference across the module to forward-propagate
1126 // attributes where applicable.
1127 // FIXME: Is this really an optimization rather than a canonicalization?
1128 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1129
Eric Christopher721eaef2019-02-26 20:33:22 +00001130 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001131 MPM.addPass(GlobalSplitPass());
1132
1133 // Run whole program optimization of virtual call when the list of callees
1134 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001135 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001136
1137 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001138 if (Level == 1) {
1139 // The LowerTypeTestsPass needs to run to lower type metadata and the
1140 // type.test intrinsics. The pass does nothing if CFI is disabled.
1141 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001142 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001143 }
Davide Italiano089a9122017-01-24 00:57:39 +00001144
1145 // Optimize globals to try and fold them into constants.
1146 MPM.addPass(GlobalOptPass());
1147
1148 // Promote any localized globals to SSA registers.
1149 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1150
1151 // Linking modules together can lead to duplicate global constant, only
1152 // keep one copy of each constant.
1153 MPM.addPass(ConstantMergePass());
1154
1155 // Remove unused arguments from functions.
1156 MPM.addPass(DeadArgumentEliminationPass());
1157
1158 // Reduce the code after globalopt and ipsccp. Both can open up significant
1159 // simplification opportunities, and both can propagate functions through
1160 // function pointers. When this happens, we often have to resolve varargs
1161 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001162 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001163 if (Level == O3)
1164 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001165 PeepholeFPM.addPass(InstCombinePass());
1166 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1167
1168 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001169
1170 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1171 // generally clean up exception handling overhead. It isn't clear this is
1172 // valuable as the inliner doesn't currently care whether it is inlining an
1173 // invoke or a call.
1174 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001175 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1176 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001177
1178 // Optimize globals again after we ran the inliner.
1179 MPM.addPass(GlobalOptPass());
1180
1181 // Garbage collect dead functions.
1182 // FIXME: Add ArgumentPromotion pass after once it's ported.
1183 MPM.addPass(GlobalDCEPass());
1184
1185 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001186 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001187 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001188 invokePeepholeEPCallbacks(FPM, Level);
1189
Davide Italiano089a9122017-01-24 00:57:39 +00001190 FPM.addPass(JumpThreadingPass());
1191
Rong Xudb29a3a2019-03-04 20:21:27 +00001192 // Do a post inline PGO instrumentation and use pass. This is a context
1193 // sensitive PGO pass.
1194 if (PGOOpt) {
1195 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1196 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1197 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1198 PGOOpt->ProfileRemappingFile);
1199 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1200 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1201 /* IsCS */ true, PGOOpt->ProfileFile,
1202 PGOOpt->ProfileRemappingFile);
1203 }
1204
Davide Italiano089a9122017-01-24 00:57:39 +00001205 // Break up allocas
1206 FPM.addPass(SROA());
1207
Robert Lougherf2158a82019-03-20 19:08:18 +00001208 // LTO provides additional opportunities for tailcall elimination due to
1209 // link-time inlining, and visibility of nocapture attribute.
1210 FPM.addPass(TailCallElimPass());
1211
Davide Italiano089a9122017-01-24 00:57:39 +00001212 // Run a few AA driver optimizations here and now to cleanup the code.
1213 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1214
1215 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1216 PostOrderFunctionAttrsPass()));
1217 // FIXME: here we run IP alias analysis in the legacy PM.
1218
1219 FunctionPassManager MainFPM;
1220
1221 // FIXME: once we fix LoopPass Manager, add LICM here.
1222 // FIXME: once we provide support for enabling MLSM, add it here.
1223 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001224 if (RunNewGVN)
1225 MainFPM.addPass(NewGVNPass());
1226 else
1227 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001228
1229 // Remove dead memcpy()'s.
1230 MainFPM.addPass(MemCpyOptPass());
1231
1232 // Nuke dead stores.
1233 MainFPM.addPass(DSEPass());
1234
1235 // FIXME: at this point, we run a bunch of loop passes:
1236 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1237 // loopVectorize. Enable them once the remaining issue with LPM
1238 // are sorted out.
1239
1240 MainFPM.addPass(InstCombinePass());
1241 MainFPM.addPass(SimplifyCFGPass());
1242 MainFPM.addPass(SCCPPass());
1243 MainFPM.addPass(InstCombinePass());
1244 MainFPM.addPass(BDCEPass());
1245
1246 // FIXME: We may want to run SLPVectorizer here.
1247 // After vectorization, assume intrinsics may tell us more
1248 // about pointer alignments.
1249#if 0
1250 MainFPM.add(AlignmentFromAssumptionsPass());
1251#endif
1252
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001253 // FIXME: Conditionally run LoadCombine here, after it's ported
1254 // (in case we still have this pass, given its questionable usefulness).
1255
Davide Italiano089a9122017-01-24 00:57:39 +00001256 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001257 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001258 MainFPM.addPass(JumpThreadingPass());
1259 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1260
1261 // Create a function that performs CFI checks for cross-DSO calls with
1262 // targets in the current module.
1263 MPM.addPass(CrossDSOCFIPass());
1264
1265 // Lower type metadata and the type.test intrinsic. This pass supports
1266 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1267 // to be run at link time if CFI is enabled. This pass does nothing if
1268 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001269 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001270
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001271 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1272 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1273 if (EnableHotColdSplit)
1274 MPM.addPass(HotColdSplittingPass());
1275
Davide Italiano089a9122017-01-24 00:57:39 +00001276 // Add late LTO optimization passes.
1277 // Delete basic blocks, which optimization passes may have killed.
1278 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1279
1280 // Drop bodies of available eternally objects to improve GlobalDCE.
1281 MPM.addPass(EliminateAvailableExternallyPass());
1282
1283 // Now that we have optimized the program, discard unreachable functions.
1284 MPM.addPass(GlobalDCEPass());
1285
1286 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001287 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001288}
1289
Chandler Carruth060ad612016-12-23 20:38:19 +00001290AAManager PassBuilder::buildDefaultAAPipeline() {
1291 AAManager AA;
1292
1293 // The order in which these are registered determines their priority when
1294 // being queried.
1295
1296 // First we register the basic alias analysis that provides the majority of
1297 // per-function local AA logic. This is a stateless, on-demand local set of
1298 // AA techniques.
1299 AA.registerFunctionAnalysis<BasicAA>();
1300
1301 // Next we query fast, specialized alias analyses that wrap IR-embedded
1302 // information about aliasing.
1303 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1304 AA.registerFunctionAnalysis<TypeBasedAA>();
1305
1306 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001307 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1308 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001309 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001310 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001311
1312 return AA;
1313}
1314
Chandler Carruth241bf242016-08-03 07:44:48 +00001315static Optional<int> parseRepeatPassName(StringRef Name) {
1316 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1317 return None;
1318 int Count;
1319 if (Name.getAsInteger(0, Count) || Count <= 0)
1320 return None;
1321 return Count;
1322}
1323
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001324static Optional<int> parseDevirtPassName(StringRef Name) {
1325 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1326 return None;
1327 int Count;
1328 if (Name.getAsInteger(0, Count) || Count <= 0)
1329 return None;
1330 return Count;
1331}
1332
Fedor Sergeevb7871402019-01-10 10:01:53 +00001333static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1334 if (!Name.consume_front(PassName))
1335 return false;
1336 // normal pass name w/o parameters == default parameters
1337 if (Name.empty())
1338 return true;
1339 return Name.startswith("<") && Name.endswith(">");
1340}
1341
1342namespace {
1343
1344/// This performs customized parsing of pass name with parameters.
1345///
1346/// We do not need parametrization of passes in textual pipeline very often,
1347/// yet on a rare occasion ability to specify parameters right there can be
1348/// useful.
1349///
1350/// \p Name - parameterized specification of a pass from a textual pipeline
1351/// is a string in a form of :
1352/// PassName '<' parameter-list '>'
1353///
1354/// Parameter list is being parsed by the parser callable argument, \p Parser,
1355/// It takes a string-ref of parameters and returns either StringError or a
1356/// parameter list in a form of a custom parameters type, all wrapped into
1357/// Expected<> template class.
1358///
1359template <typename ParametersParseCallableT>
1360auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1361 StringRef PassName) -> decltype(Parser(StringRef{})) {
1362 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1363
1364 StringRef Params = Name;
1365 if (!Params.consume_front(PassName)) {
1366 assert(false &&
1367 "unable to strip pass name from parametrized pass specification");
1368 }
1369 if (Params.empty())
1370 return ParametersT{};
1371 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1372 assert(false && "invalid format for parametrized pass name");
1373 }
1374
1375 Expected<ParametersT> Result = Parser(Params);
1376 assert((Result || Result.template errorIsA<StringError>()) &&
1377 "Pass parameter parser can only return StringErrors.");
1378 return std::move(Result);
1379}
1380
1381/// Parser of parameters for LoopUnroll pass.
1382Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1383 LoopUnrollOptions UnrollOpts;
1384 while (!Params.empty()) {
1385 StringRef ParamName;
1386 std::tie(ParamName, Params) = Params.split(';');
1387 int OptLevel = StringSwitch<int>(ParamName)
1388 .Case("O0", 0)
1389 .Case("O1", 1)
1390 .Case("O2", 2)
1391 .Case("O3", 3)
1392 .Default(-1);
1393 if (OptLevel >= 0) {
1394 UnrollOpts.setOptLevel(OptLevel);
1395 continue;
1396 }
1397
1398 bool Enable = !ParamName.consume_front("no-");
1399 if (ParamName == "partial") {
1400 UnrollOpts.setPartial(Enable);
1401 } else if (ParamName == "peeling") {
1402 UnrollOpts.setPeeling(Enable);
1403 } else if (ParamName == "runtime") {
1404 UnrollOpts.setRuntime(Enable);
1405 } else if (ParamName == "upperbound") {
1406 UnrollOpts.setUpperBound(Enable);
1407 } else {
1408 return make_error<StringError>(
1409 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1410 inconvertibleErrorCode());
1411 }
1412 }
1413 return UnrollOpts;
1414}
1415
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001416Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1417 MemorySanitizerOptions Result;
1418 while (!Params.empty()) {
1419 StringRef ParamName;
1420 std::tie(ParamName, Params) = Params.split(';');
1421
1422 if (ParamName == "recover") {
1423 Result.Recover = true;
1424 } else if (ParamName == "kernel") {
1425 Result.Kernel = true;
1426 } else if (ParamName.consume_front("track-origins=")) {
1427 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1428 return make_error<StringError>(
1429 formatv("invalid argument to MemorySanitizer pass track-origins "
1430 "parameter: '{0}' ",
1431 ParamName)
1432 .str(),
1433 inconvertibleErrorCode());
1434 } else {
1435 return make_error<StringError>(
1436 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1437 .str(),
1438 inconvertibleErrorCode());
1439 }
1440 }
1441 return Result;
1442}
1443
Serguei Katkovf5432832019-04-15 08:57:53 +00001444/// Parser of parameters for SimplifyCFG pass.
1445Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1446 SimplifyCFGOptions Result;
1447 while (!Params.empty()) {
1448 StringRef ParamName;
1449 std::tie(ParamName, Params) = Params.split(';');
1450
1451 bool Enable = !ParamName.consume_front("no-");
1452 if (ParamName == "forward-switch-cond") {
1453 Result.forwardSwitchCondToPhi(Enable);
1454 } else if (ParamName == "switch-to-lookup") {
1455 Result.convertSwitchToLookupTable(Enable);
1456 } else if (ParamName == "keep-loops") {
1457 Result.needCanonicalLoops(Enable);
1458 } else if (ParamName == "sink-common-insts") {
1459 Result.sinkCommonInsts(Enable);
1460 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1461 APInt BonusInstThreshold;
1462 if (ParamName.getAsInteger(0, BonusInstThreshold))
1463 return make_error<StringError>(
1464 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1465 "parameter: '{0}' ",
1466 ParamName).str(),
1467 inconvertibleErrorCode());
1468 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1469 } else {
1470 return make_error<StringError>(
1471 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1472 inconvertibleErrorCode());
1473 }
1474 }
1475 return Result;
1476}
1477
Serguei Katkovca6c03a2019-04-18 08:46:11 +00001478/// Parser of parameters for LoopVectorize pass.
1479Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1480 LoopVectorizeOptions Opts;
1481 while (!Params.empty()) {
1482 StringRef ParamName;
1483 std::tie(ParamName, Params) = Params.split(';');
1484
1485 bool Enable = !ParamName.consume_front("no-");
1486 if (ParamName == "interleave-forced-only") {
1487 Opts.setInterleaveOnlyWhenForced(Enable);
1488 } else if (ParamName == "vectorize-forced-only") {
1489 Opts.setVectorizeOnlyWhenForced(Enable);
1490 } else {
1491 return make_error<StringError>(
1492 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1493 inconvertibleErrorCode());
1494 }
1495 }
1496 return Opts;
1497}
1498
Fedor Sergeevb7871402019-01-10 10:01:53 +00001499} // namespace
1500
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001501/// Tests whether a pass name starts with a valid prefix for a default pipeline
1502/// alias.
1503static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1504 return Name.startswith("default") || Name.startswith("thinlto") ||
1505 Name.startswith("lto");
1506}
1507
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001508/// Tests whether registered callbacks will accept a given pass name.
1509///
1510/// When parsing a pipeline text, the type of the outermost pipeline may be
1511/// omitted, in which case the type is automatically determined from the first
1512/// pass name in the text. This may be a name that is handled through one of the
1513/// callbacks. We check this through the oridinary parsing callbacks by setting
1514/// up a dummy PassManager in order to not force the client to also handle this
1515/// type of query.
1516template <typename PassManagerT, typename CallbacksT>
1517static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1518 if (!Callbacks.empty()) {
1519 PassManagerT DummyPM;
1520 for (auto &CB : Callbacks)
1521 if (CB(Name, DummyPM, {}))
1522 return true;
1523 }
1524 return false;
1525}
1526
1527template <typename CallbacksT>
1528static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001529 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001530 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001531 return DefaultAliasRegex.match(Name);
1532
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001533 // Explicitly handle pass manager names.
1534 if (Name == "module")
1535 return true;
1536 if (Name == "cgscc")
1537 return true;
1538 if (Name == "function")
1539 return true;
1540
Chandler Carruth241bf242016-08-03 07:44:48 +00001541 // Explicitly handle custom-parsed pass names.
1542 if (parseRepeatPassName(Name))
1543 return true;
1544
Chandler Carruth74a8a222016-06-17 07:15:29 +00001545#define MODULE_PASS(NAME, CREATE_PASS) \
1546 if (Name == NAME) \
1547 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001548#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001549 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001550 return true;
1551#include "PassRegistry.def"
1552
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001553 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001554}
1555
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001556template <typename CallbacksT>
1557static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001558 // Explicitly handle pass manager names.
1559 if (Name == "cgscc")
1560 return true;
1561 if (Name == "function")
1562 return true;
1563
Chandler Carruth241bf242016-08-03 07:44:48 +00001564 // Explicitly handle custom-parsed pass names.
1565 if (parseRepeatPassName(Name))
1566 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001567 if (parseDevirtPassName(Name))
1568 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001569
Chandler Carruth74a8a222016-06-17 07:15:29 +00001570#define CGSCC_PASS(NAME, CREATE_PASS) \
1571 if (Name == NAME) \
1572 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001573#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001574 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001575 return true;
1576#include "PassRegistry.def"
1577
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001578 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001579}
1580
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001581template <typename CallbacksT>
1582static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001583 // Explicitly handle pass manager names.
1584 if (Name == "function")
1585 return true;
1586 if (Name == "loop")
1587 return true;
1588
Chandler Carruth241bf242016-08-03 07:44:48 +00001589 // Explicitly handle custom-parsed pass names.
1590 if (parseRepeatPassName(Name))
1591 return true;
1592
Chandler Carruth74a8a222016-06-17 07:15:29 +00001593#define FUNCTION_PASS(NAME, CREATE_PASS) \
1594 if (Name == NAME) \
1595 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001596#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1597 if (checkParametrizedPassName(Name, NAME)) \
1598 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001599#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001600 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001601 return true;
1602#include "PassRegistry.def"
1603
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001604 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001605}
1606
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001607template <typename CallbacksT>
1608static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001609 // Explicitly handle pass manager names.
1610 if (Name == "loop")
1611 return true;
1612
Chandler Carruth241bf242016-08-03 07:44:48 +00001613 // Explicitly handle custom-parsed pass names.
1614 if (parseRepeatPassName(Name))
1615 return true;
1616
Chandler Carruth74a8a222016-06-17 07:15:29 +00001617#define LOOP_PASS(NAME, CREATE_PASS) \
1618 if (Name == NAME) \
1619 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001620#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1621 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1622 return true;
1623#include "PassRegistry.def"
1624
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001625 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001626}
1627
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001628Optional<std::vector<PassBuilder::PipelineElement>>
1629PassBuilder::parsePipelineText(StringRef Text) {
1630 std::vector<PipelineElement> ResultPipeline;
1631
1632 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1633 &ResultPipeline};
1634 for (;;) {
1635 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1636 size_t Pos = Text.find_first_of(",()");
1637 Pipeline.push_back({Text.substr(0, Pos), {}});
1638
1639 // If we have a single terminating name, we're done.
1640 if (Pos == Text.npos)
1641 break;
1642
1643 char Sep = Text[Pos];
1644 Text = Text.substr(Pos + 1);
1645 if (Sep == ',')
1646 // Just a name ending in a comma, continue.
1647 continue;
1648
1649 if (Sep == '(') {
1650 // Push the inner pipeline onto the stack to continue processing.
1651 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1652 continue;
1653 }
1654
1655 assert(Sep == ')' && "Bogus separator!");
1656 // When handling the close parenthesis, we greedily consume them to avoid
1657 // empty strings in the pipeline.
1658 do {
1659 // If we try to pop the outer pipeline we have unbalanced parentheses.
1660 if (PipelineStack.size() == 1)
1661 return None;
1662
1663 PipelineStack.pop_back();
1664 } while (Text.consume_front(")"));
1665
1666 // Check if we've finished parsing.
1667 if (Text.empty())
1668 break;
1669
1670 // Otherwise, the end of an inner pipeline always has to be followed by
1671 // a comma, and then we can continue.
1672 if (!Text.consume_front(","))
1673 return None;
1674 }
1675
1676 if (PipelineStack.size() > 1)
1677 // Unbalanced paretheses.
1678 return None;
1679
1680 assert(PipelineStack.back() == &ResultPipeline &&
1681 "Wrong pipeline at the bottom of the stack!");
1682 return {std::move(ResultPipeline)};
1683}
1684
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001685Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1686 const PipelineElement &E,
1687 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001688 auto &Name = E.Name;
1689 auto &InnerPipeline = E.InnerPipeline;
1690
1691 // First handle complex passes like the pass managers which carry pipelines.
1692 if (!InnerPipeline.empty()) {
1693 if (Name == "module") {
1694 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001695 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1696 VerifyEachPass, DebugLogging))
1697 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001698 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001699 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001700 }
1701 if (Name == "cgscc") {
1702 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001703 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1704 DebugLogging))
1705 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001706 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001707 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001708 }
1709 if (Name == "function") {
1710 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001711 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1712 VerifyEachPass, DebugLogging))
1713 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001714 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001715 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001716 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001717 if (auto Count = parseRepeatPassName(Name)) {
1718 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001719 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1720 VerifyEachPass, DebugLogging))
1721 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001722 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001723 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001724 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001725
1726 for (auto &C : ModulePipelineParsingCallbacks)
1727 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001728 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001729
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001730 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001731 return make_error<StringError>(
1732 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1733 inconvertibleErrorCode());
1734 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001735 }
1736
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001737 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001738 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001739 SmallVector<StringRef, 3> Matches;
1740 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001741 return make_error<StringError>(
1742 formatv("unknown default pipeline alias '{0}'", Name).str(),
1743 inconvertibleErrorCode());
1744
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001745 assert(Matches.size() == 3 && "Must capture two matched strings!");
1746
Jordan Rosef85a95f2016-07-25 18:34:51 +00001747 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001748 .Case("O0", O0)
1749 .Case("O1", O1)
1750 .Case("O2", O2)
1751 .Case("O3", O3)
1752 .Case("Os", Os)
1753 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001754 if (L == O0)
1755 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001756 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001757
1758 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001759 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001760 } else if (Matches[1] == "thinlto-pre-link") {
1761 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1762 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001763 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001764 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001765 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001766 } else {
1767 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001768 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001769 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001770 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001771 }
1772
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001773 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001774#define MODULE_PASS(NAME, CREATE_PASS) \
1775 if (Name == NAME) { \
1776 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001777 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001778 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001779#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1780 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001781 MPM.addPass( \
1782 RequireAnalysisPass< \
1783 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001784 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001785 } \
1786 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001787 MPM.addPass(InvalidateAnalysisPass< \
1788 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001789 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001790 }
1791#include "PassRegistry.def"
1792
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001793 for (auto &C : ModulePipelineParsingCallbacks)
1794 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001795 return Error::success();
1796 return make_error<StringError>(
1797 formatv("unknown module pass '{0}'", Name).str(),
1798 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001799}
1800
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001801Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1802 const PipelineElement &E, bool VerifyEachPass,
1803 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001804 auto &Name = E.Name;
1805 auto &InnerPipeline = E.InnerPipeline;
1806
1807 // First handle complex passes like the pass managers which carry pipelines.
1808 if (!InnerPipeline.empty()) {
1809 if (Name == "cgscc") {
1810 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001811 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1812 VerifyEachPass, DebugLogging))
1813 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001814 // Add the nested pass manager with the appropriate adaptor.
1815 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001816 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001817 }
1818 if (Name == "function") {
1819 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001820 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1821 VerifyEachPass, DebugLogging))
1822 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001823 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001824 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001825 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001826 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001827 if (auto Count = parseRepeatPassName(Name)) {
1828 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001829 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1830 VerifyEachPass, DebugLogging))
1831 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001832 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001833 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001834 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001835 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1836 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001837 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1838 VerifyEachPass, DebugLogging))
1839 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001840 CGPM.addPass(
1841 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001842 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001843 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001844
1845 for (auto &C : CGSCCPipelineParsingCallbacks)
1846 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001847 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001848
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001849 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001850 return make_error<StringError>(
1851 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1852 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001853 }
1854
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001855// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001856#define CGSCC_PASS(NAME, CREATE_PASS) \
1857 if (Name == NAME) { \
1858 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001859 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001860 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001861#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1862 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001863 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001864 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001865 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1866 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001867 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001868 } \
1869 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001870 CGPM.addPass(InvalidateAnalysisPass< \
1871 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001872 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001873 }
1874#include "PassRegistry.def"
1875
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001876 for (auto &C : CGSCCPipelineParsingCallbacks)
1877 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001878 return Error::success();
1879 return make_error<StringError>(
1880 formatv("unknown cgscc pass '{0}'", Name).str(),
1881 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001882}
1883
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001884Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1885 const PipelineElement &E,
1886 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001887 auto &Name = E.Name;
1888 auto &InnerPipeline = E.InnerPipeline;
1889
1890 // First handle complex passes like the pass managers which carry pipelines.
1891 if (!InnerPipeline.empty()) {
1892 if (Name == "function") {
1893 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001894 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1895 VerifyEachPass, DebugLogging))
1896 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001897 // Add the nested pass manager with the appropriate adaptor.
1898 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001899 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001900 }
1901 if (Name == "loop") {
1902 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001903 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1904 DebugLogging))
1905 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001906 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001907 FPM.addPass(
1908 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001909 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001910 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001911 if (auto Count = parseRepeatPassName(Name)) {
1912 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001913 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1914 VerifyEachPass, DebugLogging))
1915 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001916 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001917 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001918 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001919
1920 for (auto &C : FunctionPipelineParsingCallbacks)
1921 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001922 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001923
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001924 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001925 return make_error<StringError>(
1926 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1927 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001928 }
1929
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001930// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001931#define FUNCTION_PASS(NAME, CREATE_PASS) \
1932 if (Name == NAME) { \
1933 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001934 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001935 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001936#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1937 if (checkParametrizedPassName(Name, NAME)) { \
1938 auto Params = parsePassParameters(PARSER, Name, NAME); \
1939 if (!Params) \
1940 return Params.takeError(); \
1941 FPM.addPass(CREATE_PASS(Params.get())); \
1942 return Error::success(); \
1943 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001944#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1945 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001946 FPM.addPass( \
1947 RequireAnalysisPass< \
1948 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001949 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001950 } \
1951 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001952 FPM.addPass(InvalidateAnalysisPass< \
1953 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001954 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001955 }
1956#include "PassRegistry.def"
1957
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001958 for (auto &C : FunctionPipelineParsingCallbacks)
1959 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001960 return Error::success();
1961 return make_error<StringError>(
1962 formatv("unknown function pass '{0}'", Name).str(),
1963 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001964}
1965
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001966Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1967 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001968 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001969 auto &InnerPipeline = E.InnerPipeline;
1970
1971 // First handle complex passes like the pass managers which carry pipelines.
1972 if (!InnerPipeline.empty()) {
1973 if (Name == "loop") {
1974 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001975 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1976 VerifyEachPass, DebugLogging))
1977 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001978 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001979 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001980 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001981 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001982 if (auto Count = parseRepeatPassName(Name)) {
1983 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001984 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1985 VerifyEachPass, DebugLogging))
1986 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001987 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001988 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001989 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001990
1991 for (auto &C : LoopPipelineParsingCallbacks)
1992 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001993 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001994
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001995 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001996 return make_error<StringError>(
1997 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1998 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001999 }
2000
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002001// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00002002#define LOOP_PASS(NAME, CREATE_PASS) \
2003 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002004 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002005 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002006 }
2007#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2008 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002009 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002010 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2011 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2012 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002013 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002014 } \
2015 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002016 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00002017 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002018 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002019 }
2020#include "PassRegistry.def"
2021
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002022 for (auto &C : LoopPipelineParsingCallbacks)
2023 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002024 return Error::success();
2025 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2026 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002027}
2028
Chandler Carruthedf59962016-02-18 09:45:17 +00002029bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002030#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2031 if (Name == NAME) { \
2032 AA.registerModuleAnalysis< \
2033 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2034 return true; \
2035 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002036#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2037 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002038 AA.registerFunctionAnalysis< \
2039 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002040 return true; \
2041 }
2042#include "PassRegistry.def"
2043
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002044 for (auto &C : AAParsingCallbacks)
2045 if (C(Name, AA))
2046 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002047 return false;
2048}
2049
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002050Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002051 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002052 bool VerifyEachPass,
2053 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002054 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002055 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2056 return Err;
2057 // FIXME: No verifier support for Loop passes!
2058 }
2059 return Error::success();
2060}
2061
2062Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2063 ArrayRef<PipelineElement> Pipeline,
2064 bool VerifyEachPass,
2065 bool DebugLogging) {
2066 for (const auto &Element : Pipeline) {
2067 if (auto Err =
2068 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2069 return Err;
2070 if (VerifyEachPass)
2071 FPM.addPass(VerifierPass());
2072 }
2073 return Error::success();
2074}
2075
2076Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2077 ArrayRef<PipelineElement> Pipeline,
2078 bool VerifyEachPass,
2079 bool DebugLogging) {
2080 for (const auto &Element : Pipeline) {
2081 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2082 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002083 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002084 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002085 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002086}
2087
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002088void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2089 FunctionAnalysisManager &FAM,
2090 CGSCCAnalysisManager &CGAM,
2091 ModuleAnalysisManager &MAM) {
2092 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2093 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002094 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2095 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2096 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2097 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2098 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2099}
2100
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002101Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2102 ArrayRef<PipelineElement> Pipeline,
2103 bool VerifyEachPass,
2104 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002105 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002106 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2107 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002108 if (VerifyEachPass)
2109 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002110 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002111 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002112}
2113
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002114// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002115// FIXME: Should this routine accept a TargetMachine or require the caller to
2116// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002117Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2118 StringRef PipelineText,
2119 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002120 auto Pipeline = parsePipelineText(PipelineText);
2121 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002122 return make_error<StringError>(
2123 formatv("invalid pipeline '{0}'", PipelineText).str(),
2124 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002125
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002126 // If the first name isn't at the module layer, wrap the pipeline up
2127 // automatically.
2128 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002129
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002130 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2131 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002132 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002133 } else if (isFunctionPassName(FirstName,
2134 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002135 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002136 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002137 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002138 } else {
2139 for (auto &C : TopLevelPipelineParsingCallbacks)
2140 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002141 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002142
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002143 // Unknown pass or pipeline name!
2144 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2145 return make_error<StringError>(
2146 formatv("unknown {0} name '{1}'",
2147 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2148 .str(),
2149 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002150 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002151 }
2152
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002153 if (auto Err =
2154 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2155 return Err;
2156 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002157}
Chandler Carruthedf59962016-02-18 09:45:17 +00002158
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002159// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002160Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2161 StringRef PipelineText,
2162 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002163 auto Pipeline = parsePipelineText(PipelineText);
2164 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002165 return make_error<StringError>(
2166 formatv("invalid pipeline '{0}'", PipelineText).str(),
2167 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002168
2169 StringRef FirstName = Pipeline->front().Name;
2170 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002171 return make_error<StringError>(
2172 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2173 PipelineText)
2174 .str(),
2175 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002176
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002177 if (auto Err =
2178 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2179 return Err;
2180 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002181}
2182
2183// Primary pass pipeline description parsing routine for a \c
2184// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002185Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2186 StringRef PipelineText,
2187 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002188 auto Pipeline = parsePipelineText(PipelineText);
2189 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002190 return make_error<StringError>(
2191 formatv("invalid pipeline '{0}'", PipelineText).str(),
2192 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002193
2194 StringRef FirstName = Pipeline->front().Name;
2195 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002196 return make_error<StringError>(
2197 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2198 PipelineText)
2199 .str(),
2200 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002201
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002202 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2203 DebugLogging))
2204 return Err;
2205 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002206}
2207
2208// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002209Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2210 StringRef PipelineText,
2211 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002212 auto Pipeline = parsePipelineText(PipelineText);
2213 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002214 return make_error<StringError>(
2215 formatv("invalid pipeline '{0}'", PipelineText).str(),
2216 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002217
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002218 if (auto Err =
2219 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2220 return Err;
2221
2222 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002223}
2224
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002225Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002226 // If the pipeline just consists of the word 'default' just replace the AA
2227 // manager with our default one.
2228 if (PipelineText == "default") {
2229 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002230 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002231 }
2232
Chandler Carruthedf59962016-02-18 09:45:17 +00002233 while (!PipelineText.empty()) {
2234 StringRef Name;
2235 std::tie(Name, PipelineText) = PipelineText.split(',');
2236 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002237 return make_error<StringError>(
2238 formatv("unknown alias analysis name '{0}'", Name).str(),
2239 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002240 }
2241
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002242 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002243}