blob: 3a0d0c29466abebd6b762b178d9b39aa401d5a28 [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"
Leonard Chan0cdd3b12019-05-14 21:17:21 +000097#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
Manman Ren18295122019-02-28 20:13:38 +000098#include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000099#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +0000100#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +0000101#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +0000102#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000103#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000104#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000105#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000106#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000107#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000108#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000109#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000110#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000111#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000112#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000113#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000114#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000115#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000116#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000117#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000118#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000119#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000120#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000121#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000122#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000123#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000124#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000125#include "llvm/Transforms/Scalar/LoopDistribute.h"
Kit Barton3cdf8792019-04-17 18:53:27 +0000126#include "llvm/Transforms/Scalar/LoopFuse.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000127#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000128#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000129#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000130#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000131#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000132#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000133#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000134#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000135#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000136#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000137#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000138#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000139#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000140#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000141#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000142#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000143#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000144#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Clement Courbet43882b12019-05-23 12:35:26 +0000145#include "llvm/Transforms/Scalar/MergeICmps.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000146#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000147#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000148#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000149#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000150#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000151#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000152#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000153#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000154#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000155#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000156#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000157#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000158#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000159#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000160#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000161#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000162#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000163#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000164#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000165#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000166#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000167#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000168#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000169#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000170#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000171#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000172#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000173#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000174#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000175
Chandler Carruth66445382014-01-11 08:16:35 +0000176using namespace llvm;
177
Chandler Carruth719ffe12017-02-12 05:38:04 +0000178static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
179 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000180static cl::opt<bool>
181 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
182 cl::Hidden, cl::ZeroOrMore,
183 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000184
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000185static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000186 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000187 cl::Hidden, cl::ZeroOrMore,
188 cl::desc("Run NewGVN instead of GVN"));
189
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000190static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000191 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
192 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000193
Davide Italianobe1b6a92017-06-03 23:18:29 +0000194static cl::opt<bool> EnableGVNSink(
195 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
196 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
197
David Green963401d2018-07-01 12:47:30 +0000198static cl::opt<bool> EnableUnrollAndJam(
199 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
200 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
201
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000202static cl::opt<bool> EnableSyntheticCounts(
203 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
204 cl::desc("Run synthetic function entry count generation "
205 "pass"));
206
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000207static Regex DefaultAliasRegex(
208 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000209
Eric Christophereff3b6f2019-04-18 06:17:40 +0000210// This option is used in simplifying testing SampleFDO optimizations for
211// profile loading.
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000212static cl::opt<bool>
213 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
214 cl::desc("Enable control height reduction optimization (CHR)"));
215
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000216PipelineTuningOptions::PipelineTuningOptions() {
217 LoopInterleaving = EnableLoopInterleaving;
218 LoopVectorization = EnableLoopVectorization;
Alina Sbirlea458c7332019-05-08 17:58:35 +0000219 SLPVectorization = RunSLPVectorization;
Alina Sbirleae4b27862019-05-23 19:35:40 +0000220 LoopUnrolling = true;
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000221 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
Alina Sbirlea43709f72019-04-19 17:46:50 +0000222 LicmMssaOptCap = SetLicmMssaOptCap;
223 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000224}
225
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000226extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000227extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000228
Wei Mi3bcccdf2019-01-17 20:48:34 +0000229extern cl::opt<bool> FlattenedProfileUsed;
230
Chandler Carruthe3f50642016-12-22 06:59:15 +0000231static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
232 switch (Level) {
233 case PassBuilder::O0:
234 case PassBuilder::O1:
235 case PassBuilder::O2:
236 case PassBuilder::O3:
237 return false;
238
239 case PassBuilder::Os:
240 case PassBuilder::Oz:
241 return true;
242 }
243 llvm_unreachable("Invalid optimization level!");
244}
245
Chandler Carruth66445382014-01-11 08:16:35 +0000246namespace {
247
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000248/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000249struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000250 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000251 return PreservedAnalyses::all();
252 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000253 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000254};
255
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000256/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000257class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
258 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000259 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000260
261public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000262 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000263 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000264 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000265};
266
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000267/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000268struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000269 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
270 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000271 return PreservedAnalyses::all();
272 }
273 static StringRef name() { return "NoOpCGSCCPass"; }
274};
275
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000276/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000277class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
278 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000279 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000280
281public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000282 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000283 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000284 return Result();
285 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000286 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000287};
288
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000289/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000290struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000291 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000292 return PreservedAnalyses::all();
293 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000294 static StringRef name() { return "NoOpFunctionPass"; }
295};
296
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000297/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000298class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
299 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000300 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000301
302public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000303 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000304 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000305 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000306};
307
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000308/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000309struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000310 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
311 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000312 return PreservedAnalyses::all();
313 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000314 static StringRef name() { return "NoOpLoopPass"; }
315};
316
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000317/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000318class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
319 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000320 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000321
322public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000323 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000324 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
325 return Result();
326 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000327 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000328};
329
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000330AnalysisKey NoOpModuleAnalysis::Key;
331AnalysisKey NoOpCGSCCAnalysis::Key;
332AnalysisKey NoOpFunctionAnalysis::Key;
333AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000334
Chandler Carruth66445382014-01-11 08:16:35 +0000335} // End anonymous namespace.
336
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000337void PassBuilder::invokePeepholeEPCallbacks(
338 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
339 for (auto &C : PeepholeEPCallbacks)
340 C(FPM, Level);
341}
342
Chandler Carruth1ff77242015-03-07 09:02:36 +0000343void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000344#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000345 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000346#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000347
348 for (auto &C : ModuleAnalysisRegistrationCallbacks)
349 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000350}
351
Chandler Carruth1ff77242015-03-07 09:02:36 +0000352void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000353#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000354 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000355#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000356
357 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
358 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000359}
360
Chandler Carruth1ff77242015-03-07 09:02:36 +0000361void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000362#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000363 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000364#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000365
366 for (auto &C : FunctionAnalysisRegistrationCallbacks)
367 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000368}
369
Justin Bognereecc3c82016-02-25 07:23:08 +0000370void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000371#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000372 LAM.registerPass([&] { return CREATE_PASS; });
373#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000374
375 for (auto &C : LoopAnalysisRegistrationCallbacks)
376 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000377}
378
Chandler Carruthe3f50642016-12-22 06:59:15 +0000379FunctionPassManager
380PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000381 ThinLTOPhase Phase,
382 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000383 assert(Level != O0 && "Must request optimizations!");
384 FunctionPassManager FPM(DebugLogging);
385
386 // Form SSA out of local memory accesses after breaking apart aggregates into
387 // scalars.
388 FPM.addPass(SROA());
389
390 // Catch trivial redundancies
Eric Christopherdfebd842019-04-19 22:18:53 +0000391 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000392
Davide Italianoc3688312017-06-01 23:08:14 +0000393 // Hoisting of scalars and load expressions.
394 if (EnableGVNHoist)
395 FPM.addPass(GVNHoistPass());
396
Davide Italianobe1b6a92017-06-03 23:18:29 +0000397 // Global value numbering based sinking.
398 if (EnableGVNSink) {
399 FPM.addPass(GVNSinkPass());
400 FPM.addPass(SimplifyCFGPass());
401 }
402
Chandler Carruthe3f50642016-12-22 06:59:15 +0000403 // Speculative execution if the target has divergent branches; otherwise nop.
404 FPM.addPass(SpeculativeExecutionPass());
405
406 // Optimize based on known information about branches, and cleanup afterward.
407 FPM.addPass(JumpThreadingPass());
408 FPM.addPass(CorrelatedValuePropagationPass());
409 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000410 if (Level == O3)
411 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000412 FPM.addPass(InstCombinePass());
413
414 if (!isOptimizingForSize(Level))
415 FPM.addPass(LibCallsShrinkWrapPass());
416
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000417 invokePeepholeEPCallbacks(FPM, Level);
418
Rong Xue1f42452017-10-23 22:21:29 +0000419 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
420 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000421 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000422 !isOptimizingForSize(Level))
423 FPM.addPass(PGOMemOPSizeOpt());
424
Chandler Carruthe3f50642016-12-22 06:59:15 +0000425 FPM.addPass(TailCallElimPass());
426 FPM.addPass(SimplifyCFGPass());
427
428 // Form canonically associated expression trees, and simplify the trees using
429 // basic mathematical properties. For example, this will form (nearly)
430 // minimal multiplication trees.
431 FPM.addPass(ReassociatePass());
432
433 // Add the primary loop simplification pipeline.
434 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000435 // some function passes in between them. These can and should be removed
436 // and/or replaced by scheduling the loop pass equivalents in the correct
437 // positions. But those equivalent passes aren't powerful enough yet.
438 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
439 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
440 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
441 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000442 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
443
Chandler Carruth71fd2702018-05-30 02:46:45 +0000444 // Simplify the loop body. We do this initially to clean up after other loop
445 // passes run, either when iterating on a loop or on inner loops with
446 // implications on the outer loop.
447 LPM1.addPass(LoopInstSimplifyPass());
448 LPM1.addPass(LoopSimplifyCFGPass());
449
Chandler Carruthe3f50642016-12-22 06:59:15 +0000450 // Rotate Loop - disable header duplication at -Oz
451 LPM1.addPass(LoopRotatePass(Level != Oz));
Alina Sbirlea43709f72019-04-19 17:46:50 +0000452 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
Chandler Carruth86248d52017-05-26 01:24:11 +0000453 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000454 LPM2.addPass(IndVarSimplifyPass());
455 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000456
457 for (auto &C : LateLoopOptimizationsEPCallbacks)
458 C(LPM2, Level);
459
Chandler Carruth79b733b2017-01-26 23:21:17 +0000460 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000461 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000462 // because it changes IR to makes profile annotation in back compile
463 // inaccurate.
Alina Sbirleae4b27862019-05-23 19:35:40 +0000464 if ((Phase != ThinLTOPhase::PreLink || !PGOOpt ||
465 PGOOpt->Action != PGOOptions::SampleUse) &&
466 PTO.LoopUnrolling)
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000467 LPM2.addPass(
468 LoopFullUnrollPass(Level, false, PTO.ForgetAllSCEVInLoopUnroll));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000469
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000470 for (auto &C : LoopOptimizerEndEPCallbacks)
471 C(LPM2, Level);
472
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000473 // We provide the opt remark emitter pass for LICM to use. We only need to do
474 // this once as it is immutable.
475 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000476 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000477 FPM.addPass(SimplifyCFGPass());
478 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000479 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000480
481 // Eliminate redundancies.
482 if (Level != O1) {
483 // These passes add substantial compile time so skip them at O1.
484 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000485 if (RunNewGVN)
486 FPM.addPass(NewGVNPass());
487 else
488 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000489 }
490
491 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
492 FPM.addPass(MemCpyOptPass());
493
494 // Sparse conditional constant propagation.
495 // FIXME: It isn't clear why we do this *after* loop passes rather than
496 // before...
497 FPM.addPass(SCCPPass());
498
499 // Delete dead bit computations (instcombine runs after to fold away the dead
500 // computations, and then ADCE will run later to exploit any new DCE
501 // opportunities that creates).
502 FPM.addPass(BDCEPass());
503
504 // Run instcombine after redundancy and dead bit elimination to exploit
505 // opportunities opened up by them.
506 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000507 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000508
509 // Re-consider control flow based optimizations after redundancy elimination,
510 // redo DCE, etc.
511 FPM.addPass(JumpThreadingPass());
512 FPM.addPass(CorrelatedValuePropagationPass());
513 FPM.addPass(DSEPass());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000514 FPM.addPass(createFunctionToLoopPassAdaptor(
515 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
516 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000517
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000518 for (auto &C : ScalarOptimizerLateEPCallbacks)
519 C(FPM, Level);
520
Chandler Carruthe3f50642016-12-22 06:59:15 +0000521 // Finally, do an expensive DCE pass to catch all the dead code exposed by
522 // the simplifications and basic cleanup after all the simplifications.
523 FPM.addPass(ADCEPass());
524 FPM.addPass(SimplifyCFGPass());
525 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000526 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000527
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000528 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000529 (PGOOpt->Action == PGOOptions::IRUse ||
530 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000531 FPM.addPass(ControlHeightReductionPass());
532
Chandler Carruthe3f50642016-12-22 06:59:15 +0000533 return FPM;
534}
535
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000536void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
537 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000538 bool RunProfileGen, bool IsCS,
539 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000540 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000541 // Generally running simplification passes and the inliner with an high
542 // threshold results in smaller executables, but there may be cases where
543 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000544 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
545 // IsCS is true).
546 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000547 InlineParams IP;
548
549 // In the old pass manager, this is a cl::opt. Should still this be one?
550 IP.DefaultThreshold = 75;
551
552 // FIXME: The hint threshold has the same value used by the regular inliner.
553 // This should probably be lowered after performance testing.
554 // FIXME: this comment is cargo culted from the old pass manager, revisit).
555 IP.HintThreshold = 325;
556
557 CGSCCPassManager CGPipeline(DebugLogging);
558
559 CGPipeline.addPass(InlinerPass(IP));
560
561 FunctionPassManager FPM;
562 FPM.addPass(SROA());
563 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
564 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
565 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000566 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000567
Davide Italiano513dfaa2017-02-13 15:26:22 +0000568 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
569
570 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
571 }
572
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000573 // Delete anything that is now dead to make sure that we don't instrument
574 // dead code. Instrumentation can end up keeping dead code around and
575 // dramatically increase code size.
576 MPM.addPass(GlobalDCEPass());
577
Davide Italiano513dfaa2017-02-13 15:26:22 +0000578 if (RunProfileGen) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000579 MPM.addPass(PGOInstrumentationGen(IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000580
Xinliang David Lib67530e2017-06-25 00:26:43 +0000581 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000582 FPM.addPass(
583 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000584 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
585
Davide Italiano513dfaa2017-02-13 15:26:22 +0000586 // Add the profile lowering pass.
587 InstrProfOptions Options;
Rong Xudb29a3a2019-03-04 20:21:27 +0000588 if (!ProfileFile.empty())
589 Options.InstrProfileOutput = ProfileFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000590 Options.DoCounterPromotion = true;
Rong Xudb29a3a2019-03-04 20:21:27 +0000591 Options.UseBFIInPromotion = IsCS;
592 MPM.addPass(InstrProfiling(Options, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000593 } else if (!ProfileFile.empty()) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000594 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000595 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
596 // RequireAnalysisPass for PSI before subsequent non-module passes.
597 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
598 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000599}
600
Easwaran Raman8249fac2017-06-28 13:33:49 +0000601static InlineParams
602getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
603 auto O3 = PassBuilder::O3;
604 unsigned OptLevel = Level > O3 ? 2 : Level;
605 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
606 return getInlineParams(OptLevel, SizeLevel);
607}
608
Chandler Carruthe3f50642016-12-22 06:59:15 +0000609ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000610PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000611 ThinLTOPhase Phase,
612 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000613 ModulePassManager MPM(DebugLogging);
614
Rong Xudb29a3a2019-03-04 20:21:27 +0000615 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000616
617 // In ThinLTO mode, when flattened profile is used, all the available
618 // profile information will be annotated in PreLink phase so there is
619 // no need to load the profile again in PostLink.
620 bool LoadSampleProfile =
621 HasSampleProfile &&
622 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
623
624 // During the ThinLTO backend phase we perform early indirect call promotion
625 // here, before globalopt. Otherwise imported available_externally functions
626 // look unreferenced and are removed. If we are going to load the sample
627 // profile then defer until later.
628 // TODO: See if we can move later and consolidate with the location where
629 // we perform ICP when we are loading a sample profile.
630 // TODO: We pass HasSampleProfile (whether there was a sample profile file
631 // passed to the compile) to the SamplePGO flag of ICP. This is used to
632 // determine whether the new direct calls are annotated with prof metadata.
633 // Ideally this should be determined from whether the IR is annotated with
634 // sample profile, and not whether the a sample profile was provided on the
635 // command line. E.g. for flattened profiles where we will not be reloading
636 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
637 // provide the sample profile file.
638 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
639 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
640
Chandler Carruthe3f50642016-12-22 06:59:15 +0000641 // Do basic inference of function attributes from known properties of system
642 // libraries and other oracles.
643 MPM.addPass(InferFunctionAttrsPass());
644
645 // Create an early function pass manager to cleanup the output of the
646 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000647 FunctionPassManager EarlyFPM(DebugLogging);
648 EarlyFPM.addPass(SimplifyCFGPass());
649 EarlyFPM.addPass(SROA());
650 EarlyFPM.addPass(EarlyCSEPass());
651 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000652 if (Level == O3)
653 EarlyFPM.addPass(CallSiteSplittingPass());
654
Dehao Chen08f88312017-08-07 20:23:20 +0000655 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
656 // to convert bitcast to direct calls so that they can be inlined during the
657 // profile annotation prepration step.
658 // More details about SamplePGO design can be found in:
659 // https://research.google.com/pubs/pub45290.html
660 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000661 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000662 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000663 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000664
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000665 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000666 // Annotate sample profile right after early FPM to ensure freshness of
667 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000668 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000669 PGOOpt->ProfileRemappingFile,
670 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000671 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
672 // RequireAnalysisPass for PSI before subsequent non-module passes.
673 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000674 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
675 // for the profile annotation to be accurate in the ThinLTO backend.
676 if (Phase != ThinLTOPhase::PreLink)
677 // We perform early indirect call promotion here, before globalopt.
678 // This is important for the ThinLTO backend phase because otherwise
679 // imported available_externally functions look unreferenced and are
680 // removed.
681 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000682 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000683 }
684
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000685 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000686 // and prior to optimizing globals.
687 // FIXME: This position in the pipeline hasn't been carefully considered in
688 // years, it should be re-analyzed.
689 MPM.addPass(IPSCCPPass());
690
Matthew Simpsoncb585582017-10-25 13:40:08 +0000691 // Attach metadata to indirect call sites indicating the set of functions
692 // they may target at run-time. This should follow IPSCCP.
693 MPM.addPass(CalledValuePropagationPass());
694
Chandler Carruthe3f50642016-12-22 06:59:15 +0000695 // Optimize globals to try and fold them into constants.
696 MPM.addPass(GlobalOptPass());
697
698 // Promote any localized globals to SSA registers.
699 // FIXME: Should this instead by a run of SROA?
700 // FIXME: We should probably run instcombine and simplify-cfg afterward to
701 // delete control flows that are dead once globals have been folded to
702 // constants.
703 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
704
705 // Remove any dead arguments exposed by cleanups and constand folding
706 // globals.
707 MPM.addPass(DeadArgumentEliminationPass());
708
709 // Create a small function pass pipeline to cleanup after all the global
710 // optimizations.
711 FunctionPassManager GlobalCleanupPM(DebugLogging);
712 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000713 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
714
Chandler Carruthe3f50642016-12-22 06:59:15 +0000715 GlobalCleanupPM.addPass(SimplifyCFGPass());
716 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
717
Dehao Chen89d32262017-08-02 01:28:31 +0000718 // Add all the requested passes for instrumentation PGO, if requested.
719 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000720 (PGOOpt->Action == PGOOptions::IRInstr ||
721 PGOOpt->Action == PGOOptions::IRUse)) {
722 addPGOInstrPasses(MPM, DebugLogging, Level,
723 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
724 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000725 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000726 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000727 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000728 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
729 PGOOpt->CSAction == PGOOptions::CSIRInstr)
730 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000731
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000732 // Synthesize function entry counts for non-PGO compilation.
733 if (EnableSyntheticCounts && !PGOOpt)
734 MPM.addPass(SyntheticCountsPropagation());
735
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000736 // Require the GlobalsAA analysis for the module so we can query it within
737 // the CGSCC pipeline.
738 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000739
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000740 // Require the ProfileSummaryAnalysis for the module so we can query it within
741 // the inliner pass.
742 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
743
Chandler Carruthe3f50642016-12-22 06:59:15 +0000744 // Now begin the main postorder CGSCC pipeline.
745 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
746 // manager and trying to emulate its precise behavior. Much of this doesn't
747 // make a lot of sense and we should revisit the core CGSCC structure.
748 CGSCCPassManager MainCGPipeline(DebugLogging);
749
750 // Note: historically, the PruneEH pass was run first to deduce nounwind and
751 // generally clean up exception handling overhead. It isn't clear this is
752 // valuable as the inliner doesn't currently care whether it is inlining an
753 // invoke or a call.
754
755 // Run the inliner first. The theory is that we are walking bottom-up and so
756 // the callees have already been fully optimized, and we want to inline them
757 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000758 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000759 // because it makes profile annotation in the backend inaccurate.
760 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000761 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
762 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000763 IP.HotCallSiteThreshold = 0;
764 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000765
766 // Now deduce any function attributes based in the current code.
767 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
768
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000769 // When at O3 add argument promotion to the pass pipeline.
770 // FIXME: It isn't at all clear why this should be limited to O3.
771 if (Level == O3)
772 MainCGPipeline.addPass(ArgumentPromotionPass());
773
Chandler Carruthe3f50642016-12-22 06:59:15 +0000774 // Lastly, add the core function simplification pipeline nested inside the
775 // CGSCC walk.
776 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000777 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000778
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000779 for (auto &C : CGSCCOptimizerLateEPCallbacks)
780 C(MainCGPipeline, Level);
781
Chandler Carruth719ffe12017-02-12 05:38:04 +0000782 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
783 // to detect when we devirtualize indirect calls and iterate the SCC passes
784 // in that case to try and catch knock-on inlining or function attrs
785 // opportunities. Then we add it to the module pipeline by walking the SCCs
786 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000787 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000788 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000789 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000790
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000791 return MPM;
792}
793
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000794ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
795 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000796 ModulePassManager MPM(DebugLogging);
797
798 // Optimize globals now that the module is fully simplified.
799 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000800 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000801
Xinliang David Li126157c2017-05-22 16:41:57 +0000802 // Run partial inlining pass to partially inline functions that have
803 // large bodies.
804 if (RunPartialInlining)
805 MPM.addPass(PartialInlinerPass());
806
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000807 // Remove avail extern fns and globals definitions since we aren't compiling
808 // an object file for later LTO. For LTO we want to preserve these so they
809 // are eligible for inlining at link-time. Note if they are unreferenced they
810 // will be removed by GlobalDCE later, so this only impacts referenced
811 // available externally globals. Eventually they will be suppressed during
812 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
813 // may make globals referenced by available external functions dead and saves
814 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000815 MPM.addPass(EliminateAvailableExternallyPass());
816
Manman Ren18295122019-02-28 20:13:38 +0000817 if (EnableOrderFileInstrumentation)
818 MPM.addPass(InstrOrderFilePass());
819
Chandler Carruthe3f50642016-12-22 06:59:15 +0000820 // Do RPO function attribute inference across the module to forward-propagate
821 // attributes where applicable.
822 // FIXME: Is this really an optimization rather than a canonicalization?
823 MPM.addPass(ReversePostOrderFunctionAttrsPass());
824
Rong Xudb29a3a2019-03-04 20:21:27 +0000825 // Do a post inline PGO instrumentation and use pass. This is a context
826 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
827 // cross-module inline has not been done yet. The context sensitive
828 // instrumentation is after all the inlines are done.
829 if (!LTOPreLink && PGOOpt) {
830 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
831 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
832 /* IsCS */ true, PGOOpt->CSProfileGenFile,
833 PGOOpt->ProfileRemappingFile);
834 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
835 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
836 /* IsCS */ true, PGOOpt->ProfileFile,
837 PGOOpt->ProfileRemappingFile);
838 }
839
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000840 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000841 // useful as the above will have inlined, DCE'ed, and function-attr
842 // propagated everything. We should at this point have a reasonably minimal
843 // and richly annotated call graph. By computing aliasing and mod/ref
844 // information for all local globals here, the late loop passes and notably
845 // the vectorizer will be able to use them to help recognize vectorizable
846 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000847 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000848
849 FunctionPassManager OptimizePM(DebugLogging);
850 OptimizePM.addPass(Float2IntPass());
851 // FIXME: We need to run some loop optimizations to re-rotate loops after
852 // simplify-cfg and others undo their rotation.
853
854 // Optimize the loop execution. These passes operate on entire loop nests
855 // rather than on each loop in an inside-out manner, and so they are actually
856 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000857
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000858 for (auto &C : VectorizerStartEPCallbacks)
859 C(OptimizePM, Level);
860
Chandler Carrutha95ff382017-01-27 00:50:21 +0000861 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000862 OptimizePM.addPass(
863 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000864
865 // Distribute loops to allow partial vectorization. I.e. isolate dependences
866 // into separate loop that would otherwise inhibit vectorization. This is
867 // currently only performed for loops marked with the metadata
868 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000869 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000870
871 // Now run the core loop vectorizer.
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000872 OptimizePM.addPass(LoopVectorizePass(
873 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000874
Chandler Carruthbaabda92017-01-27 01:32:26 +0000875 // Eliminate loads by forwarding stores from the previous iteration to loads
876 // of the current iteration.
877 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000878
879 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000880 OptimizePM.addPass(InstCombinePass());
881
Chandler Carrutha95ff382017-01-27 00:50:21 +0000882 // Now that we've formed fast to execute loop structures, we do further
883 // optimizations. These are run afterward as they might block doing complex
884 // analyses and transforms such as what are needed for loop vectorization.
885
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000886 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
887 // GVN, loop transforms, and others have already run, so it's now better to
888 // convert to more optimized IR using more aggressive simplify CFG options.
889 // The extra sinking transform can create larger basic blocks, so do this
890 // before SLP vectorization.
891 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
892 forwardSwitchCondToPhi(true).
893 convertSwitchToLookupTable(true).
894 needCanonicalLoops(false).
895 sinkCommonInsts(true)));
896
Chandler Carruthe3f50642016-12-22 06:59:15 +0000897 // Optimize parallel scalar instruction chains into SIMD instructions.
Alina Sbirlea458c7332019-05-08 17:58:35 +0000898 if (PTO.SLPVectorization)
899 OptimizePM.addPass(SLPVectorizerPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000900
Chandler Carruthe3f50642016-12-22 06:59:15 +0000901 OptimizePM.addPass(InstCombinePass());
902
903 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000904 // execution resources of an out-of-order processor. We also then need to
905 // clean up redundancies and loop invariant code.
906 // FIXME: It would be really good to use a loop-integrated instruction
907 // combiner for cleanup here so that the unrolling and LICM can be pipelined
908 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000909 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
910 if (EnableUnrollAndJam) {
911 OptimizePM.addPass(
912 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
913 }
Alina Sbirleae4b27862019-05-23 19:35:40 +0000914 if (PTO.LoopUnrolling)
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000915 OptimizePM.addPass(LoopUnrollPass(
916 LoopUnrollOptions(Level, false, PTO.ForgetAllSCEVInLoopUnroll)));
Michael Kruse72448522018-12-12 17:32:52 +0000917 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000918 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000919 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000920 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
921 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
922 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000923
924 // Now that we've vectorized and unrolled loops, we may have more refined
925 // alignment information, try to re-derive it here.
926 OptimizePM.addPass(AlignmentFromAssumptionsPass());
927
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000928 // Split out cold code. Splitting is done late to avoid hiding context from
929 // other optimizations and inadvertently regressing performance. The tradeoff
930 // is that this has a higher code size cost than splitting early.
931 if (EnableHotColdSplit && !LTOPreLink)
932 MPM.addPass(HotColdSplittingPass());
933
Chandler Carrutha95ff382017-01-27 00:50:21 +0000934 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
935 // canonicalization pass that enables other optimizations. As a result,
936 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
937 // result too early.
938 OptimizePM.addPass(LoopSinkPass());
939
940 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000941 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000942
Sanjay Patel6fd43912017-09-09 13:38:18 +0000943 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
944 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
945 // flattening of blocks.
946 OptimizePM.addPass(DivRemPairsPass());
947
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000948 // LoopSink (and other loop passes since the last simplifyCFG) might have
949 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
950 OptimizePM.addPass(SimplifyCFGPass());
951
Chandler Carruthc34f7892017-11-28 11:32:31 +0000952 // Optimize PHIs by speculating around them when profitable. Note that this
953 // pass needs to be run after any PRE or similar pass as it is essentially
Joerg Sonnenbergerec6ee792019-05-16 18:01:57 +0000954 // inserting redundancies into the program. This even includes SimplifyCFG.
Chandler Carruthc34f7892017-11-28 11:32:31 +0000955 OptimizePM.addPass(SpeculateAroundPHIsPass());
956
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000957 for (auto &C : OptimizerLastEPCallbacks)
958 C(OptimizePM, Level);
959
Chandler Carrutha95ff382017-01-27 00:50:21 +0000960 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000961 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
962
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000963 MPM.addPass(CGProfilePass());
964
Chandler Carruthe3f50642016-12-22 06:59:15 +0000965 // Now we need to do some global optimization transforms.
966 // FIXME: It would seem like these should come first in the optimization
967 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
968 // ordering here.
969 MPM.addPass(GlobalDCEPass());
970 MPM.addPass(ConstantMergePass());
971
972 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000973}
974
Chandler Carruthe3f50642016-12-22 06:59:15 +0000975ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000976PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000977 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000978 assert(Level != O0 && "Must request optimizations for the default pipeline!");
979
980 ModulePassManager MPM(DebugLogging);
981
982 // Force any function attributes we want the rest of the pipeline to observe.
983 MPM.addPass(ForceFunctionAttrsPass());
984
David Blaikie0c64f5a2018-01-23 01:25:20 +0000985 // Apply module pipeline start EP callback.
986 for (auto &C : PipelineStartEPCallbacks)
987 C(MPM);
988
Dehao Chen08f88312017-08-07 20:23:20 +0000989 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000990 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
991
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000992 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000993 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
994 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000995
996 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000997 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000998
999 return MPM;
1000}
1001
1002ModulePassManager
1003PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1004 bool DebugLogging) {
1005 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1006
1007 ModulePassManager MPM(DebugLogging);
1008
1009 // Force any function attributes we want the rest of the pipeline to observe.
1010 MPM.addPass(ForceFunctionAttrsPass());
1011
Dehao Chen08f88312017-08-07 20:23:20 +00001012 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001013 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1014
David Blaikie0c64f5a2018-01-23 01:25:20 +00001015 // Apply module pipeline start EP callback.
1016 for (auto &C : PipelineStartEPCallbacks)
1017 C(MPM);
1018
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001019 // If we are planning to perform ThinLTO later, we don't bloat the code with
1020 // unrolling/vectorization/... now. Just simplify the module as much as we
1021 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001022 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1023 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001024
1025 // Run partial inlining pass to partially inline functions that have
1026 // large bodies.
1027 // FIXME: It isn't clear whether this is really the right place to run this
1028 // in ThinLTO. Because there is another canonicalization and simplification
1029 // phase that will run after the thin link, running this here ends up with
1030 // less information than will be available later and it may grow functions in
1031 // ways that aren't beneficial.
1032 if (RunPartialInlining)
1033 MPM.addPass(PartialInlinerPass());
1034
1035 // Reduce the size of the IR as much as possible.
1036 MPM.addPass(GlobalOptPass());
1037
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001038 return MPM;
1039}
1040
Teresa Johnson28023db2018-07-19 14:51:32 +00001041ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1042 OptimizationLevel Level, bool DebugLogging,
1043 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001044 ModulePassManager MPM(DebugLogging);
1045
Teresa Johnson28023db2018-07-19 14:51:32 +00001046 if (ImportSummary) {
1047 // These passes import type identifier resolutions for whole-program
1048 // devirtualization and CFI. They must run early because other passes may
1049 // disturb the specific instruction patterns that these passes look for,
1050 // creating dependencies on resolutions that may not appear in the summary.
1051 //
1052 // For example, GVN may transform the pattern assume(type.test) appearing in
1053 // two basic blocks into assume(phi(type.test, type.test)), which would
1054 // transform a dependency on a WPD resolution into a dependency on a type
1055 // identifier resolution for CFI.
1056 //
1057 // Also, WPD has access to more precise information than ICP and can
1058 // devirtualize more effectively, so it should operate on the IR first.
Teresa Johnson867bc392019-04-23 18:56:19 +00001059 //
1060 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1061 // metadata and intrinsics.
Teresa Johnson28023db2018-07-19 14:51:32 +00001062 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1063 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1064 }
1065
Teresa Johnson867bc392019-04-23 18:56:19 +00001066 if (Level == O0)
1067 return MPM;
1068
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001069 // Force any function attributes we want the rest of the pipeline to observe.
1070 MPM.addPass(ForceFunctionAttrsPass());
1071
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001072 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001073 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1074 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001075
1076 // Now add the optimization pipeline.
1077 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1078
1079 return MPM;
1080}
1081
1082ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001083PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1084 bool DebugLogging) {
1085 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001086 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001087 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001088 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001089}
1090
Teresa Johnson28023db2018-07-19 14:51:32 +00001091ModulePassManager
1092PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1093 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001094 ModulePassManager MPM(DebugLogging);
1095
Teresa Johnson867bc392019-04-23 18:56:19 +00001096 if (Level == O0) {
1097 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1098 // metadata and intrinsics.
1099 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1100 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1101 return MPM;
1102 }
1103
Rong Xudb29a3a2019-03-04 20:21:27 +00001104 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001105 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001106 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001107 PGOOpt->ProfileRemappingFile,
1108 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001109 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1110 // RequireAnalysisPass for PSI before subsequent non-module passes.
1111 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001112 }
1113
Davide Italiano089a9122017-01-24 00:57:39 +00001114 // Remove unused virtual tables to improve the quality of code generated by
1115 // whole-program devirtualization and bitset lowering.
1116 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001117
Davide Italiano089a9122017-01-24 00:57:39 +00001118 // Force any function attributes we want the rest of the pipeline to observe.
1119 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001120
Davide Italiano089a9122017-01-24 00:57:39 +00001121 // Do basic inference of function attributes from known properties of system
1122 // libraries and other oracles.
1123 MPM.addPass(InferFunctionAttrsPass());
1124
1125 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001126 FunctionPassManager EarlyFPM(DebugLogging);
1127 EarlyFPM.addPass(CallSiteSplittingPass());
1128 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1129
Davide Italiano089a9122017-01-24 00:57:39 +00001130 // Indirect call promotion. This should promote all the targets that are
1131 // left by the earlier promotion pass that promotes intra-module targets.
1132 // This two-step promotion is to save the compile time. For LTO, it should
1133 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001134 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001135 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001136 // Propagate constants at call sites into the functions they call. This
1137 // opens opportunities for globalopt (and inlining) by substituting function
1138 // pointers passed as arguments to direct uses of functions.
1139 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001140
1141 // Attach metadata to indirect call sites indicating the set of functions
1142 // they may target at run-time. This should follow IPSCCP.
1143 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001144 }
1145
1146 // Now deduce any function attributes based in the current code.
1147 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1148 PostOrderFunctionAttrsPass()));
1149
1150 // Do RPO function attribute inference across the module to forward-propagate
1151 // attributes where applicable.
1152 // FIXME: Is this really an optimization rather than a canonicalization?
1153 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1154
Eric Christopher721eaef2019-02-26 20:33:22 +00001155 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001156 MPM.addPass(GlobalSplitPass());
1157
1158 // Run whole program optimization of virtual call when the list of callees
1159 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001160 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001161
1162 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001163 if (Level == 1) {
1164 // The LowerTypeTestsPass needs to run to lower type metadata and the
1165 // type.test intrinsics. The pass does nothing if CFI is disabled.
1166 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001167 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001168 }
Davide Italiano089a9122017-01-24 00:57:39 +00001169
1170 // Optimize globals to try and fold them into constants.
1171 MPM.addPass(GlobalOptPass());
1172
1173 // Promote any localized globals to SSA registers.
1174 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1175
1176 // Linking modules together can lead to duplicate global constant, only
1177 // keep one copy of each constant.
1178 MPM.addPass(ConstantMergePass());
1179
1180 // Remove unused arguments from functions.
1181 MPM.addPass(DeadArgumentEliminationPass());
1182
1183 // Reduce the code after globalopt and ipsccp. Both can open up significant
1184 // simplification opportunities, and both can propagate functions through
1185 // function pointers. When this happens, we often have to resolve varargs
1186 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001187 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001188 if (Level == O3)
1189 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001190 PeepholeFPM.addPass(InstCombinePass());
1191 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1192
1193 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001194
1195 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1196 // generally clean up exception handling overhead. It isn't clear this is
1197 // valuable as the inliner doesn't currently care whether it is inlining an
1198 // invoke or a call.
1199 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001200 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1201 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001202
1203 // Optimize globals again after we ran the inliner.
1204 MPM.addPass(GlobalOptPass());
1205
1206 // Garbage collect dead functions.
1207 // FIXME: Add ArgumentPromotion pass after once it's ported.
1208 MPM.addPass(GlobalDCEPass());
1209
1210 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001211 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001212 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001213 invokePeepholeEPCallbacks(FPM, Level);
1214
Davide Italiano089a9122017-01-24 00:57:39 +00001215 FPM.addPass(JumpThreadingPass());
1216
Rong Xudb29a3a2019-03-04 20:21:27 +00001217 // Do a post inline PGO instrumentation and use pass. This is a context
1218 // sensitive PGO pass.
1219 if (PGOOpt) {
1220 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1221 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1222 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1223 PGOOpt->ProfileRemappingFile);
1224 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1225 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1226 /* IsCS */ true, PGOOpt->ProfileFile,
1227 PGOOpt->ProfileRemappingFile);
1228 }
1229
Davide Italiano089a9122017-01-24 00:57:39 +00001230 // Break up allocas
1231 FPM.addPass(SROA());
1232
Robert Lougherf2158a82019-03-20 19:08:18 +00001233 // LTO provides additional opportunities for tailcall elimination due to
1234 // link-time inlining, and visibility of nocapture attribute.
1235 FPM.addPass(TailCallElimPass());
1236
Davide Italiano089a9122017-01-24 00:57:39 +00001237 // Run a few AA driver optimizations here and now to cleanup the code.
1238 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1239
1240 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1241 PostOrderFunctionAttrsPass()));
1242 // FIXME: here we run IP alias analysis in the legacy PM.
1243
1244 FunctionPassManager MainFPM;
1245
1246 // FIXME: once we fix LoopPass Manager, add LICM here.
1247 // FIXME: once we provide support for enabling MLSM, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001248 if (RunNewGVN)
1249 MainFPM.addPass(NewGVNPass());
1250 else
1251 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001252
1253 // Remove dead memcpy()'s.
1254 MainFPM.addPass(MemCpyOptPass());
1255
1256 // Nuke dead stores.
1257 MainFPM.addPass(DSEPass());
1258
1259 // FIXME: at this point, we run a bunch of loop passes:
Eric Christopher86e2f162019-05-03 00:15:23 +00001260 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
Davide Italiano089a9122017-01-24 00:57:39 +00001261 // loopVectorize. Enable them once the remaining issue with LPM
1262 // are sorted out.
1263
1264 MainFPM.addPass(InstCombinePass());
1265 MainFPM.addPass(SimplifyCFGPass());
1266 MainFPM.addPass(SCCPPass());
1267 MainFPM.addPass(InstCombinePass());
1268 MainFPM.addPass(BDCEPass());
1269
1270 // FIXME: We may want to run SLPVectorizer here.
1271 // After vectorization, assume intrinsics may tell us more
1272 // about pointer alignments.
1273#if 0
1274 MainFPM.add(AlignmentFromAssumptionsPass());
1275#endif
1276
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001277 // FIXME: Conditionally run LoadCombine here, after it's ported
1278 // (in case we still have this pass, given its questionable usefulness).
1279
Davide Italiano089a9122017-01-24 00:57:39 +00001280 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001281 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001282 MainFPM.addPass(JumpThreadingPass());
1283 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1284
1285 // Create a function that performs CFI checks for cross-DSO calls with
1286 // targets in the current module.
1287 MPM.addPass(CrossDSOCFIPass());
1288
1289 // Lower type metadata and the type.test intrinsic. This pass supports
1290 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1291 // to be run at link time if CFI is enabled. This pass does nothing if
1292 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001293 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001294
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001295 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1296 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1297 if (EnableHotColdSplit)
1298 MPM.addPass(HotColdSplittingPass());
1299
Davide Italiano089a9122017-01-24 00:57:39 +00001300 // Add late LTO optimization passes.
1301 // Delete basic blocks, which optimization passes may have killed.
1302 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1303
1304 // Drop bodies of available eternally objects to improve GlobalDCE.
1305 MPM.addPass(EliminateAvailableExternallyPass());
1306
1307 // Now that we have optimized the program, discard unreachable functions.
1308 MPM.addPass(GlobalDCEPass());
1309
Eric Christopher86e2f162019-05-03 00:15:23 +00001310 // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001311 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001312}
1313
Chandler Carruth060ad612016-12-23 20:38:19 +00001314AAManager PassBuilder::buildDefaultAAPipeline() {
1315 AAManager AA;
1316
1317 // The order in which these are registered determines their priority when
1318 // being queried.
1319
1320 // First we register the basic alias analysis that provides the majority of
1321 // per-function local AA logic. This is a stateless, on-demand local set of
1322 // AA techniques.
1323 AA.registerFunctionAnalysis<BasicAA>();
1324
1325 // Next we query fast, specialized alias analyses that wrap IR-embedded
1326 // information about aliasing.
1327 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1328 AA.registerFunctionAnalysis<TypeBasedAA>();
1329
1330 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001331 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1332 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001333 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001334 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001335
1336 return AA;
1337}
1338
Chandler Carruth241bf242016-08-03 07:44:48 +00001339static Optional<int> parseRepeatPassName(StringRef Name) {
1340 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1341 return None;
1342 int Count;
1343 if (Name.getAsInteger(0, Count) || Count <= 0)
1344 return None;
1345 return Count;
1346}
1347
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001348static Optional<int> parseDevirtPassName(StringRef Name) {
1349 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1350 return None;
1351 int Count;
1352 if (Name.getAsInteger(0, Count) || Count <= 0)
1353 return None;
1354 return Count;
1355}
1356
Fedor Sergeevb7871402019-01-10 10:01:53 +00001357static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1358 if (!Name.consume_front(PassName))
1359 return false;
1360 // normal pass name w/o parameters == default parameters
1361 if (Name.empty())
1362 return true;
1363 return Name.startswith("<") && Name.endswith(">");
1364}
1365
1366namespace {
1367
1368/// This performs customized parsing of pass name with parameters.
1369///
1370/// We do not need parametrization of passes in textual pipeline very often,
1371/// yet on a rare occasion ability to specify parameters right there can be
1372/// useful.
1373///
1374/// \p Name - parameterized specification of a pass from a textual pipeline
1375/// is a string in a form of :
1376/// PassName '<' parameter-list '>'
1377///
1378/// Parameter list is being parsed by the parser callable argument, \p Parser,
1379/// It takes a string-ref of parameters and returns either StringError or a
1380/// parameter list in a form of a custom parameters type, all wrapped into
1381/// Expected<> template class.
1382///
1383template <typename ParametersParseCallableT>
1384auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1385 StringRef PassName) -> decltype(Parser(StringRef{})) {
1386 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1387
1388 StringRef Params = Name;
1389 if (!Params.consume_front(PassName)) {
1390 assert(false &&
1391 "unable to strip pass name from parametrized pass specification");
1392 }
1393 if (Params.empty())
1394 return ParametersT{};
1395 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1396 assert(false && "invalid format for parametrized pass name");
1397 }
1398
1399 Expected<ParametersT> Result = Parser(Params);
1400 assert((Result || Result.template errorIsA<StringError>()) &&
1401 "Pass parameter parser can only return StringErrors.");
1402 return std::move(Result);
1403}
1404
1405/// Parser of parameters for LoopUnroll pass.
1406Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1407 LoopUnrollOptions UnrollOpts;
1408 while (!Params.empty()) {
1409 StringRef ParamName;
1410 std::tie(ParamName, Params) = Params.split(';');
1411 int OptLevel = StringSwitch<int>(ParamName)
1412 .Case("O0", 0)
1413 .Case("O1", 1)
1414 .Case("O2", 2)
1415 .Case("O3", 3)
1416 .Default(-1);
1417 if (OptLevel >= 0) {
1418 UnrollOpts.setOptLevel(OptLevel);
1419 continue;
1420 }
1421
1422 bool Enable = !ParamName.consume_front("no-");
1423 if (ParamName == "partial") {
1424 UnrollOpts.setPartial(Enable);
1425 } else if (ParamName == "peeling") {
1426 UnrollOpts.setPeeling(Enable);
1427 } else if (ParamName == "runtime") {
1428 UnrollOpts.setRuntime(Enable);
1429 } else if (ParamName == "upperbound") {
1430 UnrollOpts.setUpperBound(Enable);
1431 } else {
1432 return make_error<StringError>(
1433 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1434 inconvertibleErrorCode());
1435 }
1436 }
1437 return UnrollOpts;
1438}
1439
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001440Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1441 MemorySanitizerOptions Result;
1442 while (!Params.empty()) {
1443 StringRef ParamName;
1444 std::tie(ParamName, Params) = Params.split(';');
1445
1446 if (ParamName == "recover") {
1447 Result.Recover = true;
1448 } else if (ParamName == "kernel") {
1449 Result.Kernel = true;
1450 } else if (ParamName.consume_front("track-origins=")) {
1451 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1452 return make_error<StringError>(
1453 formatv("invalid argument to MemorySanitizer pass track-origins "
1454 "parameter: '{0}' ",
1455 ParamName)
1456 .str(),
1457 inconvertibleErrorCode());
1458 } else {
1459 return make_error<StringError>(
1460 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1461 .str(),
1462 inconvertibleErrorCode());
1463 }
1464 }
1465 return Result;
1466}
1467
Serguei Katkovf5432832019-04-15 08:57:53 +00001468/// Parser of parameters for SimplifyCFG pass.
1469Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1470 SimplifyCFGOptions Result;
1471 while (!Params.empty()) {
1472 StringRef ParamName;
1473 std::tie(ParamName, Params) = Params.split(';');
1474
1475 bool Enable = !ParamName.consume_front("no-");
1476 if (ParamName == "forward-switch-cond") {
1477 Result.forwardSwitchCondToPhi(Enable);
1478 } else if (ParamName == "switch-to-lookup") {
1479 Result.convertSwitchToLookupTable(Enable);
1480 } else if (ParamName == "keep-loops") {
1481 Result.needCanonicalLoops(Enable);
1482 } else if (ParamName == "sink-common-insts") {
1483 Result.sinkCommonInsts(Enable);
1484 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1485 APInt BonusInstThreshold;
1486 if (ParamName.getAsInteger(0, BonusInstThreshold))
1487 return make_error<StringError>(
1488 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1489 "parameter: '{0}' ",
1490 ParamName).str(),
1491 inconvertibleErrorCode());
1492 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1493 } else {
1494 return make_error<StringError>(
1495 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1496 inconvertibleErrorCode());
1497 }
1498 }
1499 return Result;
1500}
1501
Serguei Katkovca6c03a2019-04-18 08:46:11 +00001502/// Parser of parameters for LoopVectorize pass.
1503Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1504 LoopVectorizeOptions Opts;
1505 while (!Params.empty()) {
1506 StringRef ParamName;
1507 std::tie(ParamName, Params) = Params.split(';');
1508
1509 bool Enable = !ParamName.consume_front("no-");
1510 if (ParamName == "interleave-forced-only") {
1511 Opts.setInterleaveOnlyWhenForced(Enable);
1512 } else if (ParamName == "vectorize-forced-only") {
1513 Opts.setVectorizeOnlyWhenForced(Enable);
1514 } else {
1515 return make_error<StringError>(
1516 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1517 inconvertibleErrorCode());
1518 }
1519 }
1520 return Opts;
1521}
1522
Serguei Katkov40a3b962019-04-22 10:35:07 +00001523Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
1524 bool Result = false;
1525 while (!Params.empty()) {
1526 StringRef ParamName;
1527 std::tie(ParamName, Params) = Params.split(';');
1528
1529 bool Enable = !ParamName.consume_front("no-");
1530 if (ParamName == "nontrivial") {
1531 Result = Enable;
1532 } else {
1533 return make_error<StringError>(
1534 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
1535 .str(),
1536 inconvertibleErrorCode());
1537 }
1538 }
1539 return Result;
1540}
Fedor Sergeevb7871402019-01-10 10:01:53 +00001541} // namespace
1542
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001543/// Tests whether a pass name starts with a valid prefix for a default pipeline
1544/// alias.
1545static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1546 return Name.startswith("default") || Name.startswith("thinlto") ||
1547 Name.startswith("lto");
1548}
1549
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001550/// Tests whether registered callbacks will accept a given pass name.
1551///
1552/// When parsing a pipeline text, the type of the outermost pipeline may be
1553/// omitted, in which case the type is automatically determined from the first
1554/// pass name in the text. This may be a name that is handled through one of the
1555/// callbacks. We check this through the oridinary parsing callbacks by setting
1556/// up a dummy PassManager in order to not force the client to also handle this
1557/// type of query.
1558template <typename PassManagerT, typename CallbacksT>
1559static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1560 if (!Callbacks.empty()) {
1561 PassManagerT DummyPM;
1562 for (auto &CB : Callbacks)
1563 if (CB(Name, DummyPM, {}))
1564 return true;
1565 }
1566 return false;
1567}
1568
1569template <typename CallbacksT>
1570static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001571 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001572 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001573 return DefaultAliasRegex.match(Name);
1574
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001575 // Explicitly handle pass manager names.
1576 if (Name == "module")
1577 return true;
1578 if (Name == "cgscc")
1579 return true;
1580 if (Name == "function")
1581 return true;
1582
Chandler Carruth241bf242016-08-03 07:44:48 +00001583 // Explicitly handle custom-parsed pass names.
1584 if (parseRepeatPassName(Name))
1585 return true;
1586
Chandler Carruth74a8a222016-06-17 07:15:29 +00001587#define MODULE_PASS(NAME, CREATE_PASS) \
1588 if (Name == NAME) \
1589 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001590#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001591 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001592 return true;
1593#include "PassRegistry.def"
1594
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001595 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001596}
1597
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001598template <typename CallbacksT>
1599static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001600 // Explicitly handle pass manager names.
1601 if (Name == "cgscc")
1602 return true;
1603 if (Name == "function")
1604 return true;
1605
Chandler Carruth241bf242016-08-03 07:44:48 +00001606 // Explicitly handle custom-parsed pass names.
1607 if (parseRepeatPassName(Name))
1608 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001609 if (parseDevirtPassName(Name))
1610 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001611
Chandler Carruth74a8a222016-06-17 07:15:29 +00001612#define CGSCC_PASS(NAME, CREATE_PASS) \
1613 if (Name == NAME) \
1614 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001615#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001616 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001617 return true;
1618#include "PassRegistry.def"
1619
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001620 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001621}
1622
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001623template <typename CallbacksT>
1624static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001625 // Explicitly handle pass manager names.
1626 if (Name == "function")
1627 return true;
1628 if (Name == "loop")
1629 return true;
1630
Chandler Carruth241bf242016-08-03 07:44:48 +00001631 // Explicitly handle custom-parsed pass names.
1632 if (parseRepeatPassName(Name))
1633 return true;
1634
Chandler Carruth74a8a222016-06-17 07:15:29 +00001635#define FUNCTION_PASS(NAME, CREATE_PASS) \
1636 if (Name == NAME) \
1637 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001638#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1639 if (checkParametrizedPassName(Name, NAME)) \
1640 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001641#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001642 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001643 return true;
1644#include "PassRegistry.def"
1645
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001646 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001647}
1648
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001649template <typename CallbacksT>
1650static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001651 // Explicitly handle pass manager names.
1652 if (Name == "loop")
1653 return true;
1654
Chandler Carruth241bf242016-08-03 07:44:48 +00001655 // Explicitly handle custom-parsed pass names.
1656 if (parseRepeatPassName(Name))
1657 return true;
1658
Chandler Carruth74a8a222016-06-17 07:15:29 +00001659#define LOOP_PASS(NAME, CREATE_PASS) \
1660 if (Name == NAME) \
1661 return true;
Serguei Katkov40a3b962019-04-22 10:35:07 +00001662#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1663 if (checkParametrizedPassName(Name, NAME)) \
1664 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001665#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1666 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1667 return true;
1668#include "PassRegistry.def"
1669
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001670 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001671}
1672
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001673Optional<std::vector<PassBuilder::PipelineElement>>
1674PassBuilder::parsePipelineText(StringRef Text) {
1675 std::vector<PipelineElement> ResultPipeline;
1676
1677 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1678 &ResultPipeline};
1679 for (;;) {
1680 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1681 size_t Pos = Text.find_first_of(",()");
1682 Pipeline.push_back({Text.substr(0, Pos), {}});
1683
1684 // If we have a single terminating name, we're done.
1685 if (Pos == Text.npos)
1686 break;
1687
1688 char Sep = Text[Pos];
1689 Text = Text.substr(Pos + 1);
1690 if (Sep == ',')
1691 // Just a name ending in a comma, continue.
1692 continue;
1693
1694 if (Sep == '(') {
1695 // Push the inner pipeline onto the stack to continue processing.
1696 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1697 continue;
1698 }
1699
1700 assert(Sep == ')' && "Bogus separator!");
1701 // When handling the close parenthesis, we greedily consume them to avoid
1702 // empty strings in the pipeline.
1703 do {
1704 // If we try to pop the outer pipeline we have unbalanced parentheses.
1705 if (PipelineStack.size() == 1)
1706 return None;
1707
1708 PipelineStack.pop_back();
1709 } while (Text.consume_front(")"));
1710
1711 // Check if we've finished parsing.
1712 if (Text.empty())
1713 break;
1714
1715 // Otherwise, the end of an inner pipeline always has to be followed by
1716 // a comma, and then we can continue.
1717 if (!Text.consume_front(","))
1718 return None;
1719 }
1720
1721 if (PipelineStack.size() > 1)
1722 // Unbalanced paretheses.
1723 return None;
1724
1725 assert(PipelineStack.back() == &ResultPipeline &&
1726 "Wrong pipeline at the bottom of the stack!");
1727 return {std::move(ResultPipeline)};
1728}
1729
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001730Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1731 const PipelineElement &E,
1732 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001733 auto &Name = E.Name;
1734 auto &InnerPipeline = E.InnerPipeline;
1735
1736 // First handle complex passes like the pass managers which carry pipelines.
1737 if (!InnerPipeline.empty()) {
1738 if (Name == "module") {
1739 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001740 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1741 VerifyEachPass, DebugLogging))
1742 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001743 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001744 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001745 }
1746 if (Name == "cgscc") {
1747 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001748 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1749 DebugLogging))
1750 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001751 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001752 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001753 }
1754 if (Name == "function") {
1755 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001756 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1757 VerifyEachPass, DebugLogging))
1758 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001759 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001760 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001761 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001762 if (auto Count = parseRepeatPassName(Name)) {
1763 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001764 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1765 VerifyEachPass, DebugLogging))
1766 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001767 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001768 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001769 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001770
1771 for (auto &C : ModulePipelineParsingCallbacks)
1772 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001773 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001774
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001775 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001776 return make_error<StringError>(
1777 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1778 inconvertibleErrorCode());
1779 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001780 }
1781
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001782 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001783 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001784 SmallVector<StringRef, 3> Matches;
1785 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001786 return make_error<StringError>(
1787 formatv("unknown default pipeline alias '{0}'", Name).str(),
1788 inconvertibleErrorCode());
1789
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001790 assert(Matches.size() == 3 && "Must capture two matched strings!");
1791
Jordan Rosef85a95f2016-07-25 18:34:51 +00001792 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001793 .Case("O0", O0)
1794 .Case("O1", O1)
1795 .Case("O2", O2)
1796 .Case("O3", O3)
1797 .Case("Os", Os)
1798 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001799 if (L == O0)
1800 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001801 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001802
1803 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001804 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001805 } else if (Matches[1] == "thinlto-pre-link") {
1806 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1807 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001808 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001809 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001810 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001811 } else {
1812 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001813 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001814 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001815 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001816 }
1817
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001818 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001819#define MODULE_PASS(NAME, CREATE_PASS) \
1820 if (Name == NAME) { \
1821 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001822 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001823 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001824#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1825 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001826 MPM.addPass( \
1827 RequireAnalysisPass< \
1828 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001829 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001830 } \
1831 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001832 MPM.addPass(InvalidateAnalysisPass< \
1833 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001834 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001835 }
1836#include "PassRegistry.def"
1837
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001838 for (auto &C : ModulePipelineParsingCallbacks)
1839 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001840 return Error::success();
1841 return make_error<StringError>(
1842 formatv("unknown module pass '{0}'", Name).str(),
1843 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001844}
1845
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001846Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1847 const PipelineElement &E, bool VerifyEachPass,
1848 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001849 auto &Name = E.Name;
1850 auto &InnerPipeline = E.InnerPipeline;
1851
1852 // First handle complex passes like the pass managers which carry pipelines.
1853 if (!InnerPipeline.empty()) {
1854 if (Name == "cgscc") {
1855 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001856 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1857 VerifyEachPass, DebugLogging))
1858 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001859 // Add the nested pass manager with the appropriate adaptor.
1860 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001861 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001862 }
1863 if (Name == "function") {
1864 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001865 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1866 VerifyEachPass, DebugLogging))
1867 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001868 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001869 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001870 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001871 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001872 if (auto Count = parseRepeatPassName(Name)) {
1873 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001874 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1875 VerifyEachPass, DebugLogging))
1876 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001877 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001878 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001879 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001880 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1881 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001882 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1883 VerifyEachPass, DebugLogging))
1884 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001885 CGPM.addPass(
1886 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001887 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001888 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001889
1890 for (auto &C : CGSCCPipelineParsingCallbacks)
1891 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001892 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001893
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001894 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001895 return make_error<StringError>(
1896 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1897 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001898 }
1899
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001900// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001901#define CGSCC_PASS(NAME, CREATE_PASS) \
1902 if (Name == NAME) { \
1903 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001904 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001905 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001906#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1907 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001908 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001909 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001910 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1911 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001912 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001913 } \
1914 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001915 CGPM.addPass(InvalidateAnalysisPass< \
1916 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001917 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001918 }
1919#include "PassRegistry.def"
1920
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001921 for (auto &C : CGSCCPipelineParsingCallbacks)
1922 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001923 return Error::success();
1924 return make_error<StringError>(
1925 formatv("unknown cgscc pass '{0}'", Name).str(),
1926 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001927}
1928
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001929Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1930 const PipelineElement &E,
1931 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001932 auto &Name = E.Name;
1933 auto &InnerPipeline = E.InnerPipeline;
1934
1935 // First handle complex passes like the pass managers which carry pipelines.
1936 if (!InnerPipeline.empty()) {
1937 if (Name == "function") {
1938 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001939 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1940 VerifyEachPass, DebugLogging))
1941 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001942 // Add the nested pass manager with the appropriate adaptor.
1943 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001944 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001945 }
1946 if (Name == "loop") {
1947 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001948 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1949 DebugLogging))
1950 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001951 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001952 FPM.addPass(
1953 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001954 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001955 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001956 if (auto Count = parseRepeatPassName(Name)) {
1957 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001958 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1959 VerifyEachPass, DebugLogging))
1960 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001961 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001962 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001963 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001964
1965 for (auto &C : FunctionPipelineParsingCallbacks)
1966 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001967 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001968
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001969 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001970 return make_error<StringError>(
1971 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1972 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001973 }
1974
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001975// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001976#define FUNCTION_PASS(NAME, CREATE_PASS) \
1977 if (Name == NAME) { \
1978 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001979 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001980 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001981#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1982 if (checkParametrizedPassName(Name, NAME)) { \
1983 auto Params = parsePassParameters(PARSER, Name, NAME); \
1984 if (!Params) \
1985 return Params.takeError(); \
1986 FPM.addPass(CREATE_PASS(Params.get())); \
1987 return Error::success(); \
1988 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001989#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1990 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001991 FPM.addPass( \
1992 RequireAnalysisPass< \
1993 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001994 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001995 } \
1996 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001997 FPM.addPass(InvalidateAnalysisPass< \
1998 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001999 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00002000 }
2001#include "PassRegistry.def"
2002
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002003 for (auto &C : FunctionPipelineParsingCallbacks)
2004 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002005 return Error::success();
2006 return make_error<StringError>(
2007 formatv("unknown function pass '{0}'", Name).str(),
2008 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00002009}
2010
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002011Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
2012 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00002013 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002014 auto &InnerPipeline = E.InnerPipeline;
2015
2016 // First handle complex passes like the pass managers which carry pipelines.
2017 if (!InnerPipeline.empty()) {
2018 if (Name == "loop") {
2019 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002020 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2021 VerifyEachPass, DebugLogging))
2022 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002023 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002024 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002025 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002026 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002027 if (auto Count = parseRepeatPassName(Name)) {
2028 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002029 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2030 VerifyEachPass, DebugLogging))
2031 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002032 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002033 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002034 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002035
2036 for (auto &C : LoopPipelineParsingCallbacks)
2037 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002038 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002039
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002040 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002041 return make_error<StringError>(
2042 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2043 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002044 }
2045
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002046// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00002047#define LOOP_PASS(NAME, CREATE_PASS) \
2048 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002049 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002050 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002051 }
Serguei Katkov40a3b962019-04-22 10:35:07 +00002052#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2053 if (checkParametrizedPassName(Name, NAME)) { \
2054 auto Params = parsePassParameters(PARSER, Name, NAME); \
2055 if (!Params) \
2056 return Params.takeError(); \
2057 LPM.addPass(CREATE_PASS(Params.get())); \
2058 return Error::success(); \
2059 }
Justin Bognereecc3c82016-02-25 07:23:08 +00002060#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2061 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002062 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002063 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2064 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2065 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002066 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002067 } \
2068 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002069 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00002070 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002071 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002072 }
2073#include "PassRegistry.def"
2074
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002075 for (auto &C : LoopPipelineParsingCallbacks)
2076 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002077 return Error::success();
2078 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2079 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002080}
2081
Chandler Carruthedf59962016-02-18 09:45:17 +00002082bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002083#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2084 if (Name == NAME) { \
2085 AA.registerModuleAnalysis< \
2086 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2087 return true; \
2088 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002089#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2090 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002091 AA.registerFunctionAnalysis< \
2092 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002093 return true; \
2094 }
2095#include "PassRegistry.def"
2096
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002097 for (auto &C : AAParsingCallbacks)
2098 if (C(Name, AA))
2099 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002100 return false;
2101}
2102
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002103Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002104 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002105 bool VerifyEachPass,
2106 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002107 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002108 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2109 return Err;
2110 // FIXME: No verifier support for Loop passes!
2111 }
2112 return Error::success();
2113}
2114
2115Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2116 ArrayRef<PipelineElement> Pipeline,
2117 bool VerifyEachPass,
2118 bool DebugLogging) {
2119 for (const auto &Element : Pipeline) {
2120 if (auto Err =
2121 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2122 return Err;
2123 if (VerifyEachPass)
2124 FPM.addPass(VerifierPass());
2125 }
2126 return Error::success();
2127}
2128
2129Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2130 ArrayRef<PipelineElement> Pipeline,
2131 bool VerifyEachPass,
2132 bool DebugLogging) {
2133 for (const auto &Element : Pipeline) {
2134 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2135 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002136 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002137 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002138 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002139}
2140
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002141void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2142 FunctionAnalysisManager &FAM,
2143 CGSCCAnalysisManager &CGAM,
2144 ModuleAnalysisManager &MAM) {
2145 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2146 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002147 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2148 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2149 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2150 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2151 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2152}
2153
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002154Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2155 ArrayRef<PipelineElement> Pipeline,
2156 bool VerifyEachPass,
2157 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002158 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002159 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2160 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002161 if (VerifyEachPass)
2162 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002163 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002164 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002165}
2166
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002167// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002168// FIXME: Should this routine accept a TargetMachine or require the caller to
2169// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002170Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2171 StringRef PipelineText,
2172 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002173 auto Pipeline = parsePipelineText(PipelineText);
2174 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002175 return make_error<StringError>(
2176 formatv("invalid pipeline '{0}'", PipelineText).str(),
2177 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002178
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002179 // If the first name isn't at the module layer, wrap the pipeline up
2180 // automatically.
2181 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002182
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002183 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2184 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002185 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002186 } else if (isFunctionPassName(FirstName,
2187 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002188 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002189 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002190 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002191 } else {
2192 for (auto &C : TopLevelPipelineParsingCallbacks)
2193 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002194 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002195
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002196 // Unknown pass or pipeline name!
2197 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2198 return make_error<StringError>(
2199 formatv("unknown {0} name '{1}'",
2200 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2201 .str(),
2202 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002203 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002204 }
2205
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002206 if (auto Err =
2207 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2208 return Err;
2209 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002210}
Chandler Carruthedf59962016-02-18 09:45:17 +00002211
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002212// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002213Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2214 StringRef PipelineText,
2215 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002216 auto Pipeline = parsePipelineText(PipelineText);
2217 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002218 return make_error<StringError>(
2219 formatv("invalid pipeline '{0}'", PipelineText).str(),
2220 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002221
2222 StringRef FirstName = Pipeline->front().Name;
2223 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002224 return make_error<StringError>(
2225 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2226 PipelineText)
2227 .str(),
2228 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002229
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002230 if (auto Err =
2231 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2232 return Err;
2233 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002234}
2235
2236// Primary pass pipeline description parsing routine for a \c
2237// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002238Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2239 StringRef PipelineText,
2240 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002241 auto Pipeline = parsePipelineText(PipelineText);
2242 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002243 return make_error<StringError>(
2244 formatv("invalid pipeline '{0}'", PipelineText).str(),
2245 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002246
2247 StringRef FirstName = Pipeline->front().Name;
2248 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002249 return make_error<StringError>(
2250 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2251 PipelineText)
2252 .str(),
2253 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002254
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002255 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2256 DebugLogging))
2257 return Err;
2258 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002259}
2260
2261// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002262Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2263 StringRef PipelineText,
2264 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002265 auto Pipeline = parsePipelineText(PipelineText);
2266 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002267 return make_error<StringError>(
2268 formatv("invalid pipeline '{0}'", PipelineText).str(),
2269 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002270
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002271 if (auto Err =
2272 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2273 return Err;
2274
2275 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002276}
2277
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002278Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002279 // If the pipeline just consists of the word 'default' just replace the AA
2280 // manager with our default one.
2281 if (PipelineText == "default") {
2282 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002283 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002284 }
2285
Chandler Carruthedf59962016-02-18 09:45:17 +00002286 while (!PipelineText.empty()) {
2287 StringRef Name;
2288 std::tie(Name, PipelineText) = PipelineText.split(',');
2289 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002290 return make_error<StringError>(
2291 formatv("unknown alias analysis name '{0}'", Name).str(),
2292 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002293 }
2294
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002295 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002296}