blob: d1762864afc6b3638f8e3f8c458a4fe3f57da474 [file] [log] [blame]
Chandler Carruth1ff77242015-03-07 09:02:36 +00001//===- Parsing, selection, and construction of pass pipelines -------------===//
Chandler Carruth66445382014-01-11 08:16:35 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chandler Carruth66445382014-01-11 08:16:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
9///
Chandler Carruth1ff77242015-03-07 09:02:36 +000010/// This file provides the implementation of the PassBuilder based on our
11/// static pass registry as well as related functionality. It also provides
12/// helpers to aid in analyzing, debugging, and testing passes and pass
13/// pipelines.
Chandler Carruth66445382014-01-11 08:16:35 +000014///
15//===----------------------------------------------------------------------===//
16
Chandler Carruth1ff77242015-03-07 09:02:36 +000017#include "llvm/Passes/PassBuilder.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000018#include "llvm/ADT/StringSwitch.h"
Chandler Carruth6f5770b102016-02-13 23:32:00 +000019#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth4f846a52016-02-20 03:46:03 +000020#include "llvm/Analysis/AliasAnalysisEvaluator.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000021#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthbece8d52016-02-13 23:46:24 +000022#include "llvm/Analysis/BasicAliasAnalysis.h"
Xinliang David Li28a93272016-05-05 21:13:27 +000023#include "llvm/Analysis/BlockFrequencyInfo.h"
Xinliang David Li6e5dd412016-05-05 02:59:57 +000024#include "llvm/Analysis/BranchProbabilityInfo.h"
Mehdi Amini27d23792016-09-16 16:56:30 +000025#include "llvm/Analysis/CFGPrinter.h"
George Burgess IVbfa401e2016-07-06 00:26:41 +000026#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
27#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
Chandler Carruth572e3402014-04-21 11:12:00 +000028#include "llvm/Analysis/CGSCCPassManager.h"
Chandler Carruth4c660f72016-03-10 11:24:11 +000029#include "llvm/Analysis/CallGraph.h"
Michael Kupersteinde16b442016-04-18 23:55:01 +000030#include "llvm/Analysis/DemandedBits.h"
Chandler Carruth49c22192016-05-12 22:19:39 +000031#include "llvm/Analysis/DependenceAnalysis.h"
Hongbin Zheng751337f2016-02-25 17:54:15 +000032#include "llvm/Analysis/DominanceFrontier.h"
Chandler Carruth45a9c202016-03-11 09:15:11 +000033#include "llvm/Analysis/GlobalsModRef.h"
Dehao Chen1a444522016-07-16 22:51:33 +000034#include "llvm/Analysis/IVUsers.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000035#include "llvm/Analysis/LazyCallGraph.h"
Sean Silva687019f2016-06-13 22:01:25 +000036#include "llvm/Analysis/LazyValueInfo.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000037#include "llvm/Analysis/LoopAccessAnalysis.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000038#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth61440d22016-03-10 00:55:30 +000039#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000040#include "llvm/Analysis/MemorySSA.h"
Teresa Johnsonf93b2462016-08-12 13:53:02 +000041#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000042#include "llvm/Analysis/OptimizationRemarkEmitter.h"
John Brawnbdbbd832018-06-28 14:13:06 +000043#include "llvm/Analysis/PhiValues.h"
Hongbin Zheng3f978402016-02-25 17:54:07 +000044#include "llvm/Analysis/PostDominators.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +000045#include "llvm/Analysis/ProfileSummaryInfo.h"
Hongbin Zhengbc539772016-02-25 17:54:25 +000046#include "llvm/Analysis/RegionInfo.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000047#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth2b3d0442016-02-20 04:01:45 +000048#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruthd6091a02016-02-20 04:03:06 +000049#include "llvm/Analysis/ScopedNoAliasAA.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000050#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth8ca43222015-01-15 11:39:46 +000051#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000052#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthc1dc3842016-02-20 04:04:52 +000053#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
Michael Kuperstein82d5da52016-06-24 20:13:42 +000054#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
Wei Mi90d195a2016-07-08 03:32:49 +000055#include "llvm/CodeGen/UnreachableBlockElim.h"
Chandler Carruth64764b42015-01-14 10:19:28 +000056#include "llvm/IR/Dominators.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000057#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth66445382014-01-11 08:16:35 +000058#include "llvm/IR/PassManager.h"
Fedor Sergeeva2ed4482019-03-31 10:15:39 +000059#include "llvm/IR/SafepointIRVerifier.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000060#include "llvm/IR/Verifier.h"
Chandler Carruth52eef882014-01-12 12:15:39 +000061#include "llvm/Support/Debug.h"
Fedor Sergeevbd6b2132018-10-17 10:36:23 +000062#include "llvm/Support/FormatVariadic.h"
Chandler Carruth8b5a74192016-02-28 22:16:03 +000063#include "llvm/Support/Regex.h"
Chandler Carruthe0385522015-02-01 10:11:22 +000064#include "llvm/Target/TargetMachine.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000065#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
Chandler Carruth67fc52f2016-08-17 02:56:20 +000066#include "llvm/Transforms/IPO/AlwaysInliner.h"
Chandler Carruthaddcda42017-02-09 23:46:27 +000067#include "llvm/Transforms/IPO/ArgumentPromotion.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000068#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000069#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000070#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000071#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000072#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000073#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000074#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000075#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000076#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000077#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000078#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000079#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000080#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000081#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000082#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000083#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000084#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000085#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000086#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000087#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000088#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000089#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000090#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000091#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000092#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000093#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000094#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000095#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000096#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Manman Ren18295122019-02-28 20:13:38 +000097#include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000098#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000099#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +0000100#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +0000101#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000102#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000103#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000104#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000105#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000106#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000107#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000108#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000109#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000110#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000111#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000112#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000113#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000114#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000115#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000116#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000117#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000118#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000119#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000120#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000121#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000122#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000123#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000124#include "llvm/Transforms/Scalar/LoopDistribute.h"
Kit Barton3cdf8792019-04-17 18:53:27 +0000125#include "llvm/Transforms/Scalar/LoopFuse.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000126#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000127#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000128#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000129#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000130#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000131#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000132#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000133#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000134#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000135#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000136#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000137#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000138#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000139#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000140#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000141#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000142#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Davide Italianob49aa5c2016-06-17 19:10:09 +0000143#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000144#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000145#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000146#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000147#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000148#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000149#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000150#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000151#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000152#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000153#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000154#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000155#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000156#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000157#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000158#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000159#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000160#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000161#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000162#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000163#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000164#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000165#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000166#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000167#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000168#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000169#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000170#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000171#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000172#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000173
Chandler Carruth66445382014-01-11 08:16:35 +0000174using namespace llvm;
175
Chandler Carruth719ffe12017-02-12 05:38:04 +0000176static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
177 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000178static cl::opt<bool>
179 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
180 cl::Hidden, cl::ZeroOrMore,
181 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000182
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000183static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000184 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000185 cl::Hidden, cl::ZeroOrMore,
186 cl::desc("Run NewGVN instead of GVN"));
187
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000188static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000189 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
190 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000191
Davide Italianobe1b6a92017-06-03 23:18:29 +0000192static cl::opt<bool> EnableGVNSink(
193 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
194 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
195
David Green963401d2018-07-01 12:47:30 +0000196static cl::opt<bool> EnableUnrollAndJam(
197 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
198 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
199
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000200static cl::opt<bool> EnableSyntheticCounts(
201 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
202 cl::desc("Run synthetic function entry count generation "
203 "pass"));
204
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000205static Regex DefaultAliasRegex(
206 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000207
Eric Christophereff3b6f2019-04-18 06:17:40 +0000208// This option is used in simplifying testing SampleFDO optimizations for
209// profile loading.
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000210static cl::opt<bool>
211 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
212 cl::desc("Enable control height reduction optimization (CHR)"));
213
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000214PipelineTuningOptions::PipelineTuningOptions() {
215 LoopInterleaving = EnableLoopInterleaving;
216 LoopVectorization = EnableLoopVectorization;
Alina Sbirlea43709f72019-04-19 17:46:50 +0000217 LicmMssaOptCap = SetLicmMssaOptCap;
218 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000219}
220
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000221extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000222extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000223
Wei Mi3bcccdf2019-01-17 20:48:34 +0000224extern cl::opt<bool> FlattenedProfileUsed;
225
Chandler Carruthe3f50642016-12-22 06:59:15 +0000226static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
227 switch (Level) {
228 case PassBuilder::O0:
229 case PassBuilder::O1:
230 case PassBuilder::O2:
231 case PassBuilder::O3:
232 return false;
233
234 case PassBuilder::Os:
235 case PassBuilder::Oz:
236 return true;
237 }
238 llvm_unreachable("Invalid optimization level!");
239}
240
Chandler Carruth66445382014-01-11 08:16:35 +0000241namespace {
242
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000243/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000244struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000245 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000246 return PreservedAnalyses::all();
247 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000248 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000249};
250
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000251/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000252class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
253 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000254 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000255
256public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000257 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000258 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000259 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000260};
261
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000262/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000263struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000264 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
265 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000266 return PreservedAnalyses::all();
267 }
268 static StringRef name() { return "NoOpCGSCCPass"; }
269};
270
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000271/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000272class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
273 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000274 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000275
276public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000277 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000278 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000279 return Result();
280 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000281 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000282};
283
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000284/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000285struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000286 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000287 return PreservedAnalyses::all();
288 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000289 static StringRef name() { return "NoOpFunctionPass"; }
290};
291
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000292/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000293class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
294 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000295 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000296
297public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000298 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000299 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000300 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000301};
302
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000303/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000304struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000305 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
306 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000307 return PreservedAnalyses::all();
308 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000309 static StringRef name() { return "NoOpLoopPass"; }
310};
311
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000312/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000313class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
314 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000315 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000316
317public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000318 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000319 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
320 return Result();
321 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000322 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000323};
324
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000325AnalysisKey NoOpModuleAnalysis::Key;
326AnalysisKey NoOpCGSCCAnalysis::Key;
327AnalysisKey NoOpFunctionAnalysis::Key;
328AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000329
Chandler Carruth66445382014-01-11 08:16:35 +0000330} // End anonymous namespace.
331
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000332void PassBuilder::invokePeepholeEPCallbacks(
333 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
334 for (auto &C : PeepholeEPCallbacks)
335 C(FPM, Level);
336}
337
Chandler Carruth1ff77242015-03-07 09:02:36 +0000338void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000339#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000340 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000341#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000342
343 for (auto &C : ModuleAnalysisRegistrationCallbacks)
344 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000345}
346
Chandler Carruth1ff77242015-03-07 09:02:36 +0000347void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000348#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000349 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000350#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000351
352 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
353 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000354}
355
Chandler Carruth1ff77242015-03-07 09:02:36 +0000356void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000357#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000358 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000359#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000360
361 for (auto &C : FunctionAnalysisRegistrationCallbacks)
362 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000363}
364
Justin Bognereecc3c82016-02-25 07:23:08 +0000365void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000366#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000367 LAM.registerPass([&] { return CREATE_PASS; });
368#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000369
370 for (auto &C : LoopAnalysisRegistrationCallbacks)
371 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000372}
373
Chandler Carruthe3f50642016-12-22 06:59:15 +0000374FunctionPassManager
375PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000376 ThinLTOPhase Phase,
377 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000378 assert(Level != O0 && "Must request optimizations!");
379 FunctionPassManager FPM(DebugLogging);
380
381 // Form SSA out of local memory accesses after breaking apart aggregates into
382 // scalars.
383 FPM.addPass(SROA());
384
385 // Catch trivial redundancies
Eric Christopherdfebd842019-04-19 22:18:53 +0000386 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000387
Davide Italianoc3688312017-06-01 23:08:14 +0000388 // Hoisting of scalars and load expressions.
389 if (EnableGVNHoist)
390 FPM.addPass(GVNHoistPass());
391
Davide Italianobe1b6a92017-06-03 23:18:29 +0000392 // Global value numbering based sinking.
393 if (EnableGVNSink) {
394 FPM.addPass(GVNSinkPass());
395 FPM.addPass(SimplifyCFGPass());
396 }
397
Chandler Carruthe3f50642016-12-22 06:59:15 +0000398 // Speculative execution if the target has divergent branches; otherwise nop.
399 FPM.addPass(SpeculativeExecutionPass());
400
401 // Optimize based on known information about branches, and cleanup afterward.
402 FPM.addPass(JumpThreadingPass());
403 FPM.addPass(CorrelatedValuePropagationPass());
404 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000405 if (Level == O3)
406 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000407 FPM.addPass(InstCombinePass());
408
409 if (!isOptimizingForSize(Level))
410 FPM.addPass(LibCallsShrinkWrapPass());
411
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000412 invokePeepholeEPCallbacks(FPM, Level);
413
Rong Xue1f42452017-10-23 22:21:29 +0000414 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
415 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000416 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000417 !isOptimizingForSize(Level))
418 FPM.addPass(PGOMemOPSizeOpt());
419
Chandler Carruthe3f50642016-12-22 06:59:15 +0000420 FPM.addPass(TailCallElimPass());
421 FPM.addPass(SimplifyCFGPass());
422
423 // Form canonically associated expression trees, and simplify the trees using
424 // basic mathematical properties. For example, this will form (nearly)
425 // minimal multiplication trees.
426 FPM.addPass(ReassociatePass());
427
428 // Add the primary loop simplification pipeline.
429 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000430 // some function passes in between them. These can and should be removed
431 // and/or replaced by scheduling the loop pass equivalents in the correct
432 // positions. But those equivalent passes aren't powerful enough yet.
433 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
434 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
435 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
436 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000437 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
438
Chandler Carruth71fd2702018-05-30 02:46:45 +0000439 // Simplify the loop body. We do this initially to clean up after other loop
440 // passes run, either when iterating on a loop or on inner loops with
441 // implications on the outer loop.
442 LPM1.addPass(LoopInstSimplifyPass());
443 LPM1.addPass(LoopSimplifyCFGPass());
444
Chandler Carruthe3f50642016-12-22 06:59:15 +0000445 // Rotate Loop - disable header duplication at -Oz
446 LPM1.addPass(LoopRotatePass(Level != Oz));
Alina Sbirlea43709f72019-04-19 17:46:50 +0000447 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
Chandler Carruth86248d52017-05-26 01:24:11 +0000448 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000449 LPM2.addPass(IndVarSimplifyPass());
450 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000451
452 for (auto &C : LateLoopOptimizationsEPCallbacks)
453 C(LPM2, Level);
454
Chandler Carruth79b733b2017-01-26 23:21:17 +0000455 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000456 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000457 // because it changes IR to makes profile annotation in back compile
458 // inaccurate.
Rong Xudb29a3a2019-03-04 20:21:27 +0000459 if (Phase != ThinLTOPhase::PreLink || !PGOOpt ||
460 PGOOpt->Action != PGOOptions::SampleUse)
Teresa Johnsonecd90132017-08-02 20:35:29 +0000461 LPM2.addPass(LoopFullUnrollPass(Level));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000462
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000463 for (auto &C : LoopOptimizerEndEPCallbacks)
464 C(LPM2, Level);
465
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000466 // We provide the opt remark emitter pass for LICM to use. We only need to do
467 // this once as it is immutable.
468 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000469 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000470 FPM.addPass(SimplifyCFGPass());
471 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000472 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000473
474 // Eliminate redundancies.
475 if (Level != O1) {
476 // These passes add substantial compile time so skip them at O1.
477 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000478 if (RunNewGVN)
479 FPM.addPass(NewGVNPass());
480 else
481 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000482 }
483
484 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
485 FPM.addPass(MemCpyOptPass());
486
487 // Sparse conditional constant propagation.
488 // FIXME: It isn't clear why we do this *after* loop passes rather than
489 // before...
490 FPM.addPass(SCCPPass());
491
492 // Delete dead bit computations (instcombine runs after to fold away the dead
493 // computations, and then ADCE will run later to exploit any new DCE
494 // opportunities that creates).
495 FPM.addPass(BDCEPass());
496
497 // Run instcombine after redundancy and dead bit elimination to exploit
498 // opportunities opened up by them.
499 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000500 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000501
502 // Re-consider control flow based optimizations after redundancy elimination,
503 // redo DCE, etc.
504 FPM.addPass(JumpThreadingPass());
505 FPM.addPass(CorrelatedValuePropagationPass());
506 FPM.addPass(DSEPass());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000507 FPM.addPass(createFunctionToLoopPassAdaptor(
508 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
509 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000510
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000511 for (auto &C : ScalarOptimizerLateEPCallbacks)
512 C(FPM, Level);
513
Chandler Carruthe3f50642016-12-22 06:59:15 +0000514 // Finally, do an expensive DCE pass to catch all the dead code exposed by
515 // the simplifications and basic cleanup after all the simplifications.
516 FPM.addPass(ADCEPass());
517 FPM.addPass(SimplifyCFGPass());
518 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000519 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000520
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000521 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000522 (PGOOpt->Action == PGOOptions::IRUse ||
523 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000524 FPM.addPass(ControlHeightReductionPass());
525
Chandler Carruthe3f50642016-12-22 06:59:15 +0000526 return FPM;
527}
528
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000529void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
530 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000531 bool RunProfileGen, bool IsCS,
532 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000533 std::string ProfileRemappingFile) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000534 // Generally running simplification passes and the inliner with an high
535 // threshold results in smaller executables, but there may be cases where
536 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000537 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
538 // IsCS is true).
539 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000540 InlineParams IP;
541
542 // In the old pass manager, this is a cl::opt. Should still this be one?
543 IP.DefaultThreshold = 75;
544
545 // FIXME: The hint threshold has the same value used by the regular inliner.
546 // This should probably be lowered after performance testing.
547 // FIXME: this comment is cargo culted from the old pass manager, revisit).
548 IP.HintThreshold = 325;
549
550 CGSCCPassManager CGPipeline(DebugLogging);
551
552 CGPipeline.addPass(InlinerPass(IP));
553
554 FunctionPassManager FPM;
555 FPM.addPass(SROA());
556 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
557 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
558 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000559 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000560
Davide Italiano513dfaa2017-02-13 15:26:22 +0000561 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
562
563 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
564 }
565
Chandler Carruthf4d62c42017-05-25 07:15:09 +0000566 // Delete anything that is now dead to make sure that we don't instrument
567 // dead code. Instrumentation can end up keeping dead code around and
568 // dramatically increase code size.
569 MPM.addPass(GlobalDCEPass());
570
Davide Italiano513dfaa2017-02-13 15:26:22 +0000571 if (RunProfileGen) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000572 MPM.addPass(PGOInstrumentationGen(IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000573
Xinliang David Lib67530e2017-06-25 00:26:43 +0000574 FunctionPassManager FPM;
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000575 FPM.addPass(
576 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000577 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
578
Davide Italiano513dfaa2017-02-13 15:26:22 +0000579 // Add the profile lowering pass.
580 InstrProfOptions Options;
Rong Xudb29a3a2019-03-04 20:21:27 +0000581 if (!ProfileFile.empty())
582 Options.InstrProfileOutput = ProfileFile;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000583 Options.DoCounterPromotion = true;
Rong Xudb29a3a2019-03-04 20:21:27 +0000584 Options.UseBFIInPromotion = IsCS;
585 MPM.addPass(InstrProfiling(Options, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000586 } else if (!ProfileFile.empty()) {
Rong Xudb29a3a2019-03-04 20:21:27 +0000587 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000588 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
589 // RequireAnalysisPass for PSI before subsequent non-module passes.
590 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
591 }
Davide Italiano513dfaa2017-02-13 15:26:22 +0000592}
593
Easwaran Raman8249fac2017-06-28 13:33:49 +0000594static InlineParams
595getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
596 auto O3 = PassBuilder::O3;
597 unsigned OptLevel = Level > O3 ? 2 : Level;
598 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
599 return getInlineParams(OptLevel, SizeLevel);
600}
601
Chandler Carruthe3f50642016-12-22 06:59:15 +0000602ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000603PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000604 ThinLTOPhase Phase,
605 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000606 ModulePassManager MPM(DebugLogging);
607
Rong Xudb29a3a2019-03-04 20:21:27 +0000608 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000609
610 // In ThinLTO mode, when flattened profile is used, all the available
611 // profile information will be annotated in PreLink phase so there is
612 // no need to load the profile again in PostLink.
613 bool LoadSampleProfile =
614 HasSampleProfile &&
615 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
616
617 // During the ThinLTO backend phase we perform early indirect call promotion
618 // here, before globalopt. Otherwise imported available_externally functions
619 // look unreferenced and are removed. If we are going to load the sample
620 // profile then defer until later.
621 // TODO: See if we can move later and consolidate with the location where
622 // we perform ICP when we are loading a sample profile.
623 // TODO: We pass HasSampleProfile (whether there was a sample profile file
624 // passed to the compile) to the SamplePGO flag of ICP. This is used to
625 // determine whether the new direct calls are annotated with prof metadata.
626 // Ideally this should be determined from whether the IR is annotated with
627 // sample profile, and not whether the a sample profile was provided on the
628 // command line. E.g. for flattened profiles where we will not be reloading
629 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
630 // provide the sample profile file.
631 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
632 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
633
Chandler Carruthe3f50642016-12-22 06:59:15 +0000634 // Do basic inference of function attributes from known properties of system
635 // libraries and other oracles.
636 MPM.addPass(InferFunctionAttrsPass());
637
638 // Create an early function pass manager to cleanup the output of the
639 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000640 FunctionPassManager EarlyFPM(DebugLogging);
641 EarlyFPM.addPass(SimplifyCFGPass());
642 EarlyFPM.addPass(SROA());
643 EarlyFPM.addPass(EarlyCSEPass());
644 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000645 if (Level == O3)
646 EarlyFPM.addPass(CallSiteSplittingPass());
647
Dehao Chen08f88312017-08-07 20:23:20 +0000648 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
649 // to convert bitcast to direct calls so that they can be inlined during the
650 // profile annotation prepration step.
651 // More details about SamplePGO design can be found in:
652 // https://research.google.com/pubs/pub45290.html
653 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000654 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000655 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000656 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000657
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000658 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000659 // Annotate sample profile right after early FPM to ensure freshness of
660 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000661 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000662 PGOOpt->ProfileRemappingFile,
663 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000664 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
665 // RequireAnalysisPass for PSI before subsequent non-module passes.
666 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000667 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
668 // for the profile annotation to be accurate in the ThinLTO backend.
669 if (Phase != ThinLTOPhase::PreLink)
670 // We perform early indirect call promotion here, before globalopt.
671 // This is important for the ThinLTO backend phase because otherwise
672 // imported available_externally functions look unreferenced and are
673 // removed.
674 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000675 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000676 }
677
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000678 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000679 // and prior to optimizing globals.
680 // FIXME: This position in the pipeline hasn't been carefully considered in
681 // years, it should be re-analyzed.
682 MPM.addPass(IPSCCPPass());
683
Matthew Simpsoncb585582017-10-25 13:40:08 +0000684 // Attach metadata to indirect call sites indicating the set of functions
685 // they may target at run-time. This should follow IPSCCP.
686 MPM.addPass(CalledValuePropagationPass());
687
Chandler Carruthe3f50642016-12-22 06:59:15 +0000688 // Optimize globals to try and fold them into constants.
689 MPM.addPass(GlobalOptPass());
690
691 // Promote any localized globals to SSA registers.
692 // FIXME: Should this instead by a run of SROA?
693 // FIXME: We should probably run instcombine and simplify-cfg afterward to
694 // delete control flows that are dead once globals have been folded to
695 // constants.
696 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
697
698 // Remove any dead arguments exposed by cleanups and constand folding
699 // globals.
700 MPM.addPass(DeadArgumentEliminationPass());
701
702 // Create a small function pass pipeline to cleanup after all the global
703 // optimizations.
704 FunctionPassManager GlobalCleanupPM(DebugLogging);
705 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000706 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
707
Chandler Carruthe3f50642016-12-22 06:59:15 +0000708 GlobalCleanupPM.addPass(SimplifyCFGPass());
709 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
710
Dehao Chen89d32262017-08-02 01:28:31 +0000711 // Add all the requested passes for instrumentation PGO, if requested.
712 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000713 (PGOOpt->Action == PGOOptions::IRInstr ||
714 PGOOpt->Action == PGOOptions::IRUse)) {
715 addPGOInstrPasses(MPM, DebugLogging, Level,
716 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
717 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000718 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000719 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000720 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000721 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
722 PGOOpt->CSAction == PGOOptions::CSIRInstr)
723 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000724
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000725 // Synthesize function entry counts for non-PGO compilation.
726 if (EnableSyntheticCounts && !PGOOpt)
727 MPM.addPass(SyntheticCountsPropagation());
728
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000729 // Require the GlobalsAA analysis for the module so we can query it within
730 // the CGSCC pipeline.
731 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000732
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000733 // Require the ProfileSummaryAnalysis for the module so we can query it within
734 // the inliner pass.
735 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
736
Chandler Carruthe3f50642016-12-22 06:59:15 +0000737 // Now begin the main postorder CGSCC pipeline.
738 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
739 // manager and trying to emulate its precise behavior. Much of this doesn't
740 // make a lot of sense and we should revisit the core CGSCC structure.
741 CGSCCPassManager MainCGPipeline(DebugLogging);
742
743 // Note: historically, the PruneEH pass was run first to deduce nounwind and
744 // generally clean up exception handling overhead. It isn't clear this is
745 // valuable as the inliner doesn't currently care whether it is inlining an
746 // invoke or a call.
747
748 // Run the inliner first. The theory is that we are walking bottom-up and so
749 // the callees have already been fully optimized, and we want to inline them
750 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000751 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000752 // because it makes profile annotation in the backend inaccurate.
753 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000754 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
755 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000756 IP.HotCallSiteThreshold = 0;
757 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000758
759 // Now deduce any function attributes based in the current code.
760 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
761
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000762 // When at O3 add argument promotion to the pass pipeline.
763 // FIXME: It isn't at all clear why this should be limited to O3.
764 if (Level == O3)
765 MainCGPipeline.addPass(ArgumentPromotionPass());
766
Chandler Carruthe3f50642016-12-22 06:59:15 +0000767 // Lastly, add the core function simplification pipeline nested inside the
768 // CGSCC walk.
769 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000770 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000771
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000772 for (auto &C : CGSCCOptimizerLateEPCallbacks)
773 C(MainCGPipeline, Level);
774
Chandler Carruth719ffe12017-02-12 05:38:04 +0000775 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
776 // to detect when we devirtualize indirect calls and iterate the SCC passes
777 // in that case to try and catch knock-on inlining or function attrs
778 // opportunities. Then we add it to the module pipeline by walking the SCCs
779 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000780 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000781 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000782 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000783
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000784 return MPM;
785}
786
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000787ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
788 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000789 ModulePassManager MPM(DebugLogging);
790
791 // Optimize globals now that the module is fully simplified.
792 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000793 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000794
Xinliang David Li126157c2017-05-22 16:41:57 +0000795 // Run partial inlining pass to partially inline functions that have
796 // large bodies.
797 if (RunPartialInlining)
798 MPM.addPass(PartialInlinerPass());
799
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000800 // Remove avail extern fns and globals definitions since we aren't compiling
801 // an object file for later LTO. For LTO we want to preserve these so they
802 // are eligible for inlining at link-time. Note if they are unreferenced they
803 // will be removed by GlobalDCE later, so this only impacts referenced
804 // available externally globals. Eventually they will be suppressed during
805 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
806 // may make globals referenced by available external functions dead and saves
807 // running remaining passes on the eliminated functions.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000808 MPM.addPass(EliminateAvailableExternallyPass());
809
Manman Ren18295122019-02-28 20:13:38 +0000810 if (EnableOrderFileInstrumentation)
811 MPM.addPass(InstrOrderFilePass());
812
Chandler Carruthe3f50642016-12-22 06:59:15 +0000813 // Do RPO function attribute inference across the module to forward-propagate
814 // attributes where applicable.
815 // FIXME: Is this really an optimization rather than a canonicalization?
816 MPM.addPass(ReversePostOrderFunctionAttrsPass());
817
Rong Xudb29a3a2019-03-04 20:21:27 +0000818 // Do a post inline PGO instrumentation and use pass. This is a context
819 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
820 // cross-module inline has not been done yet. The context sensitive
821 // instrumentation is after all the inlines are done.
822 if (!LTOPreLink && PGOOpt) {
823 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
824 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
825 /* IsCS */ true, PGOOpt->CSProfileGenFile,
826 PGOOpt->ProfileRemappingFile);
827 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
828 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
829 /* IsCS */ true, PGOOpt->ProfileFile,
830 PGOOpt->ProfileRemappingFile);
831 }
832
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000833 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000834 // useful as the above will have inlined, DCE'ed, and function-attr
835 // propagated everything. We should at this point have a reasonably minimal
836 // and richly annotated call graph. By computing aliasing and mod/ref
837 // information for all local globals here, the late loop passes and notably
838 // the vectorizer will be able to use them to help recognize vectorizable
839 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000840 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000841
842 FunctionPassManager OptimizePM(DebugLogging);
843 OptimizePM.addPass(Float2IntPass());
844 // FIXME: We need to run some loop optimizations to re-rotate loops after
845 // simplify-cfg and others undo their rotation.
846
847 // Optimize the loop execution. These passes operate on entire loop nests
848 // rather than on each loop in an inside-out manner, and so they are actually
849 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000850
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000851 for (auto &C : VectorizerStartEPCallbacks)
852 C(OptimizePM, Level);
853
Chandler Carrutha95ff382017-01-27 00:50:21 +0000854 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000855 OptimizePM.addPass(
856 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000857
858 // Distribute loops to allow partial vectorization. I.e. isolate dependences
859 // into separate loop that would otherwise inhibit vectorization. This is
860 // currently only performed for loops marked with the metadata
861 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000862 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000863
864 // Now run the core loop vectorizer.
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000865 OptimizePM.addPass(LoopVectorizePass(
866 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000867
Chandler Carruthbaabda92017-01-27 01:32:26 +0000868 // Eliminate loads by forwarding stores from the previous iteration to loads
869 // of the current iteration.
870 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000871
872 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000873 OptimizePM.addPass(InstCombinePass());
874
Chandler Carrutha95ff382017-01-27 00:50:21 +0000875 // Now that we've formed fast to execute loop structures, we do further
876 // optimizations. These are run afterward as they might block doing complex
877 // analyses and transforms such as what are needed for loop vectorization.
878
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000879 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
880 // GVN, loop transforms, and others have already run, so it's now better to
881 // convert to more optimized IR using more aggressive simplify CFG options.
882 // The extra sinking transform can create larger basic blocks, so do this
883 // before SLP vectorization.
884 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
885 forwardSwitchCondToPhi(true).
886 convertSwitchToLookupTable(true).
887 needCanonicalLoops(false).
888 sinkCommonInsts(true)));
889
Chandler Carruthe3f50642016-12-22 06:59:15 +0000890 // Optimize parallel scalar instruction chains into SIMD instructions.
891 OptimizePM.addPass(SLPVectorizerPass());
892
Chandler Carruthe3f50642016-12-22 06:59:15 +0000893 OptimizePM.addPass(InstCombinePass());
894
895 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000896 // execution resources of an out-of-order processor. We also then need to
897 // clean up redundancies and loop invariant code.
898 // FIXME: It would be really good to use a loop-integrated instruction
899 // combiner for cleanup here so that the unrolling and LICM can be pipelined
900 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000901 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
902 if (EnableUnrollAndJam) {
903 OptimizePM.addPass(
904 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
905 }
Fedor Sergeev412ed342018-10-31 14:33:14 +0000906 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
Michael Kruse72448522018-12-12 17:32:52 +0000907 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000908 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000909 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000910 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
911 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
912 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000913
914 // Now that we've vectorized and unrolled loops, we may have more refined
915 // alignment information, try to re-derive it here.
916 OptimizePM.addPass(AlignmentFromAssumptionsPass());
917
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000918 // Split out cold code. Splitting is done late to avoid hiding context from
919 // other optimizations and inadvertently regressing performance. The tradeoff
920 // is that this has a higher code size cost than splitting early.
921 if (EnableHotColdSplit && !LTOPreLink)
922 MPM.addPass(HotColdSplittingPass());
923
Chandler Carrutha95ff382017-01-27 00:50:21 +0000924 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
925 // canonicalization pass that enables other optimizations. As a result,
926 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
927 // result too early.
928 OptimizePM.addPass(LoopSinkPass());
929
930 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000931 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000932
Sanjay Patel6fd43912017-09-09 13:38:18 +0000933 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
934 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
935 // flattening of blocks.
936 OptimizePM.addPass(DivRemPairsPass());
937
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000938 // LoopSink (and other loop passes since the last simplifyCFG) might have
939 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
940 OptimizePM.addPass(SimplifyCFGPass());
941
Chandler Carruthc34f7892017-11-28 11:32:31 +0000942 // Optimize PHIs by speculating around them when profitable. Note that this
943 // pass needs to be run after any PRE or similar pass as it is essentially
944 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
945 OptimizePM.addPass(SpeculateAroundPHIsPass());
946
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000947 for (auto &C : OptimizerLastEPCallbacks)
948 C(OptimizePM, Level);
949
Chandler Carrutha95ff382017-01-27 00:50:21 +0000950 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000951 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
952
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000953 MPM.addPass(CGProfilePass());
954
Chandler Carruthe3f50642016-12-22 06:59:15 +0000955 // Now we need to do some global optimization transforms.
956 // FIXME: It would seem like these should come first in the optimization
957 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
958 // ordering here.
959 MPM.addPass(GlobalDCEPass());
960 MPM.addPass(ConstantMergePass());
961
962 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000963}
964
Chandler Carruthe3f50642016-12-22 06:59:15 +0000965ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000966PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000967 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000968 assert(Level != O0 && "Must request optimizations for the default pipeline!");
969
970 ModulePassManager MPM(DebugLogging);
971
972 // Force any function attributes we want the rest of the pipeline to observe.
973 MPM.addPass(ForceFunctionAttrsPass());
974
David Blaikie0c64f5a2018-01-23 01:25:20 +0000975 // Apply module pipeline start EP callback.
976 for (auto &C : PipelineStartEPCallbacks)
977 C(MPM);
978
Dehao Chen08f88312017-08-07 20:23:20 +0000979 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +0000980 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
981
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000982 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +0000983 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
984 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000985
986 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000987 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000988
989 return MPM;
990}
991
992ModulePassManager
993PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
994 bool DebugLogging) {
995 assert(Level != O0 && "Must request optimizations for the default pipeline!");
996
997 ModulePassManager MPM(DebugLogging);
998
999 // Force any function attributes we want the rest of the pipeline to observe.
1000 MPM.addPass(ForceFunctionAttrsPass());
1001
Dehao Chen08f88312017-08-07 20:23:20 +00001002 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001003 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1004
David Blaikie0c64f5a2018-01-23 01:25:20 +00001005 // Apply module pipeline start EP callback.
1006 for (auto &C : PipelineStartEPCallbacks)
1007 C(MPM);
1008
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001009 // If we are planning to perform ThinLTO later, we don't bloat the code with
1010 // unrolling/vectorization/... now. Just simplify the module as much as we
1011 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001012 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1013 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001014
1015 // Run partial inlining pass to partially inline functions that have
1016 // large bodies.
1017 // FIXME: It isn't clear whether this is really the right place to run this
1018 // in ThinLTO. Because there is another canonicalization and simplification
1019 // phase that will run after the thin link, running this here ends up with
1020 // less information than will be available later and it may grow functions in
1021 // ways that aren't beneficial.
1022 if (RunPartialInlining)
1023 MPM.addPass(PartialInlinerPass());
1024
1025 // Reduce the size of the IR as much as possible.
1026 MPM.addPass(GlobalOptPass());
1027
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001028 return MPM;
1029}
1030
Teresa Johnson28023db2018-07-19 14:51:32 +00001031ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1032 OptimizationLevel Level, bool DebugLogging,
1033 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001034 ModulePassManager MPM(DebugLogging);
1035
Teresa Johnson28023db2018-07-19 14:51:32 +00001036 if (ImportSummary) {
1037 // These passes import type identifier resolutions for whole-program
1038 // devirtualization and CFI. They must run early because other passes may
1039 // disturb the specific instruction patterns that these passes look for,
1040 // creating dependencies on resolutions that may not appear in the summary.
1041 //
1042 // For example, GVN may transform the pattern assume(type.test) appearing in
1043 // two basic blocks into assume(phi(type.test, type.test)), which would
1044 // transform a dependency on a WPD resolution into a dependency on a type
1045 // identifier resolution for CFI.
1046 //
1047 // Also, WPD has access to more precise information than ICP and can
1048 // devirtualize more effectively, so it should operate on the IR first.
1049 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1050 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1051 }
1052
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001053 // Force any function attributes we want the rest of the pipeline to observe.
1054 MPM.addPass(ForceFunctionAttrsPass());
1055
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001056 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001057 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1058 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001059
1060 // Now add the optimization pipeline.
1061 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1062
1063 return MPM;
1064}
1065
1066ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001067PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1068 bool DebugLogging) {
1069 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001070 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001071 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001072 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001073}
1074
Teresa Johnson28023db2018-07-19 14:51:32 +00001075ModulePassManager
1076PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1077 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001078 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1079 ModulePassManager MPM(DebugLogging);
1080
Rong Xudb29a3a2019-03-04 20:21:27 +00001081 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001082 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001083 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001084 PGOOpt->ProfileRemappingFile,
1085 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001086 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1087 // RequireAnalysisPass for PSI before subsequent non-module passes.
1088 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001089 }
1090
Davide Italiano089a9122017-01-24 00:57:39 +00001091 // Remove unused virtual tables to improve the quality of code generated by
1092 // whole-program devirtualization and bitset lowering.
1093 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001094
Davide Italiano089a9122017-01-24 00:57:39 +00001095 // Force any function attributes we want the rest of the pipeline to observe.
1096 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001097
Davide Italiano089a9122017-01-24 00:57:39 +00001098 // Do basic inference of function attributes from known properties of system
1099 // libraries and other oracles.
1100 MPM.addPass(InferFunctionAttrsPass());
1101
1102 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001103 FunctionPassManager EarlyFPM(DebugLogging);
1104 EarlyFPM.addPass(CallSiteSplittingPass());
1105 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1106
Davide Italiano089a9122017-01-24 00:57:39 +00001107 // Indirect call promotion. This should promote all the targets that are
1108 // left by the earlier promotion pass that promotes intra-module targets.
1109 // This two-step promotion is to save the compile time. For LTO, it should
1110 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001111 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001112 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001113 // Propagate constants at call sites into the functions they call. This
1114 // opens opportunities for globalopt (and inlining) by substituting function
1115 // pointers passed as arguments to direct uses of functions.
1116 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001117
1118 // Attach metadata to indirect call sites indicating the set of functions
1119 // they may target at run-time. This should follow IPSCCP.
1120 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001121 }
1122
1123 // Now deduce any function attributes based in the current code.
1124 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1125 PostOrderFunctionAttrsPass()));
1126
1127 // Do RPO function attribute inference across the module to forward-propagate
1128 // attributes where applicable.
1129 // FIXME: Is this really an optimization rather than a canonicalization?
1130 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1131
Eric Christopher721eaef2019-02-26 20:33:22 +00001132 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001133 MPM.addPass(GlobalSplitPass());
1134
1135 // Run whole program optimization of virtual call when the list of callees
1136 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001137 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001138
1139 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001140 if (Level == 1) {
1141 // The LowerTypeTestsPass needs to run to lower type metadata and the
1142 // type.test intrinsics. The pass does nothing if CFI is disabled.
1143 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001144 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001145 }
Davide Italiano089a9122017-01-24 00:57:39 +00001146
1147 // Optimize globals to try and fold them into constants.
1148 MPM.addPass(GlobalOptPass());
1149
1150 // Promote any localized globals to SSA registers.
1151 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1152
1153 // Linking modules together can lead to duplicate global constant, only
1154 // keep one copy of each constant.
1155 MPM.addPass(ConstantMergePass());
1156
1157 // Remove unused arguments from functions.
1158 MPM.addPass(DeadArgumentEliminationPass());
1159
1160 // Reduce the code after globalopt and ipsccp. Both can open up significant
1161 // simplification opportunities, and both can propagate functions through
1162 // function pointers. When this happens, we often have to resolve varargs
1163 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001164 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001165 if (Level == O3)
1166 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001167 PeepholeFPM.addPass(InstCombinePass());
1168 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1169
1170 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001171
1172 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1173 // generally clean up exception handling overhead. It isn't clear this is
1174 // valuable as the inliner doesn't currently care whether it is inlining an
1175 // invoke or a call.
1176 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001177 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1178 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001179
1180 // Optimize globals again after we ran the inliner.
1181 MPM.addPass(GlobalOptPass());
1182
1183 // Garbage collect dead functions.
1184 // FIXME: Add ArgumentPromotion pass after once it's ported.
1185 MPM.addPass(GlobalDCEPass());
1186
1187 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001188 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001189 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001190 invokePeepholeEPCallbacks(FPM, Level);
1191
Davide Italiano089a9122017-01-24 00:57:39 +00001192 FPM.addPass(JumpThreadingPass());
1193
Rong Xudb29a3a2019-03-04 20:21:27 +00001194 // Do a post inline PGO instrumentation and use pass. This is a context
1195 // sensitive PGO pass.
1196 if (PGOOpt) {
1197 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1198 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1199 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1200 PGOOpt->ProfileRemappingFile);
1201 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1202 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1203 /* IsCS */ true, PGOOpt->ProfileFile,
1204 PGOOpt->ProfileRemappingFile);
1205 }
1206
Davide Italiano089a9122017-01-24 00:57:39 +00001207 // Break up allocas
1208 FPM.addPass(SROA());
1209
Robert Lougherf2158a82019-03-20 19:08:18 +00001210 // LTO provides additional opportunities for tailcall elimination due to
1211 // link-time inlining, and visibility of nocapture attribute.
1212 FPM.addPass(TailCallElimPass());
1213
Davide Italiano089a9122017-01-24 00:57:39 +00001214 // Run a few AA driver optimizations here and now to cleanup the code.
1215 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1216
1217 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1218 PostOrderFunctionAttrsPass()));
1219 // FIXME: here we run IP alias analysis in the legacy PM.
1220
1221 FunctionPassManager MainFPM;
1222
1223 // FIXME: once we fix LoopPass Manager, add LICM here.
1224 // FIXME: once we provide support for enabling MLSM, add it here.
1225 // FIXME: once we provide support for enabling NewGVN, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001226 if (RunNewGVN)
1227 MainFPM.addPass(NewGVNPass());
1228 else
1229 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001230
1231 // Remove dead memcpy()'s.
1232 MainFPM.addPass(MemCpyOptPass());
1233
1234 // Nuke dead stores.
1235 MainFPM.addPass(DSEPass());
1236
1237 // FIXME: at this point, we run a bunch of loop passes:
1238 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1239 // loopVectorize. Enable them once the remaining issue with LPM
1240 // are sorted out.
1241
1242 MainFPM.addPass(InstCombinePass());
1243 MainFPM.addPass(SimplifyCFGPass());
1244 MainFPM.addPass(SCCPPass());
1245 MainFPM.addPass(InstCombinePass());
1246 MainFPM.addPass(BDCEPass());
1247
1248 // FIXME: We may want to run SLPVectorizer here.
1249 // After vectorization, assume intrinsics may tell us more
1250 // about pointer alignments.
1251#if 0
1252 MainFPM.add(AlignmentFromAssumptionsPass());
1253#endif
1254
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001255 // FIXME: Conditionally run LoadCombine here, after it's ported
1256 // (in case we still have this pass, given its questionable usefulness).
1257
Davide Italiano089a9122017-01-24 00:57:39 +00001258 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001259 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001260 MainFPM.addPass(JumpThreadingPass());
1261 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1262
1263 // Create a function that performs CFI checks for cross-DSO calls with
1264 // targets in the current module.
1265 MPM.addPass(CrossDSOCFIPass());
1266
1267 // Lower type metadata and the type.test intrinsic. This pass supports
1268 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1269 // to be run at link time if CFI is enabled. This pass does nothing if
1270 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001271 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001272
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001273 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1274 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1275 if (EnableHotColdSplit)
1276 MPM.addPass(HotColdSplittingPass());
1277
Davide Italiano089a9122017-01-24 00:57:39 +00001278 // Add late LTO optimization passes.
1279 // Delete basic blocks, which optimization passes may have killed.
1280 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1281
1282 // Drop bodies of available eternally objects to improve GlobalDCE.
1283 MPM.addPass(EliminateAvailableExternallyPass());
1284
1285 // Now that we have optimized the program, discard unreachable functions.
1286 MPM.addPass(GlobalDCEPass());
1287
1288 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001289 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001290}
1291
Chandler Carruth060ad612016-12-23 20:38:19 +00001292AAManager PassBuilder::buildDefaultAAPipeline() {
1293 AAManager AA;
1294
1295 // The order in which these are registered determines their priority when
1296 // being queried.
1297
1298 // First we register the basic alias analysis that provides the majority of
1299 // per-function local AA logic. This is a stateless, on-demand local set of
1300 // AA techniques.
1301 AA.registerFunctionAnalysis<BasicAA>();
1302
1303 // Next we query fast, specialized alias analyses that wrap IR-embedded
1304 // information about aliasing.
1305 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1306 AA.registerFunctionAnalysis<TypeBasedAA>();
1307
1308 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001309 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1310 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001311 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001312 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001313
1314 return AA;
1315}
1316
Chandler Carruth241bf242016-08-03 07:44:48 +00001317static Optional<int> parseRepeatPassName(StringRef Name) {
1318 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1319 return None;
1320 int Count;
1321 if (Name.getAsInteger(0, Count) || Count <= 0)
1322 return None;
1323 return Count;
1324}
1325
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001326static Optional<int> parseDevirtPassName(StringRef Name) {
1327 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1328 return None;
1329 int Count;
1330 if (Name.getAsInteger(0, Count) || Count <= 0)
1331 return None;
1332 return Count;
1333}
1334
Fedor Sergeevb7871402019-01-10 10:01:53 +00001335static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1336 if (!Name.consume_front(PassName))
1337 return false;
1338 // normal pass name w/o parameters == default parameters
1339 if (Name.empty())
1340 return true;
1341 return Name.startswith("<") && Name.endswith(">");
1342}
1343
1344namespace {
1345
1346/// This performs customized parsing of pass name with parameters.
1347///
1348/// We do not need parametrization of passes in textual pipeline very often,
1349/// yet on a rare occasion ability to specify parameters right there can be
1350/// useful.
1351///
1352/// \p Name - parameterized specification of a pass from a textual pipeline
1353/// is a string in a form of :
1354/// PassName '<' parameter-list '>'
1355///
1356/// Parameter list is being parsed by the parser callable argument, \p Parser,
1357/// It takes a string-ref of parameters and returns either StringError or a
1358/// parameter list in a form of a custom parameters type, all wrapped into
1359/// Expected<> template class.
1360///
1361template <typename ParametersParseCallableT>
1362auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1363 StringRef PassName) -> decltype(Parser(StringRef{})) {
1364 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1365
1366 StringRef Params = Name;
1367 if (!Params.consume_front(PassName)) {
1368 assert(false &&
1369 "unable to strip pass name from parametrized pass specification");
1370 }
1371 if (Params.empty())
1372 return ParametersT{};
1373 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1374 assert(false && "invalid format for parametrized pass name");
1375 }
1376
1377 Expected<ParametersT> Result = Parser(Params);
1378 assert((Result || Result.template errorIsA<StringError>()) &&
1379 "Pass parameter parser can only return StringErrors.");
1380 return std::move(Result);
1381}
1382
1383/// Parser of parameters for LoopUnroll pass.
1384Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1385 LoopUnrollOptions UnrollOpts;
1386 while (!Params.empty()) {
1387 StringRef ParamName;
1388 std::tie(ParamName, Params) = Params.split(';');
1389 int OptLevel = StringSwitch<int>(ParamName)
1390 .Case("O0", 0)
1391 .Case("O1", 1)
1392 .Case("O2", 2)
1393 .Case("O3", 3)
1394 .Default(-1);
1395 if (OptLevel >= 0) {
1396 UnrollOpts.setOptLevel(OptLevel);
1397 continue;
1398 }
1399
1400 bool Enable = !ParamName.consume_front("no-");
1401 if (ParamName == "partial") {
1402 UnrollOpts.setPartial(Enable);
1403 } else if (ParamName == "peeling") {
1404 UnrollOpts.setPeeling(Enable);
1405 } else if (ParamName == "runtime") {
1406 UnrollOpts.setRuntime(Enable);
1407 } else if (ParamName == "upperbound") {
1408 UnrollOpts.setUpperBound(Enable);
1409 } else {
1410 return make_error<StringError>(
1411 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1412 inconvertibleErrorCode());
1413 }
1414 }
1415 return UnrollOpts;
1416}
1417
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001418Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1419 MemorySanitizerOptions Result;
1420 while (!Params.empty()) {
1421 StringRef ParamName;
1422 std::tie(ParamName, Params) = Params.split(';');
1423
1424 if (ParamName == "recover") {
1425 Result.Recover = true;
1426 } else if (ParamName == "kernel") {
1427 Result.Kernel = true;
1428 } else if (ParamName.consume_front("track-origins=")) {
1429 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1430 return make_error<StringError>(
1431 formatv("invalid argument to MemorySanitizer pass track-origins "
1432 "parameter: '{0}' ",
1433 ParamName)
1434 .str(),
1435 inconvertibleErrorCode());
1436 } else {
1437 return make_error<StringError>(
1438 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1439 .str(),
1440 inconvertibleErrorCode());
1441 }
1442 }
1443 return Result;
1444}
1445
Serguei Katkovf5432832019-04-15 08:57:53 +00001446/// Parser of parameters for SimplifyCFG pass.
1447Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1448 SimplifyCFGOptions Result;
1449 while (!Params.empty()) {
1450 StringRef ParamName;
1451 std::tie(ParamName, Params) = Params.split(';');
1452
1453 bool Enable = !ParamName.consume_front("no-");
1454 if (ParamName == "forward-switch-cond") {
1455 Result.forwardSwitchCondToPhi(Enable);
1456 } else if (ParamName == "switch-to-lookup") {
1457 Result.convertSwitchToLookupTable(Enable);
1458 } else if (ParamName == "keep-loops") {
1459 Result.needCanonicalLoops(Enable);
1460 } else if (ParamName == "sink-common-insts") {
1461 Result.sinkCommonInsts(Enable);
1462 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1463 APInt BonusInstThreshold;
1464 if (ParamName.getAsInteger(0, BonusInstThreshold))
1465 return make_error<StringError>(
1466 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1467 "parameter: '{0}' ",
1468 ParamName).str(),
1469 inconvertibleErrorCode());
1470 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1471 } else {
1472 return make_error<StringError>(
1473 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1474 inconvertibleErrorCode());
1475 }
1476 }
1477 return Result;
1478}
1479
Serguei Katkovca6c03a2019-04-18 08:46:11 +00001480/// Parser of parameters for LoopVectorize pass.
1481Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1482 LoopVectorizeOptions Opts;
1483 while (!Params.empty()) {
1484 StringRef ParamName;
1485 std::tie(ParamName, Params) = Params.split(';');
1486
1487 bool Enable = !ParamName.consume_front("no-");
1488 if (ParamName == "interleave-forced-only") {
1489 Opts.setInterleaveOnlyWhenForced(Enable);
1490 } else if (ParamName == "vectorize-forced-only") {
1491 Opts.setVectorizeOnlyWhenForced(Enable);
1492 } else {
1493 return make_error<StringError>(
1494 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1495 inconvertibleErrorCode());
1496 }
1497 }
1498 return Opts;
1499}
1500
Fedor Sergeevb7871402019-01-10 10:01:53 +00001501} // namespace
1502
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001503/// Tests whether a pass name starts with a valid prefix for a default pipeline
1504/// alias.
1505static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1506 return Name.startswith("default") || Name.startswith("thinlto") ||
1507 Name.startswith("lto");
1508}
1509
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001510/// Tests whether registered callbacks will accept a given pass name.
1511///
1512/// When parsing a pipeline text, the type of the outermost pipeline may be
1513/// omitted, in which case the type is automatically determined from the first
1514/// pass name in the text. This may be a name that is handled through one of the
1515/// callbacks. We check this through the oridinary parsing callbacks by setting
1516/// up a dummy PassManager in order to not force the client to also handle this
1517/// type of query.
1518template <typename PassManagerT, typename CallbacksT>
1519static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1520 if (!Callbacks.empty()) {
1521 PassManagerT DummyPM;
1522 for (auto &CB : Callbacks)
1523 if (CB(Name, DummyPM, {}))
1524 return true;
1525 }
1526 return false;
1527}
1528
1529template <typename CallbacksT>
1530static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001531 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001532 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001533 return DefaultAliasRegex.match(Name);
1534
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001535 // Explicitly handle pass manager names.
1536 if (Name == "module")
1537 return true;
1538 if (Name == "cgscc")
1539 return true;
1540 if (Name == "function")
1541 return true;
1542
Chandler Carruth241bf242016-08-03 07:44:48 +00001543 // Explicitly handle custom-parsed pass names.
1544 if (parseRepeatPassName(Name))
1545 return true;
1546
Chandler Carruth74a8a222016-06-17 07:15:29 +00001547#define MODULE_PASS(NAME, CREATE_PASS) \
1548 if (Name == NAME) \
1549 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001550#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001551 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001552 return true;
1553#include "PassRegistry.def"
1554
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001555 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001556}
1557
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001558template <typename CallbacksT>
1559static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001560 // Explicitly handle pass manager names.
1561 if (Name == "cgscc")
1562 return true;
1563 if (Name == "function")
1564 return true;
1565
Chandler Carruth241bf242016-08-03 07:44:48 +00001566 // Explicitly handle custom-parsed pass names.
1567 if (parseRepeatPassName(Name))
1568 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001569 if (parseDevirtPassName(Name))
1570 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001571
Chandler Carruth74a8a222016-06-17 07:15:29 +00001572#define CGSCC_PASS(NAME, CREATE_PASS) \
1573 if (Name == NAME) \
1574 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001575#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001576 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001577 return true;
1578#include "PassRegistry.def"
1579
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001580 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001581}
1582
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001583template <typename CallbacksT>
1584static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001585 // Explicitly handle pass manager names.
1586 if (Name == "function")
1587 return true;
1588 if (Name == "loop")
1589 return true;
1590
Chandler Carruth241bf242016-08-03 07:44:48 +00001591 // Explicitly handle custom-parsed pass names.
1592 if (parseRepeatPassName(Name))
1593 return true;
1594
Chandler Carruth74a8a222016-06-17 07:15:29 +00001595#define FUNCTION_PASS(NAME, CREATE_PASS) \
1596 if (Name == NAME) \
1597 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001598#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1599 if (checkParametrizedPassName(Name, NAME)) \
1600 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001601#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001602 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001603 return true;
1604#include "PassRegistry.def"
1605
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001606 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001607}
1608
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001609template <typename CallbacksT>
1610static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001611 // Explicitly handle pass manager names.
1612 if (Name == "loop")
1613 return true;
1614
Chandler Carruth241bf242016-08-03 07:44:48 +00001615 // Explicitly handle custom-parsed pass names.
1616 if (parseRepeatPassName(Name))
1617 return true;
1618
Chandler Carruth74a8a222016-06-17 07:15:29 +00001619#define LOOP_PASS(NAME, CREATE_PASS) \
1620 if (Name == NAME) \
1621 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001622#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1623 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1624 return true;
1625#include "PassRegistry.def"
1626
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001627 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001628}
1629
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001630Optional<std::vector<PassBuilder::PipelineElement>>
1631PassBuilder::parsePipelineText(StringRef Text) {
1632 std::vector<PipelineElement> ResultPipeline;
1633
1634 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1635 &ResultPipeline};
1636 for (;;) {
1637 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1638 size_t Pos = Text.find_first_of(",()");
1639 Pipeline.push_back({Text.substr(0, Pos), {}});
1640
1641 // If we have a single terminating name, we're done.
1642 if (Pos == Text.npos)
1643 break;
1644
1645 char Sep = Text[Pos];
1646 Text = Text.substr(Pos + 1);
1647 if (Sep == ',')
1648 // Just a name ending in a comma, continue.
1649 continue;
1650
1651 if (Sep == '(') {
1652 // Push the inner pipeline onto the stack to continue processing.
1653 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1654 continue;
1655 }
1656
1657 assert(Sep == ')' && "Bogus separator!");
1658 // When handling the close parenthesis, we greedily consume them to avoid
1659 // empty strings in the pipeline.
1660 do {
1661 // If we try to pop the outer pipeline we have unbalanced parentheses.
1662 if (PipelineStack.size() == 1)
1663 return None;
1664
1665 PipelineStack.pop_back();
1666 } while (Text.consume_front(")"));
1667
1668 // Check if we've finished parsing.
1669 if (Text.empty())
1670 break;
1671
1672 // Otherwise, the end of an inner pipeline always has to be followed by
1673 // a comma, and then we can continue.
1674 if (!Text.consume_front(","))
1675 return None;
1676 }
1677
1678 if (PipelineStack.size() > 1)
1679 // Unbalanced paretheses.
1680 return None;
1681
1682 assert(PipelineStack.back() == &ResultPipeline &&
1683 "Wrong pipeline at the bottom of the stack!");
1684 return {std::move(ResultPipeline)};
1685}
1686
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001687Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1688 const PipelineElement &E,
1689 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001690 auto &Name = E.Name;
1691 auto &InnerPipeline = E.InnerPipeline;
1692
1693 // First handle complex passes like the pass managers which carry pipelines.
1694 if (!InnerPipeline.empty()) {
1695 if (Name == "module") {
1696 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001697 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1698 VerifyEachPass, DebugLogging))
1699 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001700 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001701 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001702 }
1703 if (Name == "cgscc") {
1704 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001705 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1706 DebugLogging))
1707 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001708 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001709 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001710 }
1711 if (Name == "function") {
1712 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001713 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1714 VerifyEachPass, DebugLogging))
1715 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001716 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001717 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001718 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001719 if (auto Count = parseRepeatPassName(Name)) {
1720 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001721 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1722 VerifyEachPass, DebugLogging))
1723 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001724 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001725 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001726 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001727
1728 for (auto &C : ModulePipelineParsingCallbacks)
1729 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001730 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001731
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001732 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001733 return make_error<StringError>(
1734 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1735 inconvertibleErrorCode());
1736 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001737 }
1738
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001739 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001740 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001741 SmallVector<StringRef, 3> Matches;
1742 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001743 return make_error<StringError>(
1744 formatv("unknown default pipeline alias '{0}'", Name).str(),
1745 inconvertibleErrorCode());
1746
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001747 assert(Matches.size() == 3 && "Must capture two matched strings!");
1748
Jordan Rosef85a95f2016-07-25 18:34:51 +00001749 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001750 .Case("O0", O0)
1751 .Case("O1", O1)
1752 .Case("O2", O2)
1753 .Case("O3", O3)
1754 .Case("Os", Os)
1755 .Case("Oz", Oz);
Chandler Carruthe3f50642016-12-22 06:59:15 +00001756 if (L == O0)
1757 // At O0 we do nothing at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001758 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001759
1760 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001761 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001762 } else if (Matches[1] == "thinlto-pre-link") {
1763 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1764 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001765 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001766 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001767 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001768 } else {
1769 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001770 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001771 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001772 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001773 }
1774
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001775 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001776#define MODULE_PASS(NAME, CREATE_PASS) \
1777 if (Name == NAME) { \
1778 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001779 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001780 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001781#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1782 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001783 MPM.addPass( \
1784 RequireAnalysisPass< \
1785 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001786 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001787 } \
1788 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001789 MPM.addPass(InvalidateAnalysisPass< \
1790 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001791 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001792 }
1793#include "PassRegistry.def"
1794
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001795 for (auto &C : ModulePipelineParsingCallbacks)
1796 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001797 return Error::success();
1798 return make_error<StringError>(
1799 formatv("unknown module pass '{0}'", Name).str(),
1800 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001801}
1802
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001803Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1804 const PipelineElement &E, bool VerifyEachPass,
1805 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001806 auto &Name = E.Name;
1807 auto &InnerPipeline = E.InnerPipeline;
1808
1809 // First handle complex passes like the pass managers which carry pipelines.
1810 if (!InnerPipeline.empty()) {
1811 if (Name == "cgscc") {
1812 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001813 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1814 VerifyEachPass, DebugLogging))
1815 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001816 // Add the nested pass manager with the appropriate adaptor.
1817 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001818 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001819 }
1820 if (Name == "function") {
1821 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001822 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1823 VerifyEachPass, DebugLogging))
1824 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001825 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001826 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001827 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001828 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001829 if (auto Count = parseRepeatPassName(Name)) {
1830 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001831 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1832 VerifyEachPass, DebugLogging))
1833 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001834 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001835 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001836 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001837 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1838 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001839 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1840 VerifyEachPass, DebugLogging))
1841 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001842 CGPM.addPass(
1843 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001844 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001845 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001846
1847 for (auto &C : CGSCCPipelineParsingCallbacks)
1848 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001849 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001850
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001851 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001852 return make_error<StringError>(
1853 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1854 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001855 }
1856
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001857// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001858#define CGSCC_PASS(NAME, CREATE_PASS) \
1859 if (Name == NAME) { \
1860 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001861 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001862 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001863#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1864 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001865 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001866 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001867 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1868 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001869 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001870 } \
1871 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001872 CGPM.addPass(InvalidateAnalysisPass< \
1873 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001874 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001875 }
1876#include "PassRegistry.def"
1877
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001878 for (auto &C : CGSCCPipelineParsingCallbacks)
1879 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001880 return Error::success();
1881 return make_error<StringError>(
1882 formatv("unknown cgscc pass '{0}'", Name).str(),
1883 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001884}
1885
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001886Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1887 const PipelineElement &E,
1888 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001889 auto &Name = E.Name;
1890 auto &InnerPipeline = E.InnerPipeline;
1891
1892 // First handle complex passes like the pass managers which carry pipelines.
1893 if (!InnerPipeline.empty()) {
1894 if (Name == "function") {
1895 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001896 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1897 VerifyEachPass, DebugLogging))
1898 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001899 // Add the nested pass manager with the appropriate adaptor.
1900 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001901 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001902 }
1903 if (Name == "loop") {
1904 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001905 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1906 DebugLogging))
1907 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001908 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001909 FPM.addPass(
1910 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001911 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001912 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001913 if (auto Count = parseRepeatPassName(Name)) {
1914 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001915 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1916 VerifyEachPass, DebugLogging))
1917 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001918 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001919 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001920 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001921
1922 for (auto &C : FunctionPipelineParsingCallbacks)
1923 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001924 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001925
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001926 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001927 return make_error<StringError>(
1928 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1929 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001930 }
1931
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001932// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001933#define FUNCTION_PASS(NAME, CREATE_PASS) \
1934 if (Name == NAME) { \
1935 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001936 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001937 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00001938#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1939 if (checkParametrizedPassName(Name, NAME)) { \
1940 auto Params = parsePassParameters(PARSER, Name, NAME); \
1941 if (!Params) \
1942 return Params.takeError(); \
1943 FPM.addPass(CREATE_PASS(Params.get())); \
1944 return Error::success(); \
1945 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001946#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1947 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001948 FPM.addPass( \
1949 RequireAnalysisPass< \
1950 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001951 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001952 } \
1953 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001954 FPM.addPass(InvalidateAnalysisPass< \
1955 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001956 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001957 }
1958#include "PassRegistry.def"
1959
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001960 for (auto &C : FunctionPipelineParsingCallbacks)
1961 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001962 return Error::success();
1963 return make_error<StringError>(
1964 formatv("unknown function pass '{0}'", Name).str(),
1965 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00001966}
1967
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001968Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1969 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00001970 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001971 auto &InnerPipeline = E.InnerPipeline;
1972
1973 // First handle complex passes like the pass managers which carry pipelines.
1974 if (!InnerPipeline.empty()) {
1975 if (Name == "loop") {
1976 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001977 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1978 VerifyEachPass, DebugLogging))
1979 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001980 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00001981 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001982 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001983 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001984 if (auto Count = parseRepeatPassName(Name)) {
1985 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001986 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1987 VerifyEachPass, DebugLogging))
1988 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001989 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001990 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001991 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001992
1993 for (auto &C : LoopPipelineParsingCallbacks)
1994 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001995 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001996
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001997 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001998 return make_error<StringError>(
1999 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2000 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002001 }
2002
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002003// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00002004#define LOOP_PASS(NAME, CREATE_PASS) \
2005 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002006 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002007 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002008 }
2009#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2010 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002011 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002012 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2013 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2014 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002015 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002016 } \
2017 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002018 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00002019 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002020 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002021 }
2022#include "PassRegistry.def"
2023
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002024 for (auto &C : LoopPipelineParsingCallbacks)
2025 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002026 return Error::success();
2027 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2028 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002029}
2030
Chandler Carruthedf59962016-02-18 09:45:17 +00002031bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002032#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2033 if (Name == NAME) { \
2034 AA.registerModuleAnalysis< \
2035 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2036 return true; \
2037 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002038#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2039 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002040 AA.registerFunctionAnalysis< \
2041 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002042 return true; \
2043 }
2044#include "PassRegistry.def"
2045
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002046 for (auto &C : AAParsingCallbacks)
2047 if (C(Name, AA))
2048 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002049 return false;
2050}
2051
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002052Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002053 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002054 bool VerifyEachPass,
2055 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002056 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002057 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2058 return Err;
2059 // FIXME: No verifier support for Loop passes!
2060 }
2061 return Error::success();
2062}
2063
2064Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2065 ArrayRef<PipelineElement> Pipeline,
2066 bool VerifyEachPass,
2067 bool DebugLogging) {
2068 for (const auto &Element : Pipeline) {
2069 if (auto Err =
2070 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2071 return Err;
2072 if (VerifyEachPass)
2073 FPM.addPass(VerifierPass());
2074 }
2075 return Error::success();
2076}
2077
2078Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2079 ArrayRef<PipelineElement> Pipeline,
2080 bool VerifyEachPass,
2081 bool DebugLogging) {
2082 for (const auto &Element : Pipeline) {
2083 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2084 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002085 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002086 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002087 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002088}
2089
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002090void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2091 FunctionAnalysisManager &FAM,
2092 CGSCCAnalysisManager &CGAM,
2093 ModuleAnalysisManager &MAM) {
2094 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2095 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002096 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2097 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2098 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2099 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2100 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2101}
2102
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002103Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2104 ArrayRef<PipelineElement> Pipeline,
2105 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 = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2109 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002110 if (VerifyEachPass)
2111 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002112 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002113 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002114}
2115
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002116// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002117// FIXME: Should this routine accept a TargetMachine or require the caller to
2118// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002119Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2120 StringRef PipelineText,
2121 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002122 auto Pipeline = parsePipelineText(PipelineText);
2123 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002124 return make_error<StringError>(
2125 formatv("invalid pipeline '{0}'", PipelineText).str(),
2126 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002127
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002128 // If the first name isn't at the module layer, wrap the pipeline up
2129 // automatically.
2130 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002131
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002132 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2133 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002134 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002135 } else if (isFunctionPassName(FirstName,
2136 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002137 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002138 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002139 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002140 } else {
2141 for (auto &C : TopLevelPipelineParsingCallbacks)
2142 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002143 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002144
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002145 // Unknown pass or pipeline name!
2146 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2147 return make_error<StringError>(
2148 formatv("unknown {0} name '{1}'",
2149 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2150 .str(),
2151 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002152 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002153 }
2154
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002155 if (auto Err =
2156 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2157 return Err;
2158 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002159}
Chandler Carruthedf59962016-02-18 09:45:17 +00002160
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002161// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002162Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2163 StringRef PipelineText,
2164 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002165 auto Pipeline = parsePipelineText(PipelineText);
2166 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002167 return make_error<StringError>(
2168 formatv("invalid pipeline '{0}'", PipelineText).str(),
2169 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002170
2171 StringRef FirstName = Pipeline->front().Name;
2172 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002173 return make_error<StringError>(
2174 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2175 PipelineText)
2176 .str(),
2177 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002178
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002179 if (auto Err =
2180 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2181 return Err;
2182 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002183}
2184
2185// Primary pass pipeline description parsing routine for a \c
2186// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002187Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2188 StringRef PipelineText,
2189 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002190 auto Pipeline = parsePipelineText(PipelineText);
2191 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002192 return make_error<StringError>(
2193 formatv("invalid pipeline '{0}'", PipelineText).str(),
2194 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002195
2196 StringRef FirstName = Pipeline->front().Name;
2197 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002198 return make_error<StringError>(
2199 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2200 PipelineText)
2201 .str(),
2202 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002203
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002204 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2205 DebugLogging))
2206 return Err;
2207 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002208}
2209
2210// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002211Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2212 StringRef PipelineText,
2213 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002214 auto Pipeline = parsePipelineText(PipelineText);
2215 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002216 return make_error<StringError>(
2217 formatv("invalid pipeline '{0}'", PipelineText).str(),
2218 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002219
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002220 if (auto Err =
2221 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2222 return Err;
2223
2224 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002225}
2226
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002227Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002228 // If the pipeline just consists of the word 'default' just replace the AA
2229 // manager with our default one.
2230 if (PipelineText == "default") {
2231 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002232 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002233 }
2234
Chandler Carruthedf59962016-02-18 09:45:17 +00002235 while (!PipelineText.empty()) {
2236 StringRef Name;
2237 std::tie(Name, PipelineText) = PipelineText.split(',');
2238 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002239 return make_error<StringError>(
2240 formatv("unknown alias analysis name '{0}'", Name).str(),
2241 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002242 }
2243
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002244 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002245}