blob: 6cb6afa00d83b5b35f77f0561b80d63d0c1b5d82 [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"
Johannes Doerfertaade7822019-06-05 03:02:24 +000068#include "llvm/Transforms/IPO/Attributor.h"
Matthew Simpsoncb585582017-10-25 13:40:08 +000069#include "llvm/Transforms/IPO/CalledValuePropagation.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000070#include "llvm/Transforms/IPO/ConstantMerge.h"
Davide Italiano92b933a2016-07-09 03:25:35 +000071#include "llvm/Transforms/IPO/CrossDSOCFI.h"
Sean Silvae3bb4572016-06-12 09:16:39 +000072#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
Davide Italiano344e8382016-05-05 02:37:32 +000073#include "llvm/Transforms/IPO/ElimAvailExtern.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000074#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
Chandler Carruth9c4ed172016-02-18 11:03:11 +000075#include "llvm/Transforms/IPO/FunctionAttrs.h"
Teresa Johnson21241572016-07-18 21:22:24 +000076#include "llvm/Transforms/IPO/FunctionImport.h"
Davide Italiano66228c42016-05-03 19:39:15 +000077#include "llvm/Transforms/IPO/GlobalDCE.h"
Justin Bogner1a075012016-04-26 00:28:01 +000078#include "llvm/Transforms/IPO/GlobalOpt.h"
Davide Italiano2ae76dd2016-11-21 00:28:23 +000079#include "llvm/Transforms/IPO/GlobalSplit.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000080#include "llvm/Transforms/IPO/HotColdSplitting.h"
Chandler Carruth3a040e62015-12-27 08:41:34 +000081#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
Chandler Carruth1d963112016-12-20 03:15:32 +000082#include "llvm/Transforms/IPO/Inliner.h"
Justin Bogner4563a062016-04-26 20:15:52 +000083#include "llvm/Transforms/IPO/Internalize.h"
Davide Italianoe8ae0b52016-07-11 18:10:06 +000084#include "llvm/Transforms/IPO/LowerTypeTests.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000085#include "llvm/Transforms/IPO/PartialInlining.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000086#include "llvm/Transforms/IPO/SCCP.h"
David Blaikie301627f2018-03-22 22:42:44 +000087#include "llvm/Transforms/IPO/SampleProfile.h"
Justin Bogner21e15372015-10-30 23:28:12 +000088#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
Easwaran Ramanbdf20262018-01-09 19:39:35 +000089#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
Davide Italianod737dd22016-06-14 21:44:19 +000090#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +000091#include "llvm/Transforms/InstCombine/InstCombine.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +000092#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000093#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruth00a301d2017-11-14 01:30:04 +000094#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
Vitaly Buka4493fe12018-11-26 21:57:47 +000095#include "llvm/Transforms/Instrumentation/CGProfile.h"
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +000096#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +000097#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Leonard Chan0cdd3b12019-05-14 21:17:21 +000098#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
Manman Ren18295122019-02-28 20:13:38 +000099#include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000100#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffeb39a97c2019-01-03 13:42:44 +0000101#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
David Blaikie4fe1fe12018-03-23 22:11:06 +0000102#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
Philip Reamesf47a3132019-07-09 18:49:29 +0000103#include "llvm/Transforms/Instrumentation/PoisonChecking.h"
Leonard Chan007f6742019-07-25 20:53:15 +0000104#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +0000105#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Justin Bogner19b67992015-10-30 23:13:18 +0000106#include "llvm/Transforms/Scalar/ADCE.h"
Sean Silvaa4c2d152016-06-15 06:18:01 +0000107#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
Davide Italiano655a1452016-05-25 01:57:04 +0000108#include "llvm/Transforms/Scalar/BDCE.h"
Jun Bum Lim0c990072017-11-03 20:41:16 +0000109#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
Adam Nemet3beef412016-07-18 16:29:17 +0000110#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Sean Silvab025d372016-07-06 23:26:29 +0000111#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
Justin Bogner395c2122016-04-22 19:40:41 +0000112#include "llvm/Transforms/Scalar/DCE.h"
Justin Bogner594e07b2016-05-17 21:38:13 +0000113#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Sanjay Patel6fd43912017-09-09 13:38:18 +0000114#include "llvm/Transforms/Scalar/DivRemPairs.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000115#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Kuperstein83b753d2016-06-24 23:32:02 +0000116#include "llvm/Transforms/Scalar/Float2Int.h"
Easwaran Raman019e0bf2016-06-03 22:54:26 +0000117#include "llvm/Transforms/Scalar/GVN.h"
Davide Italiano89ab89d2016-06-14 00:49:23 +0000118#include "llvm/Transforms/Scalar/GuardWidening.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000119#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
Sanjoy Das4d4339d2016-06-05 18:01:19 +0000120#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +0000121#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Chandler Carruth7c557f82018-06-29 23:36:03 +0000122#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
Sean Silva46590d52016-06-14 00:51:09 +0000123#include "llvm/Transforms/Scalar/JumpThreading.h"
Dehao Chenf400a092016-07-12 22:42:24 +0000124#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000125#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
Teresa Johnson1eca6bc2016-08-13 04:11:27 +0000126#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +0000127#include "llvm/Transforms/Scalar/LoopDeletion.h"
Adam Nemetb2593f72016-07-18 16:29:27 +0000128#include "llvm/Transforms/Scalar/LoopDistribute.h"
Kit Barton3cdf8792019-04-17 18:53:27 +0000129#include "llvm/Transforms/Scalar/LoopFuse.h"
Dehao Chenb9f8e292016-07-12 18:45:51 +0000130#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
Chandler Carruthe6c30fd2018-05-25 01:32:36 +0000131#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +0000132#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000133#include "llvm/Transforms/Scalar/LoopPassManager.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000134#include "llvm/Transforms/Scalar/LoopPredication.h"
Justin Bognerd0d23412016-05-03 22:02:31 +0000135#include "llvm/Transforms/Scalar/LoopRotation.h"
Justin Bognerab6a5132016-05-03 21:47:32 +0000136#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000137#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000138#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
David Green963401d2018-07-01 12:47:30 +0000139#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
Sean Silvae3c18a52016-07-19 23:54:23 +0000140#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
Davide Italiano99223442016-05-13 22:52:35 +0000141#include "llvm/Transforms/Scalar/LowerAtomic.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +0000142#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Michael Kupersteine45d4d92016-07-28 22:08:41 +0000143#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
Max Kazantsevf392bc82019-01-31 09:10:17 +0000144#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
Max Kazantsevb9e65cb2018-12-07 14:39:46 +0000145#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
Sean Silva6347df02016-06-14 02:44:55 +0000146#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Leonard Chanbb147aa2019-07-15 23:18:31 +0000147#include "llvm/Transforms/Scalar/MergeICmps.h"
Leonard Chan007f6742019-07-25 20:53:15 +0000148#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Wei Mi1cf58f82016-07-21 22:28:52 +0000149#include "llvm/Transforms/Scalar/NaryReassociate.h"
Davide Italianoe05e3302016-12-22 16:35:02 +0000150#include "llvm/Transforms/Scalar/NewGVN.h"
Davide Italiano1021c682016-05-25 23:38:53 +0000151#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
Justin Bognerc2bf63d2016-04-26 23:39:29 +0000152#include "llvm/Transforms/Scalar/Reassociate.h"
Fedor Sergeev4b86d792017-12-15 09:32:11 +0000153#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +0000154#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +0000155#include "llvm/Transforms/Scalar/SROA.h"
Mikael Holmenb6f76002018-11-21 14:00:17 +0000156#include "llvm/Transforms/Scalar/Scalarizer.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000157#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruthf49f1a872015-12-27 08:13:45 +0000158#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Justin Bognerb9394902016-04-22 19:54:10 +0000159#include "llvm/Transforms/Scalar/Sink.h"
Chandler Carruthc34f7892017-11-28 11:32:31 +0000160#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
Michael Kupersteinc4061862016-08-01 21:48:33 +0000161#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
Sean Silva59fe82f2016-07-06 23:48:41 +0000162#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
Michael Kruse72448522018-12-12 17:32:52 +0000163#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
Xinliang David Li1eaecef2016-06-15 21:51:30 +0000164#include "llvm/Transforms/Utils/AddDiscriminators.h"
Wei Mie04d0ef2016-07-22 18:04:25 +0000165#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Teresa Johnson853b9622019-01-04 19:04:54 +0000166#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Hans Wennborge1ecd612017-11-14 21:09:45 +0000167#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Easwaran Ramane12c4872016-06-09 19:44:46 +0000168#include "llvm/Transforms/Utils/LCSSA.h"
Rong Xu1c0e9b92016-10-18 21:36:27 +0000169#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
Davide Italianocd96cfd2016-07-09 03:03:01 +0000170#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kuperstein31b83992016-08-12 17:28:27 +0000171#include "llvm/Transforms/Utils/LowerInvoke.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000172#include "llvm/Transforms/Utils/Mem2Reg.h"
Mehdi Amini27d23792016-09-16 16:56:30 +0000173#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Michael Kuperstein39feb622016-07-25 20:52:00 +0000174#include "llvm/Transforms/Utils/SymbolRewriter.h"
Markus Lavin4dc4ebd2018-12-07 08:23:37 +0000175#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
Sean Silvadb90d4d2016-07-09 22:56:50 +0000176#include "llvm/Transforms/Vectorize/LoopVectorize.h"
Sean Silva0dacbd82016-07-09 03:11:29 +0000177#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
Davide Italianocccf4f02016-06-14 03:22:22 +0000178
Chandler Carruth66445382014-01-11 08:16:35 +0000179using namespace llvm;
180
Chandler Carruth719ffe12017-02-12 05:38:04 +0000181static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
182 cl::ReallyHidden, cl::init(4));
Xinliang David Li126157c2017-05-22 16:41:57 +0000183static cl::opt<bool>
184 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
185 cl::Hidden, cl::ZeroOrMore,
186 cl::desc("Run Partial inlinining pass"));
Chandler Carruth719ffe12017-02-12 05:38:04 +0000187
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000188static cl::opt<bool>
Davide Italiano8e7d11a2017-05-22 23:47:11 +0000189 RunNewGVN("enable-npm-newgvn", cl::init(false),
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000190 cl::Hidden, cl::ZeroOrMore,
191 cl::desc("Run NewGVN instead of GVN"));
192
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000193static cl::opt<bool> EnableGVNHoist(
Eric Christopherdcf1d972018-10-01 18:57:08 +0000194 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
195 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
Chandler Carruthc246a4c2017-04-27 00:28:03 +0000196
Davide Italianobe1b6a92017-06-03 23:18:29 +0000197static cl::opt<bool> EnableGVNSink(
198 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
199 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
200
David Green963401d2018-07-01 12:47:30 +0000201static cl::opt<bool> EnableUnrollAndJam(
202 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
203 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
204
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000205static cl::opt<bool> EnableSyntheticCounts(
206 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
207 cl::desc("Run synthetic function entry count generation "
208 "pass"));
209
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000210static Regex DefaultAliasRegex(
211 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000212
Eric Christophereff3b6f2019-04-18 06:17:40 +0000213// This option is used in simplifying testing SampleFDO optimizations for
214// profile loading.
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000215static cl::opt<bool>
216 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
217 cl::desc("Enable control height reduction optimization (CHR)"));
218
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000219PipelineTuningOptions::PipelineTuningOptions() {
220 LoopInterleaving = EnableLoopInterleaving;
221 LoopVectorization = EnableLoopVectorization;
Alina Sbirlea458c7332019-05-08 17:58:35 +0000222 SLPVectorization = RunSLPVectorization;
Alina Sbirleae4b27862019-05-23 19:35:40 +0000223 LoopUnrolling = true;
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000224 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
Alina Sbirlea43709f72019-04-19 17:46:50 +0000225 LicmMssaOptCap = SetLicmMssaOptCap;
226 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000227}
228
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000229extern cl::opt<bool> EnableHotColdSplit;
Manman Ren18295122019-02-28 20:13:38 +0000230extern cl::opt<bool> EnableOrderFileInstrumentation;
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000231
Wei Mi3bcccdf2019-01-17 20:48:34 +0000232extern cl::opt<bool> FlattenedProfileUsed;
233
Chandler Carruthe3f50642016-12-22 06:59:15 +0000234static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
235 switch (Level) {
236 case PassBuilder::O0:
237 case PassBuilder::O1:
238 case PassBuilder::O2:
239 case PassBuilder::O3:
240 return false;
241
242 case PassBuilder::Os:
243 case PassBuilder::Oz:
244 return true;
245 }
246 llvm_unreachable("Invalid optimization level!");
247}
248
Chandler Carruth66445382014-01-11 08:16:35 +0000249namespace {
250
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000251/// No-op module pass which does nothing.
Chandler Carruth66445382014-01-11 08:16:35 +0000252struct NoOpModulePass {
Sean Silvafd03ac62016-08-09 00:28:38 +0000253 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000254 return PreservedAnalyses::all();
255 }
Chandler Carrutha13f27c2014-01-11 11:52:05 +0000256 static StringRef name() { return "NoOpModulePass"; }
Chandler Carruth66445382014-01-11 08:16:35 +0000257};
258
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000259/// No-op module analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000260class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
261 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000262 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000263
264public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000265 struct Result {};
Sean Silvafd03ac62016-08-09 00:28:38 +0000266 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000267 static StringRef name() { return "NoOpModuleAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000268};
269
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000270/// No-op CGSCC pass which does nothing.
Chandler Carruth572e3402014-04-21 11:12:00 +0000271struct NoOpCGSCCPass {
Chandler Carruth88823462016-08-24 09:37:14 +0000272 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
273 LazyCallGraph &, CGSCCUpdateResult &UR) {
Chandler Carruth572e3402014-04-21 11:12:00 +0000274 return PreservedAnalyses::all();
275 }
276 static StringRef name() { return "NoOpCGSCCPass"; }
277};
278
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000279/// No-op CGSCC analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000280class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
281 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000282 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000283
284public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000285 struct Result {};
Chandler Carruth88823462016-08-24 09:37:14 +0000286 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000287 return Result();
288 }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000289 static StringRef name() { return "NoOpCGSCCAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000290};
291
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000292/// No-op function pass which does nothing.
Chandler Carruthd8330982014-01-12 09:34:22 +0000293struct NoOpFunctionPass {
Sean Silva36e0d012016-08-09 00:28:15 +0000294 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000295 return PreservedAnalyses::all();
296 }
Chandler Carruthd8330982014-01-12 09:34:22 +0000297 static StringRef name() { return "NoOpFunctionPass"; }
298};
299
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000300/// No-op function analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000301class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
302 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000303 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000304
305public:
Chandler Carruth0b576b32015-01-06 02:50:06 +0000306 struct Result {};
Sean Silva36e0d012016-08-09 00:28:15 +0000307 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000308 static StringRef name() { return "NoOpFunctionAnalysis"; }
Chandler Carruth0b576b32015-01-06 02:50:06 +0000309};
310
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000311/// No-op loop pass which does nothing.
Justin Bognereecc3c82016-02-25 07:23:08 +0000312struct NoOpLoopPass {
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000313 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
314 LoopStandardAnalysisResults &, LPMUpdater &) {
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000315 return PreservedAnalyses::all();
316 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000317 static StringRef name() { return "NoOpLoopPass"; }
318};
319
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000320/// No-op loop analysis.
Chandler Carruth30a07302016-03-11 10:33:22 +0000321class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
322 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000323 static AnalysisKey Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000324
325public:
Justin Bognereecc3c82016-02-25 07:23:08 +0000326 struct Result {};
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000327 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
328 return Result();
329 }
Justin Bognereecc3c82016-02-25 07:23:08 +0000330 static StringRef name() { return "NoOpLoopAnalysis"; }
Justin Bognereecc3c82016-02-25 07:23:08 +0000331};
332
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000333AnalysisKey NoOpModuleAnalysis::Key;
334AnalysisKey NoOpCGSCCAnalysis::Key;
335AnalysisKey NoOpFunctionAnalysis::Key;
336AnalysisKey NoOpLoopAnalysis::Key;
Chandler Carruthb4faf132016-03-11 10:22:49 +0000337
Chandler Carruth66445382014-01-11 08:16:35 +0000338} // End anonymous namespace.
339
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000340void PassBuilder::invokePeepholeEPCallbacks(
341 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
342 for (auto &C : PeepholeEPCallbacks)
343 C(FPM, Level);
344}
345
Chandler Carruth1ff77242015-03-07 09:02:36 +0000346void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000347#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000348 MAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000349#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000350
351 for (auto &C : ModuleAnalysisRegistrationCallbacks)
352 C(MAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000353}
354
Chandler Carruth1ff77242015-03-07 09:02:36 +0000355void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000356#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000357 CGAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000358#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000359
360 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
361 C(CGAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000362}
363
Chandler Carruth1ff77242015-03-07 09:02:36 +0000364void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000365#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruthedf59962016-02-18 09:45:17 +0000366 FAM.registerPass([&] { return CREATE_PASS; });
Chandler Carruthb70f6732015-01-06 02:21:37 +0000367#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000368
369 for (auto &C : FunctionAnalysisRegistrationCallbacks)
370 C(FAM);
Chandler Carruthb70f6732015-01-06 02:21:37 +0000371}
372
Justin Bognereecc3c82016-02-25 07:23:08 +0000373void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
Chandler Carruth74a8a222016-06-17 07:15:29 +0000374#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
Justin Bognereecc3c82016-02-25 07:23:08 +0000375 LAM.registerPass([&] { return CREATE_PASS; });
376#include "PassRegistry.def"
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000377
378 for (auto &C : LoopAnalysisRegistrationCallbacks)
379 C(LAM);
Justin Bognereecc3c82016-02-25 07:23:08 +0000380}
381
Chandler Carruthe3f50642016-12-22 06:59:15 +0000382FunctionPassManager
383PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000384 ThinLTOPhase Phase,
385 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000386 assert(Level != O0 && "Must request optimizations!");
387 FunctionPassManager FPM(DebugLogging);
388
389 // Form SSA out of local memory accesses after breaking apart aggregates into
390 // scalars.
391 FPM.addPass(SROA());
392
393 // Catch trivial redundancies
Eric Christopherdfebd842019-04-19 22:18:53 +0000394 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000395
Davide Italianoc3688312017-06-01 23:08:14 +0000396 // Hoisting of scalars and load expressions.
397 if (EnableGVNHoist)
398 FPM.addPass(GVNHoistPass());
399
Davide Italianobe1b6a92017-06-03 23:18:29 +0000400 // Global value numbering based sinking.
401 if (EnableGVNSink) {
402 FPM.addPass(GVNSinkPass());
403 FPM.addPass(SimplifyCFGPass());
404 }
405
Chandler Carruthe3f50642016-12-22 06:59:15 +0000406 // Speculative execution if the target has divergent branches; otherwise nop.
407 FPM.addPass(SpeculativeExecutionPass());
408
409 // Optimize based on known information about branches, and cleanup afterward.
410 FPM.addPass(JumpThreadingPass());
411 FPM.addPass(CorrelatedValuePropagationPass());
412 FPM.addPass(SimplifyCFGPass());
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000413 if (Level == O3)
414 FPM.addPass(AggressiveInstCombinePass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000415 FPM.addPass(InstCombinePass());
416
417 if (!isOptimizingForSize(Level))
418 FPM.addPass(LibCallsShrinkWrapPass());
419
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000420 invokePeepholeEPCallbacks(FPM, Level);
421
Rong Xue1f42452017-10-23 22:21:29 +0000422 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
423 // using the size value profile. Don't perform this when optimizing for size.
Rong Xudb29a3a2019-03-04 20:21:27 +0000424 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
Rong Xue1f42452017-10-23 22:21:29 +0000425 !isOptimizingForSize(Level))
426 FPM.addPass(PGOMemOPSizeOpt());
427
Chandler Carruthe3f50642016-12-22 06:59:15 +0000428 FPM.addPass(TailCallElimPass());
429 FPM.addPass(SimplifyCFGPass());
430
431 // Form canonically associated expression trees, and simplify the trees using
432 // basic mathematical properties. For example, this will form (nearly)
433 // minimal multiplication trees.
434 FPM.addPass(ReassociatePass());
435
436 // Add the primary loop simplification pipeline.
437 // FIXME: Currently this is split into two loop pass pipelines because we run
Chandler Carruth71fd2702018-05-30 02:46:45 +0000438 // some function passes in between them. These can and should be removed
439 // and/or replaced by scheduling the loop pass equivalents in the correct
440 // positions. But those equivalent passes aren't powerful enough yet.
441 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
442 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
443 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
444 // `LoopInstSimplify`.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000445 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
446
Chandler Carruth71fd2702018-05-30 02:46:45 +0000447 // Simplify the loop body. We do this initially to clean up after other loop
448 // passes run, either when iterating on a loop or on inner loops with
449 // implications on the outer loop.
450 LPM1.addPass(LoopInstSimplifyPass());
451 LPM1.addPass(LoopSimplifyCFGPass());
452
Chandler Carruthe3f50642016-12-22 06:59:15 +0000453 // Rotate Loop - disable header duplication at -Oz
454 LPM1.addPass(LoopRotatePass(Level != Oz));
Alina Sbirlea43709f72019-04-19 17:46:50 +0000455 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
Chandler Carruth86248d52017-05-26 01:24:11 +0000456 LPM1.addPass(SimpleLoopUnswitchPass());
Chandler Carruth79b733b2017-01-26 23:21:17 +0000457 LPM2.addPass(IndVarSimplifyPass());
458 LPM2.addPass(LoopIdiomRecognizePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000459
460 for (auto &C : LateLoopOptimizationsEPCallbacks)
461 C(LPM2, Level);
462
Chandler Carruth79b733b2017-01-26 23:21:17 +0000463 LPM2.addPass(LoopDeletionPass());
Dehao Chen95f00302017-07-30 04:55:39 +0000464 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000465 // because it changes IR to makes profile annotation in back compile
466 // inaccurate.
Alina Sbirleae4b27862019-05-23 19:35:40 +0000467 if ((Phase != ThinLTOPhase::PreLink || !PGOOpt ||
468 PGOOpt->Action != PGOOptions::SampleUse) &&
469 PTO.LoopUnrolling)
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000470 LPM2.addPass(
471 LoopFullUnrollPass(Level, false, PTO.ForgetAllSCEVInLoopUnroll));
Chandler Carruth79b733b2017-01-26 23:21:17 +0000472
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000473 for (auto &C : LoopOptimizerEndEPCallbacks)
474 C(LPM2, Level);
475
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000476 // We provide the opt remark emitter pass for LICM to use. We only need to do
477 // this once as it is immutable.
478 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000479 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000480 FPM.addPass(SimplifyCFGPass());
481 FPM.addPass(InstCombinePass());
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000482 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000483
484 // Eliminate redundancies.
485 if (Level != O1) {
486 // These passes add substantial compile time so skip them at O1.
487 FPM.addPass(MergedLoadStoreMotionPass());
Davide Italiano8a09b8e2017-05-22 23:41:40 +0000488 if (RunNewGVN)
489 FPM.addPass(NewGVNPass());
490 else
491 FPM.addPass(GVN());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000492 }
493
494 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
495 FPM.addPass(MemCpyOptPass());
496
497 // Sparse conditional constant propagation.
498 // FIXME: It isn't clear why we do this *after* loop passes rather than
499 // before...
500 FPM.addPass(SCCPPass());
501
502 // Delete dead bit computations (instcombine runs after to fold away the dead
503 // computations, and then ADCE will run later to exploit any new DCE
504 // opportunities that creates).
505 FPM.addPass(BDCEPass());
506
507 // Run instcombine after redundancy and dead bit elimination to exploit
508 // opportunities opened up by them.
509 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000510 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000511
512 // Re-consider control flow based optimizations after redundancy elimination,
513 // redo DCE, etc.
514 FPM.addPass(JumpThreadingPass());
515 FPM.addPass(CorrelatedValuePropagationPass());
516 FPM.addPass(DSEPass());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000517 FPM.addPass(createFunctionToLoopPassAdaptor(
518 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
519 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000520
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000521 for (auto &C : ScalarOptimizerLateEPCallbacks)
522 C(FPM, Level);
523
Chandler Carruthe3f50642016-12-22 06:59:15 +0000524 // Finally, do an expensive DCE pass to catch all the dead code exposed by
525 // the simplifications and basic cleanup after all the simplifications.
526 FPM.addPass(ADCEPass());
527 FPM.addPass(SimplifyCFGPass());
528 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000529 invokePeepholeEPCallbacks(FPM, Level);
Chandler Carruthe3f50642016-12-22 06:59:15 +0000530
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000531 if (EnableCHR && Level == O3 && PGOOpt &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000532 (PGOOpt->Action == PGOOptions::IRUse ||
533 PGOOpt->Action == PGOOptions::SampleUse))
Hiroshi Yamauchi9775a622018-09-04 17:19:13 +0000534 FPM.addPass(ControlHeightReductionPass());
535
Chandler Carruthe3f50642016-12-22 06:59:15 +0000536 return FPM;
537}
538
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000539void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
540 PassBuilder::OptimizationLevel Level,
Rong Xudb29a3a2019-03-04 20:21:27 +0000541 bool RunProfileGen, bool IsCS,
542 std::string ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000543 std::string ProfileRemappingFile) {
Rong Xuca161fa2019-08-01 22:36:34 +0000544 assert(Level != O0 && "Not expecting O0 here!");
Davide Italiano513dfaa2017-02-13 15:26:22 +0000545 // Generally running simplification passes and the inliner with an high
546 // threshold results in smaller executables, but there may be cases where
547 // the size grows, so let's be conservative here and skip this simplification
Rong Xudb29a3a2019-03-04 20:21:27 +0000548 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
549 // IsCS is true).
550 if (!isOptimizingForSize(Level) && !IsCS) {
Davide Italiano513dfaa2017-02-13 15:26:22 +0000551 InlineParams IP;
552
553 // In the old pass manager, this is a cl::opt. Should still this be one?
554 IP.DefaultThreshold = 75;
555
556 // FIXME: The hint threshold has the same value used by the regular inliner.
557 // This should probably be lowered after performance testing.
558 // FIXME: this comment is cargo culted from the old pass manager, revisit).
559 IP.HintThreshold = 325;
560
561 CGSCCPassManager CGPipeline(DebugLogging);
562
563 CGPipeline.addPass(InlinerPass(IP));
564
565 FunctionPassManager FPM;
566 FPM.addPass(SROA());
567 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
568 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
569 FPM.addPass(InstCombinePass()); // Combine silly sequences.
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000570 invokePeepholeEPCallbacks(FPM, Level);
Davide Italiano513dfaa2017-02-13 15:26:22 +0000571
Davide Italiano513dfaa2017-02-13 15:26:22 +0000572 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
573
574 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
Rong Xuca161fa2019-08-01 22:36:34 +0000575
576 // Delete anything that is now dead to make sure that we don't instrument
577 // dead code. Instrumentation can end up keeping dead code around and
578 // dramatically increase code size.
579 MPM.addPass(GlobalDCEPass());
Davide Italiano513dfaa2017-02-13 15:26:22 +0000580 }
581
Rong Xuca161fa2019-08-01 22:36:34 +0000582 if (!RunProfileGen) {
583 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
Rong Xudb29a3a2019-03-04 20:21:27 +0000584 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000585 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
586 // RequireAnalysisPass for PSI before subsequent non-module passes.
587 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Rong Xuca161fa2019-08-01 22:36:34 +0000588 return;
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000589 }
Rong Xuca161fa2019-08-01 22:36:34 +0000590
591 // Perform PGO instrumentation.
592 MPM.addPass(PGOInstrumentationGen(IsCS));
593
594 FunctionPassManager FPM;
595 FPM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
596 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
597
598 // Add the profile lowering pass.
599 InstrProfOptions Options;
600 if (!ProfileFile.empty())
601 Options.InstrProfileOutput = ProfileFile;
602 // Do counter promotion at Level greater than O0.
603 Options.DoCounterPromotion = true;
604 Options.UseBFIInPromotion = IsCS;
605 MPM.addPass(InstrProfiling(Options, IsCS));
606}
607
608void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM,
609 bool DebugLogging, bool RunProfileGen,
610 bool IsCS, std::string ProfileFile,
611 std::string ProfileRemappingFile) {
612 if (!RunProfileGen) {
613 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
614 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
615 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
616 // RequireAnalysisPass for PSI before subsequent non-module passes.
617 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
618 return;
619 }
620
621 // Perform PGO instrumentation.
622 MPM.addPass(PGOInstrumentationGen(IsCS));
623 // Add the profile lowering pass.
624 InstrProfOptions Options;
625 if (!ProfileFile.empty())
626 Options.InstrProfileOutput = ProfileFile;
627 // Do not do counter promotion at O0.
628 Options.DoCounterPromotion = false;
629 Options.UseBFIInPromotion = IsCS;
630 MPM.addPass(InstrProfiling(Options, IsCS));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000631}
632
Easwaran Raman8249fac2017-06-28 13:33:49 +0000633static InlineParams
634getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
635 auto O3 = PassBuilder::O3;
636 unsigned OptLevel = Level > O3 ? 2 : Level;
637 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
638 return getInlineParams(OptLevel, SizeLevel);
639}
640
Chandler Carruthe3f50642016-12-22 06:59:15 +0000641ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000642PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
Dehao Chen95f00302017-07-30 04:55:39 +0000643 ThinLTOPhase Phase,
644 bool DebugLogging) {
Chandler Carruthe3f50642016-12-22 06:59:15 +0000645 ModulePassManager MPM(DebugLogging);
646
Rong Xudb29a3a2019-03-04 20:21:27 +0000647 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000648
649 // In ThinLTO mode, when flattened profile is used, all the available
650 // profile information will be annotated in PreLink phase so there is
651 // no need to load the profile again in PostLink.
652 bool LoadSampleProfile =
653 HasSampleProfile &&
654 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
655
656 // During the ThinLTO backend phase we perform early indirect call promotion
657 // here, before globalopt. Otherwise imported available_externally functions
658 // look unreferenced and are removed. If we are going to load the sample
659 // profile then defer until later.
660 // TODO: See if we can move later and consolidate with the location where
661 // we perform ICP when we are loading a sample profile.
662 // TODO: We pass HasSampleProfile (whether there was a sample profile file
663 // passed to the compile) to the SamplePGO flag of ICP. This is used to
664 // determine whether the new direct calls are annotated with prof metadata.
665 // Ideally this should be determined from whether the IR is annotated with
666 // sample profile, and not whether the a sample profile was provided on the
667 // command line. E.g. for flattened profiles where we will not be reloading
668 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
669 // provide the sample profile file.
670 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
671 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
672
Chandler Carruthe3f50642016-12-22 06:59:15 +0000673 // Do basic inference of function attributes from known properties of system
674 // libraries and other oracles.
675 MPM.addPass(InferFunctionAttrsPass());
676
677 // Create an early function pass manager to cleanup the output of the
678 // frontend.
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000679 FunctionPassManager EarlyFPM(DebugLogging);
680 EarlyFPM.addPass(SimplifyCFGPass());
681 EarlyFPM.addPass(SROA());
682 EarlyFPM.addPass(EarlyCSEPass());
683 EarlyFPM.addPass(LowerExpectIntrinsicPass());
Jun Bum Lim0c990072017-11-03 20:41:16 +0000684 if (Level == O3)
685 EarlyFPM.addPass(CallSiteSplittingPass());
686
Dehao Chen08f88312017-08-07 20:23:20 +0000687 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
688 // to convert bitcast to direct calls so that they can be inlined during the
689 // profile annotation prepration step.
690 // More details about SamplePGO design can be found in:
691 // https://research.google.com/pubs/pub45290.html
692 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000693 if (LoadSampleProfile)
Dehao Chen08f88312017-08-07 20:23:20 +0000694 EarlyFPM.addPass(InstCombinePass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +0000695 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000696
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000697 if (LoadSampleProfile) {
Dehao Chen08f88312017-08-07 20:23:20 +0000698 // Annotate sample profile right after early FPM to ensure freshness of
699 // the debug info.
Rong Xudb29a3a2019-03-04 20:21:27 +0000700 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000701 PGOOpt->ProfileRemappingFile,
702 Phase == ThinLTOPhase::PreLink));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +0000703 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
704 // RequireAnalysisPass for PSI before subsequent non-module passes.
705 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Dehao Chen08f88312017-08-07 20:23:20 +0000706 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
707 // for the profile annotation to be accurate in the ThinLTO backend.
708 if (Phase != ThinLTOPhase::PreLink)
709 // We perform early indirect call promotion here, before globalopt.
710 // This is important for the ThinLTO backend phase because otherwise
711 // imported available_externally functions look unreferenced and are
712 // removed.
713 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
Teresa Johnsonb0bf5302019-02-05 04:09:19 +0000714 true /* SamplePGO */));
Dehao Chen08f88312017-08-07 20:23:20 +0000715 }
716
Malcolm Parsons21e545d2018-01-24 10:33:39 +0000717 // Interprocedural constant propagation now that basic cleanup has occurred
Chandler Carruthe3f50642016-12-22 06:59:15 +0000718 // and prior to optimizing globals.
719 // FIXME: This position in the pipeline hasn't been carefully considered in
720 // years, it should be re-analyzed.
721 MPM.addPass(IPSCCPPass());
722
Matthew Simpsoncb585582017-10-25 13:40:08 +0000723 // Attach metadata to indirect call sites indicating the set of functions
724 // they may target at run-time. This should follow IPSCCP.
725 MPM.addPass(CalledValuePropagationPass());
726
Chandler Carruthe3f50642016-12-22 06:59:15 +0000727 // Optimize globals to try and fold them into constants.
728 MPM.addPass(GlobalOptPass());
729
730 // Promote any localized globals to SSA registers.
731 // FIXME: Should this instead by a run of SROA?
732 // FIXME: We should probably run instcombine and simplify-cfg afterward to
733 // delete control flows that are dead once globals have been folded to
734 // constants.
735 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
736
737 // Remove any dead arguments exposed by cleanups and constand folding
738 // globals.
739 MPM.addPass(DeadArgumentEliminationPass());
740
741 // Create a small function pass pipeline to cleanup after all the global
742 // optimizations.
743 FunctionPassManager GlobalCleanupPM(DebugLogging);
744 GlobalCleanupPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000745 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
746
Chandler Carruthe3f50642016-12-22 06:59:15 +0000747 GlobalCleanupPM.addPass(SimplifyCFGPass());
748 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
749
Dehao Chen89d32262017-08-02 01:28:31 +0000750 // Add all the requested passes for instrumentation PGO, if requested.
751 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
Rong Xudb29a3a2019-03-04 20:21:27 +0000752 (PGOOpt->Action == PGOOptions::IRInstr ||
753 PGOOpt->Action == PGOOptions::IRUse)) {
754 addPGOInstrPasses(MPM, DebugLogging, Level,
755 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
756 /* IsCS */ false, PGOOpt->ProfileFile,
Richard Smith6c676622018-10-10 23:13:47 +0000757 PGOOpt->ProfileRemappingFile);
Dehao Chen89d32262017-08-02 01:28:31 +0000758 MPM.addPass(PGOIndirectCallPromotion(false, false));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000759 }
Rong Xudb29a3a2019-03-04 20:21:27 +0000760 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
761 PGOOpt->CSAction == PGOOptions::CSIRInstr)
762 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
Davide Italiano513dfaa2017-02-13 15:26:22 +0000763
Easwaran Ramanbdf20262018-01-09 19:39:35 +0000764 // Synthesize function entry counts for non-PGO compilation.
765 if (EnableSyntheticCounts && !PGOOpt)
766 MPM.addPass(SyntheticCountsPropagation());
767
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000768 // Require the GlobalsAA analysis for the module so we can query it within
769 // the CGSCC pipeline.
770 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000771
Easwaran Raman5e6f9bd2017-05-04 16:58:45 +0000772 // Require the ProfileSummaryAnalysis for the module so we can query it within
773 // the inliner pass.
774 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
775
Chandler Carruthe3f50642016-12-22 06:59:15 +0000776 // Now begin the main postorder CGSCC pipeline.
777 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
778 // manager and trying to emulate its precise behavior. Much of this doesn't
779 // make a lot of sense and we should revisit the core CGSCC structure.
780 CGSCCPassManager MainCGPipeline(DebugLogging);
781
782 // Note: historically, the PruneEH pass was run first to deduce nounwind and
783 // generally clean up exception handling overhead. It isn't clear this is
784 // valuable as the inliner doesn't currently care whether it is inlining an
785 // invoke or a call.
786
787 // Run the inliner first. The theory is that we are walking bottom-up and so
788 // the callees have already been fully optimized, and we want to inline them
789 // into the callers so that our optimizations can reflect that.
Dehao Chen95f00302017-07-30 04:55:39 +0000790 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
Dehao Chen3a9861422017-07-07 20:53:10 +0000791 // because it makes profile annotation in the backend inaccurate.
792 InlineParams IP = getInlineParamsFromOptLevel(Level);
Rong Xudb29a3a2019-03-04 20:21:27 +0000793 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
794 PGOOpt->Action == PGOOptions::SampleUse)
Dehao Chen3a9861422017-07-07 20:53:10 +0000795 IP.HotCallSiteThreshold = 0;
796 MainCGPipeline.addPass(InlinerPass(IP));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000797
798 // Now deduce any function attributes based in the current code.
799 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
800
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000801 // When at O3 add argument promotion to the pass pipeline.
802 // FIXME: It isn't at all clear why this should be limited to O3.
803 if (Level == O3)
804 MainCGPipeline.addPass(ArgumentPromotionPass());
805
Chandler Carruthe3f50642016-12-22 06:59:15 +0000806 // Lastly, add the core function simplification pipeline nested inside the
807 // CGSCC walk.
808 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
Dehao Chen95f00302017-07-30 04:55:39 +0000809 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000810
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000811 for (auto &C : CGSCCOptimizerLateEPCallbacks)
812 C(MainCGPipeline, Level);
813
Chandler Carruth719ffe12017-02-12 05:38:04 +0000814 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
815 // to detect when we devirtualize indirect calls and iterate the SCC passes
816 // in that case to try and catch knock-on inlining or function attrs
817 // opportunities. Then we add it to the module pipeline by walking the SCCs
818 // in postorder (or bottom-up).
Chandler Carruthe3f50642016-12-22 06:59:15 +0000819 MPM.addPass(
Chandler Carruth719ffe12017-02-12 05:38:04 +0000820 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
Chandler Carruth19913b22017-08-11 05:47:13 +0000821 std::move(MainCGPipeline), MaxDevirtIterations)));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000822
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000823 return MPM;
824}
825
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000826ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
827 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000828 ModulePassManager MPM(DebugLogging);
829
830 // Optimize globals now that the module is fully simplified.
831 MPM.addPass(GlobalOptPass());
Davide Italianoe0707212017-10-05 18:36:01 +0000832 MPM.addPass(GlobalDCEPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000833
Xinliang David Li126157c2017-05-22 16:41:57 +0000834 // Run partial inlining pass to partially inline functions that have
835 // large bodies.
836 if (RunPartialInlining)
837 MPM.addPass(PartialInlinerPass());
838
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000839 // Remove avail extern fns and globals definitions since we aren't compiling
840 // an object file for later LTO. For LTO we want to preserve these so they
841 // are eligible for inlining at link-time. Note if they are unreferenced they
842 // will be removed by GlobalDCE later, so this only impacts referenced
843 // available externally globals. Eventually they will be suppressed during
844 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
845 // may make globals referenced by available external functions dead and saves
Leonard Chan97dc6222019-06-20 19:44:51 +0000846 // running remaining passes on the eliminated functions. These should be
847 // preserved during prelinking for link-time inlining decisions.
848 if (!LTOPreLink)
849 MPM.addPass(EliminateAvailableExternallyPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000850
Manman Ren18295122019-02-28 20:13:38 +0000851 if (EnableOrderFileInstrumentation)
852 MPM.addPass(InstrOrderFilePass());
853
Chandler Carruthe3f50642016-12-22 06:59:15 +0000854 // Do RPO function attribute inference across the module to forward-propagate
855 // attributes where applicable.
856 // FIXME: Is this really an optimization rather than a canonicalization?
857 MPM.addPass(ReversePostOrderFunctionAttrsPass());
858
Rong Xudb29a3a2019-03-04 20:21:27 +0000859 // Do a post inline PGO instrumentation and use pass. This is a context
860 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
861 // cross-module inline has not been done yet. The context sensitive
862 // instrumentation is after all the inlines are done.
863 if (!LTOPreLink && PGOOpt) {
864 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
865 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
866 /* IsCS */ true, PGOOpt->CSProfileGenFile,
867 PGOOpt->ProfileRemappingFile);
868 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
869 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
870 /* IsCS */ true, PGOOpt->ProfileFile,
871 PGOOpt->ProfileRemappingFile);
872 }
873
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000874 // Re-require GloblasAA here prior to function passes. This is particularly
Chandler Carruthe3f50642016-12-22 06:59:15 +0000875 // useful as the above will have inlined, DCE'ed, and function-attr
876 // propagated everything. We should at this point have a reasonably minimal
877 // and richly annotated call graph. By computing aliasing and mod/ref
878 // information for all local globals here, the late loop passes and notably
879 // the vectorizer will be able to use them to help recognize vectorizable
880 // memory operations.
Chandler Carruthe87fc8c2017-02-12 05:34:04 +0000881 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000882
883 FunctionPassManager OptimizePM(DebugLogging);
884 OptimizePM.addPass(Float2IntPass());
885 // FIXME: We need to run some loop optimizations to re-rotate loops after
886 // simplify-cfg and others undo their rotation.
887
888 // Optimize the loop execution. These passes operate on entire loop nests
889 // rather than on each loop in an inside-out manner, and so they are actually
890 // function passes.
Chandler Carrutha95ff382017-01-27 00:50:21 +0000891
Philip Pfaffe730f2f92017-07-10 10:57:55 +0000892 for (auto &C : VectorizerStartEPCallbacks)
893 C(OptimizePM, Level);
894
Chandler Carrutha95ff382017-01-27 00:50:21 +0000895 // First rotate loops that may have been un-rotated by prior passes.
Fedor Sergeev02e7f022017-12-29 08:16:06 +0000896 OptimizePM.addPass(
897 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000898
899 // Distribute loops to allow partial vectorization. I.e. isolate dependences
900 // into separate loop that would otherwise inhibit vectorization. This is
901 // currently only performed for loops marked with the metadata
902 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000903 OptimizePM.addPass(LoopDistributePass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000904
905 // Now run the core loop vectorizer.
Alina Sbirlea0499a2f2019-04-19 16:11:59 +0000906 OptimizePM.addPass(LoopVectorizePass(
907 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
Chandler Carrutha95ff382017-01-27 00:50:21 +0000908
Chandler Carruthbaabda92017-01-27 01:32:26 +0000909 // Eliminate loads by forwarding stores from the previous iteration to loads
910 // of the current iteration.
911 OptimizePM.addPass(LoopLoadEliminationPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000912
913 // Cleanup after the loop optimization passes.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000914 OptimizePM.addPass(InstCombinePass());
915
Chandler Carrutha95ff382017-01-27 00:50:21 +0000916 // Now that we've formed fast to execute loop structures, we do further
917 // optimizations. These are run afterward as they might block doing complex
918 // analyses and transforms such as what are needed for loop vectorization.
919
Sanjay Patel0ab0c1a2017-12-14 22:05:20 +0000920 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
921 // GVN, loop transforms, and others have already run, so it's now better to
922 // convert to more optimized IR using more aggressive simplify CFG options.
923 // The extra sinking transform can create larger basic blocks, so do this
924 // before SLP vectorization.
925 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
926 forwardSwitchCondToPhi(true).
927 convertSwitchToLookupTable(true).
928 needCanonicalLoops(false).
929 sinkCommonInsts(true)));
930
Chandler Carruthe3f50642016-12-22 06:59:15 +0000931 // Optimize parallel scalar instruction chains into SIMD instructions.
Alina Sbirlea458c7332019-05-08 17:58:35 +0000932 if (PTO.SLPVectorization)
933 OptimizePM.addPass(SLPVectorizerPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +0000934
Chandler Carruthe3f50642016-12-22 06:59:15 +0000935 OptimizePM.addPass(InstCombinePass());
936
937 // Unroll small loops to hide loop backedge latency and saturate any parallel
Chandler Carrutha95ff382017-01-27 00:50:21 +0000938 // execution resources of an out-of-order processor. We also then need to
939 // clean up redundancies and loop invariant code.
940 // FIXME: It would be really good to use a loop-integrated instruction
941 // combiner for cleanup here so that the unrolling and LICM can be pipelined
942 // across the loop nests.
David Green963401d2018-07-01 12:47:30 +0000943 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
944 if (EnableUnrollAndJam) {
945 OptimizePM.addPass(
946 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
947 }
Alina Sbirleae4b27862019-05-23 19:35:40 +0000948 if (PTO.LoopUnrolling)
Alina Sbirlead82ddfa2019-05-23 21:52:59 +0000949 OptimizePM.addPass(LoopUnrollPass(
950 LoopUnrollOptions(Level, false, PTO.ForgetAllSCEVInLoopUnroll)));
Michael Kruse72448522018-12-12 17:32:52 +0000951 OptimizePM.addPass(WarnMissedTransformationsPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000952 OptimizePM.addPass(InstCombinePass());
Chandler Carruth0ede22e2017-02-09 23:54:57 +0000953 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
Alina Sbirlea43709f72019-04-19 17:46:50 +0000954 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
955 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
956 DebugLogging));
Chandler Carruthe3f50642016-12-22 06:59:15 +0000957
958 // Now that we've vectorized and unrolled loops, we may have more refined
959 // alignment information, try to re-derive it here.
960 OptimizePM.addPass(AlignmentFromAssumptionsPass());
961
Vedant Kumar47a0c9b2019-02-15 18:46:44 +0000962 // Split out cold code. Splitting is done late to avoid hiding context from
963 // other optimizations and inadvertently regressing performance. The tradeoff
964 // is that this has a higher code size cost than splitting early.
965 if (EnableHotColdSplit && !LTOPreLink)
966 MPM.addPass(HotColdSplittingPass());
967
Chandler Carrutha95ff382017-01-27 00:50:21 +0000968 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
969 // canonicalization pass that enables other optimizations. As a result,
970 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
971 // result too early.
972 OptimizePM.addPass(LoopSinkPass());
973
974 // And finally clean up LCSSA form before generating code.
Chandler Carruth7c557f82018-06-29 23:36:03 +0000975 OptimizePM.addPass(InstSimplifyPass());
Chandler Carrutha95ff382017-01-27 00:50:21 +0000976
Sanjay Patel6fd43912017-09-09 13:38:18 +0000977 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
978 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
979 // flattening of blocks.
980 OptimizePM.addPass(DivRemPairsPass());
981
Filipe Cabecinhas92dc3482017-04-26 12:02:41 +0000982 // LoopSink (and other loop passes since the last simplifyCFG) might have
983 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
984 OptimizePM.addPass(SimplifyCFGPass());
985
Chandler Carruthc34f7892017-11-28 11:32:31 +0000986 // Optimize PHIs by speculating around them when profitable. Note that this
987 // pass needs to be run after any PRE or similar pass as it is essentially
Joerg Sonnenbergerec6ee792019-05-16 18:01:57 +0000988 // inserting redundancies into the program. This even includes SimplifyCFG.
Chandler Carruthc34f7892017-11-28 11:32:31 +0000989 OptimizePM.addPass(SpeculateAroundPHIsPass());
990
Philip Pfaffe2d4effb2018-11-12 11:17:07 +0000991 for (auto &C : OptimizerLastEPCallbacks)
992 C(OptimizePM, Level);
993
Chandler Carrutha95ff382017-01-27 00:50:21 +0000994 // Add the core optimizing pipeline.
Chandler Carruthe3f50642016-12-22 06:59:15 +0000995 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
996
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000997 MPM.addPass(CGProfilePass());
998
Chandler Carruthe3f50642016-12-22 06:59:15 +0000999 // Now we need to do some global optimization transforms.
1000 // FIXME: It would seem like these should come first in the optimization
1001 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1002 // ordering here.
1003 MPM.addPass(GlobalDCEPass());
1004 MPM.addPass(ConstantMergePass());
1005
1006 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001007}
1008
Chandler Carruthe3f50642016-12-22 06:59:15 +00001009ModulePassManager
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001010PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001011 bool DebugLogging, bool LTOPreLink) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001012 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1013
1014 ModulePassManager MPM(DebugLogging);
1015
1016 // Force any function attributes we want the rest of the pipeline to observe.
1017 MPM.addPass(ForceFunctionAttrsPass());
1018
David Blaikie0c64f5a2018-01-23 01:25:20 +00001019 // Apply module pipeline start EP callback.
1020 for (auto &C : PipelineStartEPCallbacks)
1021 C(MPM);
1022
Dehao Chen08f88312017-08-07 20:23:20 +00001023 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001024 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1025
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001026 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001027 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
1028 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001029
1030 // Now add the optimization pipeline.
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001031 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001032
1033 return MPM;
1034}
1035
1036ModulePassManager
1037PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1038 bool DebugLogging) {
1039 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1040
1041 ModulePassManager MPM(DebugLogging);
1042
1043 // Force any function attributes we want the rest of the pipeline to observe.
1044 MPM.addPass(ForceFunctionAttrsPass());
1045
Dehao Chen08f88312017-08-07 20:23:20 +00001046 if (PGOOpt && PGOOpt->SamplePGOSupport)
Dehao Chence0842c2017-07-29 04:10:24 +00001047 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1048
David Blaikie0c64f5a2018-01-23 01:25:20 +00001049 // Apply module pipeline start EP callback.
1050 for (auto &C : PipelineStartEPCallbacks)
1051 C(MPM);
1052
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001053 // If we are planning to perform ThinLTO later, we don't bloat the code with
1054 // unrolling/vectorization/... now. Just simplify the module as much as we
1055 // can.
Dehao Chen95f00302017-07-30 04:55:39 +00001056 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1057 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001058
1059 // Run partial inlining pass to partially inline functions that have
1060 // large bodies.
1061 // FIXME: It isn't clear whether this is really the right place to run this
1062 // in ThinLTO. Because there is another canonicalization and simplification
1063 // phase that will run after the thin link, running this here ends up with
1064 // less information than will be available later and it may grow functions in
1065 // ways that aren't beneficial.
1066 if (RunPartialInlining)
1067 MPM.addPass(PartialInlinerPass());
1068
1069 // Reduce the size of the IR as much as possible.
1070 MPM.addPass(GlobalOptPass());
1071
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001072 return MPM;
1073}
1074
Teresa Johnson28023db2018-07-19 14:51:32 +00001075ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1076 OptimizationLevel Level, bool DebugLogging,
1077 const ModuleSummaryIndex *ImportSummary) {
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001078 ModulePassManager MPM(DebugLogging);
1079
Teresa Johnson28023db2018-07-19 14:51:32 +00001080 if (ImportSummary) {
1081 // These passes import type identifier resolutions for whole-program
1082 // devirtualization and CFI. They must run early because other passes may
1083 // disturb the specific instruction patterns that these passes look for,
1084 // creating dependencies on resolutions that may not appear in the summary.
1085 //
1086 // For example, GVN may transform the pattern assume(type.test) appearing in
1087 // two basic blocks into assume(phi(type.test, type.test)), which would
1088 // transform a dependency on a WPD resolution into a dependency on a type
1089 // identifier resolution for CFI.
1090 //
1091 // Also, WPD has access to more precise information than ICP and can
1092 // devirtualize more effectively, so it should operate on the IR first.
Teresa Johnson867bc392019-04-23 18:56:19 +00001093 //
1094 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1095 // metadata and intrinsics.
Teresa Johnson28023db2018-07-19 14:51:32 +00001096 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1097 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1098 }
1099
Teresa Johnson867bc392019-04-23 18:56:19 +00001100 if (Level == O0)
1101 return MPM;
1102
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001103 // Force any function attributes we want the rest of the pipeline to observe.
1104 MPM.addPass(ForceFunctionAttrsPass());
1105
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001106 // Add the core simplification pipeline.
Dehao Chen95f00302017-07-30 04:55:39 +00001107 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1108 DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001109
1110 // Now add the optimization pipeline.
1111 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1112
1113 return MPM;
1114}
1115
1116ModulePassManager
Chandler Carruthe3f50642016-12-22 06:59:15 +00001117PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1118 bool DebugLogging) {
1119 assert(Level != O0 && "Must request optimizations for the default pipeline!");
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001120 // FIXME: We should use a customized pre-link pipeline!
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001121 return buildPerModuleDefaultPipeline(Level, DebugLogging,
Rong Xudb29a3a2019-03-04 20:21:27 +00001122 /* LTOPreLink */true);
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001123}
1124
Teresa Johnson28023db2018-07-19 14:51:32 +00001125ModulePassManager
1126PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1127 ModuleSummaryIndex *ExportSummary) {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001128 ModulePassManager MPM(DebugLogging);
1129
Teresa Johnson867bc392019-04-23 18:56:19 +00001130 if (Level == O0) {
1131 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1132 // metadata and intrinsics.
1133 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1134 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1135 return MPM;
1136 }
1137
Rong Xudb29a3a2019-03-04 20:21:27 +00001138 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
Xin Tong642c8d32018-11-15 18:06:42 +00001139 // Load sample profile before running the LTO optimization pipeline.
Rong Xudb29a3a2019-03-04 20:21:27 +00001140 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
Xin Tong642c8d32018-11-15 18:06:42 +00001141 PGOOpt->ProfileRemappingFile,
1142 false /* ThinLTOPhase::PreLink */));
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00001143 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1144 // RequireAnalysisPass for PSI before subsequent non-module passes.
1145 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
Xin Tong642c8d32018-11-15 18:06:42 +00001146 }
1147
Davide Italiano089a9122017-01-24 00:57:39 +00001148 // Remove unused virtual tables to improve the quality of code generated by
1149 // whole-program devirtualization and bitset lowering.
1150 MPM.addPass(GlobalDCEPass());
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001151
Davide Italiano089a9122017-01-24 00:57:39 +00001152 // Force any function attributes we want the rest of the pipeline to observe.
1153 MPM.addPass(ForceFunctionAttrsPass());
Chandler Carruthe3f50642016-12-22 06:59:15 +00001154
Davide Italiano089a9122017-01-24 00:57:39 +00001155 // Do basic inference of function attributes from known properties of system
1156 // libraries and other oracles.
1157 MPM.addPass(InferFunctionAttrsPass());
1158
1159 if (Level > 1) {
Jun Bum Lim0c990072017-11-03 20:41:16 +00001160 FunctionPassManager EarlyFPM(DebugLogging);
1161 EarlyFPM.addPass(CallSiteSplittingPass());
1162 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1163
Davide Italiano089a9122017-01-24 00:57:39 +00001164 // Indirect call promotion. This should promote all the targets that are
1165 // left by the earlier promotion pass that promotes intra-module targets.
1166 // This two-step promotion is to save the compile time. For LTO, it should
1167 // produce the same result as if we only do promotion here.
Dehao Chen2f31d0d2017-06-29 23:33:05 +00001168 MPM.addPass(PGOIndirectCallPromotion(
Rong Xudb29a3a2019-03-04 20:21:27 +00001169 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
Davide Italiano089a9122017-01-24 00:57:39 +00001170 // Propagate constants at call sites into the functions they call. This
1171 // opens opportunities for globalopt (and inlining) by substituting function
1172 // pointers passed as arguments to direct uses of functions.
1173 MPM.addPass(IPSCCPPass());
Matthew Simpsoncb585582017-10-25 13:40:08 +00001174
1175 // Attach metadata to indirect call sites indicating the set of functions
1176 // they may target at run-time. This should follow IPSCCP.
1177 MPM.addPass(CalledValuePropagationPass());
Davide Italiano089a9122017-01-24 00:57:39 +00001178 }
1179
1180 // Now deduce any function attributes based in the current code.
1181 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1182 PostOrderFunctionAttrsPass()));
1183
1184 // Do RPO function attribute inference across the module to forward-propagate
1185 // attributes where applicable.
1186 // FIXME: Is this really an optimization rather than a canonicalization?
1187 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1188
Eric Christopher721eaef2019-02-26 20:33:22 +00001189 // Use in-range annotations on GEP indices to split globals where beneficial.
Davide Italiano089a9122017-01-24 00:57:39 +00001190 MPM.addPass(GlobalSplitPass());
1191
1192 // Run whole program optimization of virtual call when the list of callees
1193 // is fixed.
Teresa Johnson28023db2018-07-19 14:51:32 +00001194 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001195
1196 // Stop here at -O1.
Teresa Johnson28023db2018-07-19 14:51:32 +00001197 if (Level == 1) {
1198 // The LowerTypeTestsPass needs to run to lower type metadata and the
1199 // type.test intrinsics. The pass does nothing if CFI is disabled.
1200 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001201 return MPM;
Teresa Johnson28023db2018-07-19 14:51:32 +00001202 }
Davide Italiano089a9122017-01-24 00:57:39 +00001203
1204 // Optimize globals to try and fold them into constants.
1205 MPM.addPass(GlobalOptPass());
1206
1207 // Promote any localized globals to SSA registers.
1208 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1209
1210 // Linking modules together can lead to duplicate global constant, only
1211 // keep one copy of each constant.
1212 MPM.addPass(ConstantMergePass());
1213
1214 // Remove unused arguments from functions.
1215 MPM.addPass(DeadArgumentEliminationPass());
1216
1217 // Reduce the code after globalopt and ipsccp. Both can open up significant
1218 // simplification opportunities, and both can propagate functions through
1219 // function pointers. When this happens, we often have to resolve varargs
1220 // calls, etc, so let instcombine do this.
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001221 FunctionPassManager PeepholeFPM(DebugLogging);
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001222 if (Level == O3)
1223 PeepholeFPM.addPass(AggressiveInstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001224 PeepholeFPM.addPass(InstCombinePass());
1225 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1226
1227 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
Davide Italiano089a9122017-01-24 00:57:39 +00001228
1229 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1230 // generally clean up exception handling overhead. It isn't clear this is
1231 // valuable as the inliner doesn't currently care whether it is inlining an
1232 // invoke or a call.
1233 // Run the inliner now.
Easwaran Raman8249fac2017-06-28 13:33:49 +00001234 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1235 InlinerPass(getInlineParamsFromOptLevel(Level))));
Davide Italiano089a9122017-01-24 00:57:39 +00001236
1237 // Optimize globals again after we ran the inliner.
1238 MPM.addPass(GlobalOptPass());
1239
1240 // Garbage collect dead functions.
1241 // FIXME: Add ArgumentPromotion pass after once it's ported.
1242 MPM.addPass(GlobalDCEPass());
1243
1244 FunctionPassManager FPM(DebugLogging);
Davide Italiano089a9122017-01-24 00:57:39 +00001245 // The IPO Passes may leave cruft around. Clean up after them.
Davide Italiano089a9122017-01-24 00:57:39 +00001246 FPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001247 invokePeepholeEPCallbacks(FPM, Level);
1248
Davide Italiano089a9122017-01-24 00:57:39 +00001249 FPM.addPass(JumpThreadingPass());
1250
Rong Xudb29a3a2019-03-04 20:21:27 +00001251 // Do a post inline PGO instrumentation and use pass. This is a context
1252 // sensitive PGO pass.
1253 if (PGOOpt) {
1254 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1255 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1256 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1257 PGOOpt->ProfileRemappingFile);
1258 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1259 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1260 /* IsCS */ true, PGOOpt->ProfileFile,
1261 PGOOpt->ProfileRemappingFile);
1262 }
1263
Davide Italiano089a9122017-01-24 00:57:39 +00001264 // Break up allocas
1265 FPM.addPass(SROA());
1266
Robert Lougherf2158a82019-03-20 19:08:18 +00001267 // LTO provides additional opportunities for tailcall elimination due to
1268 // link-time inlining, and visibility of nocapture attribute.
1269 FPM.addPass(TailCallElimPass());
1270
Davide Italiano089a9122017-01-24 00:57:39 +00001271 // Run a few AA driver optimizations here and now to cleanup the code.
1272 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1273
1274 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1275 PostOrderFunctionAttrsPass()));
1276 // FIXME: here we run IP alias analysis in the legacy PM.
1277
1278 FunctionPassManager MainFPM;
1279
1280 // FIXME: once we fix LoopPass Manager, add LICM here.
1281 // FIXME: once we provide support for enabling MLSM, add it here.
Davide Italiano8a09b8e2017-05-22 23:41:40 +00001282 if (RunNewGVN)
1283 MainFPM.addPass(NewGVNPass());
1284 else
1285 MainFPM.addPass(GVN());
Davide Italiano089a9122017-01-24 00:57:39 +00001286
1287 // Remove dead memcpy()'s.
1288 MainFPM.addPass(MemCpyOptPass());
1289
1290 // Nuke dead stores.
1291 MainFPM.addPass(DSEPass());
1292
1293 // FIXME: at this point, we run a bunch of loop passes:
Eric Christopher86e2f162019-05-03 00:15:23 +00001294 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
Davide Italiano089a9122017-01-24 00:57:39 +00001295 // loopVectorize. Enable them once the remaining issue with LPM
1296 // are sorted out.
1297
1298 MainFPM.addPass(InstCombinePass());
1299 MainFPM.addPass(SimplifyCFGPass());
1300 MainFPM.addPass(SCCPPass());
1301 MainFPM.addPass(InstCombinePass());
1302 MainFPM.addPass(BDCEPass());
1303
1304 // FIXME: We may want to run SLPVectorizer here.
1305 // After vectorization, assume intrinsics may tell us more
1306 // about pointer alignments.
1307#if 0
1308 MainFPM.add(AlignmentFromAssumptionsPass());
1309#endif
1310
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001311 // FIXME: Conditionally run LoadCombine here, after it's ported
1312 // (in case we still have this pass, given its questionable usefulness).
1313
Davide Italiano089a9122017-01-24 00:57:39 +00001314 MainFPM.addPass(InstCombinePass());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001315 invokePeepholeEPCallbacks(MainFPM, Level);
Davide Italiano089a9122017-01-24 00:57:39 +00001316 MainFPM.addPass(JumpThreadingPass());
1317 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1318
1319 // Create a function that performs CFI checks for cross-DSO calls with
1320 // targets in the current module.
1321 MPM.addPass(CrossDSOCFIPass());
1322
1323 // Lower type metadata and the type.test intrinsic. This pass supports
1324 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1325 // to be run at link time if CFI is enabled. This pass does nothing if
1326 // CFI is disabled.
Teresa Johnson28023db2018-07-19 14:51:32 +00001327 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
Davide Italiano089a9122017-01-24 00:57:39 +00001328
Vedant Kumar47a0c9b2019-02-15 18:46:44 +00001329 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1330 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1331 if (EnableHotColdSplit)
1332 MPM.addPass(HotColdSplittingPass());
1333
Davide Italiano089a9122017-01-24 00:57:39 +00001334 // Add late LTO optimization passes.
1335 // Delete basic blocks, which optimization passes may have killed.
1336 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1337
1338 // Drop bodies of available eternally objects to improve GlobalDCE.
1339 MPM.addPass(EliminateAvailableExternallyPass());
1340
1341 // Now that we have optimized the program, discard unreachable functions.
1342 MPM.addPass(GlobalDCEPass());
1343
Eric Christopher86e2f162019-05-03 00:15:23 +00001344 // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
Chandler Carruthe3f50642016-12-22 06:59:15 +00001345 return MPM;
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001346}
1347
Chandler Carruth060ad612016-12-23 20:38:19 +00001348AAManager PassBuilder::buildDefaultAAPipeline() {
1349 AAManager AA;
1350
1351 // The order in which these are registered determines their priority when
1352 // being queried.
1353
1354 // First we register the basic alias analysis that provides the majority of
1355 // per-function local AA logic. This is a stateless, on-demand local set of
1356 // AA techniques.
1357 AA.registerFunctionAnalysis<BasicAA>();
1358
1359 // Next we query fast, specialized alias analyses that wrap IR-embedded
1360 // information about aliasing.
1361 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1362 AA.registerFunctionAnalysis<TypeBasedAA>();
1363
1364 // Add support for querying global aliasing information when available.
Chandler Carruth534d6442016-12-24 05:11:17 +00001365 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1366 // analysis, all that the `AAManager` can do is query for any *cached*
Chandler Carruthe87fc8c2017-02-12 05:34:04 +00001367 // results from `GlobalsAA` through a readonly proxy.
Chandler Carruth060ad612016-12-23 20:38:19 +00001368 AA.registerModuleAnalysis<GlobalsAA>();
Chandler Carruth060ad612016-12-23 20:38:19 +00001369
1370 return AA;
1371}
1372
Chandler Carruth241bf242016-08-03 07:44:48 +00001373static Optional<int> parseRepeatPassName(StringRef Name) {
1374 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1375 return None;
1376 int Count;
1377 if (Name.getAsInteger(0, Count) || Count <= 0)
1378 return None;
1379 return Count;
1380}
1381
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001382static Optional<int> parseDevirtPassName(StringRef Name) {
1383 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1384 return None;
1385 int Count;
1386 if (Name.getAsInteger(0, Count) || Count <= 0)
1387 return None;
1388 return Count;
1389}
1390
Fedor Sergeevb7871402019-01-10 10:01:53 +00001391static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1392 if (!Name.consume_front(PassName))
1393 return false;
1394 // normal pass name w/o parameters == default parameters
1395 if (Name.empty())
1396 return true;
1397 return Name.startswith("<") && Name.endswith(">");
1398}
1399
1400namespace {
1401
1402/// This performs customized parsing of pass name with parameters.
1403///
1404/// We do not need parametrization of passes in textual pipeline very often,
1405/// yet on a rare occasion ability to specify parameters right there can be
1406/// useful.
1407///
1408/// \p Name - parameterized specification of a pass from a textual pipeline
1409/// is a string in a form of :
1410/// PassName '<' parameter-list '>'
1411///
1412/// Parameter list is being parsed by the parser callable argument, \p Parser,
1413/// It takes a string-ref of parameters and returns either StringError or a
1414/// parameter list in a form of a custom parameters type, all wrapped into
1415/// Expected<> template class.
1416///
1417template <typename ParametersParseCallableT>
1418auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1419 StringRef PassName) -> decltype(Parser(StringRef{})) {
1420 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1421
1422 StringRef Params = Name;
1423 if (!Params.consume_front(PassName)) {
1424 assert(false &&
1425 "unable to strip pass name from parametrized pass specification");
1426 }
1427 if (Params.empty())
1428 return ParametersT{};
1429 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1430 assert(false && "invalid format for parametrized pass name");
1431 }
1432
1433 Expected<ParametersT> Result = Parser(Params);
1434 assert((Result || Result.template errorIsA<StringError>()) &&
1435 "Pass parameter parser can only return StringErrors.");
1436 return std::move(Result);
1437}
1438
1439/// Parser of parameters for LoopUnroll pass.
1440Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1441 LoopUnrollOptions UnrollOpts;
1442 while (!Params.empty()) {
1443 StringRef ParamName;
1444 std::tie(ParamName, Params) = Params.split(';');
1445 int OptLevel = StringSwitch<int>(ParamName)
1446 .Case("O0", 0)
1447 .Case("O1", 1)
1448 .Case("O2", 2)
1449 .Case("O3", 3)
1450 .Default(-1);
1451 if (OptLevel >= 0) {
1452 UnrollOpts.setOptLevel(OptLevel);
1453 continue;
1454 }
1455
1456 bool Enable = !ParamName.consume_front("no-");
1457 if (ParamName == "partial") {
1458 UnrollOpts.setPartial(Enable);
1459 } else if (ParamName == "peeling") {
1460 UnrollOpts.setPeeling(Enable);
1461 } else if (ParamName == "runtime") {
1462 UnrollOpts.setRuntime(Enable);
1463 } else if (ParamName == "upperbound") {
1464 UnrollOpts.setUpperBound(Enable);
1465 } else {
1466 return make_error<StringError>(
1467 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1468 inconvertibleErrorCode());
1469 }
1470 }
1471 return UnrollOpts;
1472}
1473
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001474Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1475 MemorySanitizerOptions Result;
1476 while (!Params.empty()) {
1477 StringRef ParamName;
1478 std::tie(ParamName, Params) = Params.split(';');
1479
1480 if (ParamName == "recover") {
1481 Result.Recover = true;
1482 } else if (ParamName == "kernel") {
1483 Result.Kernel = true;
1484 } else if (ParamName.consume_front("track-origins=")) {
1485 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1486 return make_error<StringError>(
1487 formatv("invalid argument to MemorySanitizer pass track-origins "
1488 "parameter: '{0}' ",
1489 ParamName)
1490 .str(),
1491 inconvertibleErrorCode());
1492 } else {
1493 return make_error<StringError>(
1494 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1495 .str(),
1496 inconvertibleErrorCode());
1497 }
1498 }
1499 return Result;
1500}
1501
Serguei Katkovf5432832019-04-15 08:57:53 +00001502/// Parser of parameters for SimplifyCFG pass.
1503Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1504 SimplifyCFGOptions Result;
1505 while (!Params.empty()) {
1506 StringRef ParamName;
1507 std::tie(ParamName, Params) = Params.split(';');
1508
1509 bool Enable = !ParamName.consume_front("no-");
1510 if (ParamName == "forward-switch-cond") {
1511 Result.forwardSwitchCondToPhi(Enable);
1512 } else if (ParamName == "switch-to-lookup") {
1513 Result.convertSwitchToLookupTable(Enable);
1514 } else if (ParamName == "keep-loops") {
1515 Result.needCanonicalLoops(Enable);
1516 } else if (ParamName == "sink-common-insts") {
1517 Result.sinkCommonInsts(Enable);
1518 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1519 APInt BonusInstThreshold;
1520 if (ParamName.getAsInteger(0, BonusInstThreshold))
1521 return make_error<StringError>(
1522 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1523 "parameter: '{0}' ",
1524 ParamName).str(),
1525 inconvertibleErrorCode());
1526 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1527 } else {
1528 return make_error<StringError>(
1529 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1530 inconvertibleErrorCode());
1531 }
1532 }
1533 return Result;
1534}
1535
Serguei Katkovca6c03a2019-04-18 08:46:11 +00001536/// Parser of parameters for LoopVectorize pass.
1537Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1538 LoopVectorizeOptions Opts;
1539 while (!Params.empty()) {
1540 StringRef ParamName;
1541 std::tie(ParamName, Params) = Params.split(';');
1542
1543 bool Enable = !ParamName.consume_front("no-");
1544 if (ParamName == "interleave-forced-only") {
1545 Opts.setInterleaveOnlyWhenForced(Enable);
1546 } else if (ParamName == "vectorize-forced-only") {
1547 Opts.setVectorizeOnlyWhenForced(Enable);
1548 } else {
1549 return make_error<StringError>(
1550 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1551 inconvertibleErrorCode());
1552 }
1553 }
1554 return Opts;
1555}
1556
Serguei Katkov40a3b962019-04-22 10:35:07 +00001557Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
1558 bool Result = false;
1559 while (!Params.empty()) {
1560 StringRef ParamName;
1561 std::tie(ParamName, Params) = Params.split(';');
1562
1563 bool Enable = !ParamName.consume_front("no-");
1564 if (ParamName == "nontrivial") {
1565 Result = Enable;
1566 } else {
1567 return make_error<StringError>(
1568 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
1569 .str(),
1570 inconvertibleErrorCode());
1571 }
1572 }
1573 return Result;
1574}
Fedor Sergeevb7871402019-01-10 10:01:53 +00001575} // namespace
1576
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001577/// Tests whether a pass name starts with a valid prefix for a default pipeline
1578/// alias.
1579static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1580 return Name.startswith("default") || Name.startswith("thinlto") ||
1581 Name.startswith("lto");
1582}
1583
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001584/// Tests whether registered callbacks will accept a given pass name.
1585///
1586/// When parsing a pipeline text, the type of the outermost pipeline may be
1587/// omitted, in which case the type is automatically determined from the first
1588/// pass name in the text. This may be a name that is handled through one of the
1589/// callbacks. We check this through the oridinary parsing callbacks by setting
1590/// up a dummy PassManager in order to not force the client to also handle this
1591/// type of query.
1592template <typename PassManagerT, typename CallbacksT>
1593static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1594 if (!Callbacks.empty()) {
1595 PassManagerT DummyPM;
1596 for (auto &CB : Callbacks)
1597 if (CB(Name, DummyPM, {}))
1598 return true;
1599 }
1600 return false;
1601}
1602
1603template <typename CallbacksT>
1604static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001605 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001606 if (startsWithDefaultPipelineAliasPrefix(Name))
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001607 return DefaultAliasRegex.match(Name);
1608
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001609 // Explicitly handle pass manager names.
1610 if (Name == "module")
1611 return true;
1612 if (Name == "cgscc")
1613 return true;
1614 if (Name == "function")
1615 return true;
1616
Chandler Carruth241bf242016-08-03 07:44:48 +00001617 // Explicitly handle custom-parsed pass names.
1618 if (parseRepeatPassName(Name))
1619 return true;
1620
Chandler Carruth74a8a222016-06-17 07:15:29 +00001621#define MODULE_PASS(NAME, CREATE_PASS) \
1622 if (Name == NAME) \
1623 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001624#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001625 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001626 return true;
1627#include "PassRegistry.def"
1628
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001629 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
Chandler Carruth66445382014-01-11 08:16:35 +00001630}
1631
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001632template <typename CallbacksT>
1633static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001634 // Explicitly handle pass manager names.
1635 if (Name == "cgscc")
1636 return true;
1637 if (Name == "function")
1638 return true;
1639
Chandler Carruth241bf242016-08-03 07:44:48 +00001640 // Explicitly handle custom-parsed pass names.
1641 if (parseRepeatPassName(Name))
1642 return true;
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001643 if (parseDevirtPassName(Name))
1644 return true;
Chandler Carruth241bf242016-08-03 07:44:48 +00001645
Chandler Carruth74a8a222016-06-17 07:15:29 +00001646#define CGSCC_PASS(NAME, CREATE_PASS) \
1647 if (Name == NAME) \
1648 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001649#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001650 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001651 return true;
1652#include "PassRegistry.def"
1653
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001654 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
Chandler Carruth572e3402014-04-21 11:12:00 +00001655}
1656
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001657template <typename CallbacksT>
1658static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001659 // Explicitly handle pass manager names.
1660 if (Name == "function")
1661 return true;
1662 if (Name == "loop")
1663 return true;
1664
Chandler Carruth241bf242016-08-03 07:44:48 +00001665 // Explicitly handle custom-parsed pass names.
1666 if (parseRepeatPassName(Name))
1667 return true;
1668
Chandler Carruth74a8a222016-06-17 07:15:29 +00001669#define FUNCTION_PASS(NAME, CREATE_PASS) \
1670 if (Name == NAME) \
1671 return true;
Fedor Sergeevb7871402019-01-10 10:01:53 +00001672#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1673 if (checkParametrizedPassName(Name, NAME)) \
1674 return true;
Chandler Carruth628503e2015-01-06 02:10:51 +00001675#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001676 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
Chandler Carruth628503e2015-01-06 02:10:51 +00001677 return true;
1678#include "PassRegistry.def"
1679
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001680 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
Chandler Carruthd8330982014-01-12 09:34:22 +00001681}
1682
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001683template <typename CallbacksT>
1684static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001685 // Explicitly handle pass manager names.
1686 if (Name == "loop")
1687 return true;
1688
Chandler Carruth241bf242016-08-03 07:44:48 +00001689 // Explicitly handle custom-parsed pass names.
1690 if (parseRepeatPassName(Name))
1691 return true;
1692
Chandler Carruth74a8a222016-06-17 07:15:29 +00001693#define LOOP_PASS(NAME, CREATE_PASS) \
1694 if (Name == NAME) \
1695 return true;
Serguei Katkov40a3b962019-04-22 10:35:07 +00001696#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1697 if (checkParametrizedPassName(Name, NAME)) \
1698 return true;
Justin Bognereecc3c82016-02-25 07:23:08 +00001699#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1700 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1701 return true;
1702#include "PassRegistry.def"
1703
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001704 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
Justin Bognereecc3c82016-02-25 07:23:08 +00001705}
1706
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001707Optional<std::vector<PassBuilder::PipelineElement>>
1708PassBuilder::parsePipelineText(StringRef Text) {
1709 std::vector<PipelineElement> ResultPipeline;
1710
1711 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1712 &ResultPipeline};
1713 for (;;) {
1714 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1715 size_t Pos = Text.find_first_of(",()");
1716 Pipeline.push_back({Text.substr(0, Pos), {}});
1717
1718 // If we have a single terminating name, we're done.
1719 if (Pos == Text.npos)
1720 break;
1721
1722 char Sep = Text[Pos];
1723 Text = Text.substr(Pos + 1);
1724 if (Sep == ',')
1725 // Just a name ending in a comma, continue.
1726 continue;
1727
1728 if (Sep == '(') {
1729 // Push the inner pipeline onto the stack to continue processing.
1730 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1731 continue;
1732 }
1733
1734 assert(Sep == ')' && "Bogus separator!");
1735 // When handling the close parenthesis, we greedily consume them to avoid
1736 // empty strings in the pipeline.
1737 do {
1738 // If we try to pop the outer pipeline we have unbalanced parentheses.
1739 if (PipelineStack.size() == 1)
1740 return None;
1741
1742 PipelineStack.pop_back();
1743 } while (Text.consume_front(")"));
1744
1745 // Check if we've finished parsing.
1746 if (Text.empty())
1747 break;
1748
1749 // Otherwise, the end of an inner pipeline always has to be followed by
1750 // a comma, and then we can continue.
1751 if (!Text.consume_front(","))
1752 return None;
1753 }
1754
1755 if (PipelineStack.size() > 1)
1756 // Unbalanced paretheses.
1757 return None;
1758
1759 assert(PipelineStack.back() == &ResultPipeline &&
1760 "Wrong pipeline at the bottom of the stack!");
1761 return {std::move(ResultPipeline)};
1762}
1763
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001764Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1765 const PipelineElement &E,
1766 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001767 auto &Name = E.Name;
1768 auto &InnerPipeline = E.InnerPipeline;
1769
1770 // First handle complex passes like the pass managers which carry pipelines.
1771 if (!InnerPipeline.empty()) {
1772 if (Name == "module") {
1773 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001774 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1775 VerifyEachPass, DebugLogging))
1776 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001777 MPM.addPass(std::move(NestedMPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001778 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001779 }
1780 if (Name == "cgscc") {
1781 CGSCCPassManager CGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001782 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1783 DebugLogging))
1784 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001785 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001786 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001787 }
1788 if (Name == "function") {
1789 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001790 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1791 VerifyEachPass, DebugLogging))
1792 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001793 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001794 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001795 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001796 if (auto Count = parseRepeatPassName(Name)) {
1797 ModulePassManager NestedMPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001798 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1799 VerifyEachPass, DebugLogging))
1800 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001801 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001802 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001803 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001804
1805 for (auto &C : ModulePipelineParsingCallbacks)
1806 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001807 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001808
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001809 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001810 return make_error<StringError>(
1811 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1812 inconvertibleErrorCode());
1813 ;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001814 }
1815
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001816 // Manually handle aliases for pre-configured pipeline fragments.
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001817 if (startsWithDefaultPipelineAliasPrefix(Name)) {
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001818 SmallVector<StringRef, 3> Matches;
1819 if (!DefaultAliasRegex.match(Name, &Matches))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001820 return make_error<StringError>(
1821 formatv("unknown default pipeline alias '{0}'", Name).str(),
1822 inconvertibleErrorCode());
1823
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001824 assert(Matches.size() == 3 && "Must capture two matched strings!");
1825
Jordan Rosef85a95f2016-07-25 18:34:51 +00001826 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001827 .Case("O0", O0)
1828 .Case("O1", O1)
1829 .Case("O2", O2)
1830 .Case("O3", O3)
1831 .Case("Os", Os)
1832 .Case("Oz", Oz);
Rong Xuca161fa2019-08-01 22:36:34 +00001833 if (L == O0) {
1834 // Add instrumentation PGO passes -- at O0 we can still do PGO.
1835 if (PGOOpt && Matches[1] != "thinlto" &&
1836 (PGOOpt->Action == PGOOptions::IRInstr ||
1837 PGOOpt->Action == PGOOptions::IRUse))
1838 addPGOInstrPassesForO0(
1839 MPM, DebugLogging,
1840 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1841 /* IsCS */ false, PGOOpt->ProfileFile,
1842 PGOOpt->ProfileRemappingFile);
1843 // Do nothing else at all!
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001844 return Error::success();
Rong Xuca161fa2019-08-01 22:36:34 +00001845 }
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001846
1847 if (Matches[1] == "default") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001848 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
Chandler Carruth8b3be4e2017-06-01 11:39:39 +00001849 } else if (Matches[1] == "thinlto-pre-link") {
1850 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1851 } else if (Matches[1] == "thinlto") {
Teresa Johnson28023db2018-07-19 14:51:32 +00001852 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001853 } else if (Matches[1] == "lto-pre-link") {
Chandler Carruthe3f50642016-12-22 06:59:15 +00001854 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001855 } else {
1856 assert(Matches[1] == "lto" && "Not one of the matched options!");
Teresa Johnson28023db2018-07-19 14:51:32 +00001857 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001858 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001859 return Error::success();
Chandler Carruth8b5a74192016-02-28 22:16:03 +00001860 }
1861
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001862 // Finally expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00001863#define MODULE_PASS(NAME, CREATE_PASS) \
1864 if (Name == NAME) { \
1865 MPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001866 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00001867 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001868#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1869 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001870 MPM.addPass( \
1871 RequireAnalysisPass< \
1872 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001873 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001874 } \
1875 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001876 MPM.addPass(InvalidateAnalysisPass< \
1877 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001878 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001879 }
1880#include "PassRegistry.def"
1881
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001882 for (auto &C : ModulePipelineParsingCallbacks)
1883 if (C(Name, MPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001884 return Error::success();
1885 return make_error<StringError>(
1886 formatv("unknown module pass '{0}'", Name).str(),
1887 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00001888}
1889
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001890Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1891 const PipelineElement &E, bool VerifyEachPass,
1892 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001893 auto &Name = E.Name;
1894 auto &InnerPipeline = E.InnerPipeline;
1895
1896 // First handle complex passes like the pass managers which carry pipelines.
1897 if (!InnerPipeline.empty()) {
1898 if (Name == "cgscc") {
1899 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001900 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1901 VerifyEachPass, DebugLogging))
1902 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001903 // Add the nested pass manager with the appropriate adaptor.
1904 CGPM.addPass(std::move(NestedCGPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001905 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001906 }
1907 if (Name == "function") {
1908 FunctionPassManager FPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001909 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1910 VerifyEachPass, DebugLogging))
1911 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001912 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruth19913b22017-08-11 05:47:13 +00001913 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001914 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001915 }
Chandler Carruth241bf242016-08-03 07:44:48 +00001916 if (auto Count = parseRepeatPassName(Name)) {
1917 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001918 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1919 VerifyEachPass, DebugLogging))
1920 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00001921 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001922 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00001923 }
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001924 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1925 CGSCCPassManager NestedCGPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001926 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1927 VerifyEachPass, DebugLogging))
1928 return Err;
Chandler Carruth19913b22017-08-11 05:47:13 +00001929 CGPM.addPass(
1930 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001931 return Error::success();
Chandler Carruth05ca5ac2016-12-28 11:07:33 +00001932 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001933
1934 for (auto &C : CGSCCPipelineParsingCallbacks)
1935 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001936 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001937
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001938 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001939 return make_error<StringError>(
1940 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1941 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001942 }
1943
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001944// Now expand the basic registered passes from the .inc file.
Chandler Carruth572e3402014-04-21 11:12:00 +00001945#define CGSCC_PASS(NAME, CREATE_PASS) \
1946 if (Name == NAME) { \
1947 CGPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001948 return Error::success(); \
Chandler Carruth572e3402014-04-21 11:12:00 +00001949 }
Chandler Carruth628503e2015-01-06 02:10:51 +00001950#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1951 if (Name == "require<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001952 CGPM.addPass(RequireAnalysisPass< \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00001953 std::remove_reference<decltype(CREATE_PASS)>::type, \
Chandler Carruth88823462016-08-24 09:37:14 +00001954 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1955 CGSCCUpdateResult &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001956 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00001957 } \
1958 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00001959 CGPM.addPass(InvalidateAnalysisPass< \
1960 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001961 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00001962 }
1963#include "PassRegistry.def"
1964
Philip Pfaffe730f2f92017-07-10 10:57:55 +00001965 for (auto &C : CGSCCPipelineParsingCallbacks)
1966 if (C(Name, CGPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001967 return Error::success();
1968 return make_error<StringError>(
1969 formatv("unknown cgscc pass '{0}'", Name).str(),
1970 inconvertibleErrorCode());
Chandler Carruth572e3402014-04-21 11:12:00 +00001971}
1972
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001973Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1974 const PipelineElement &E,
1975 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001976 auto &Name = E.Name;
1977 auto &InnerPipeline = E.InnerPipeline;
1978
1979 // First handle complex passes like the pass managers which carry pipelines.
1980 if (!InnerPipeline.empty()) {
1981 if (Name == "function") {
1982 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001983 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1984 VerifyEachPass, DebugLogging))
1985 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001986 // Add the nested pass manager with the appropriate adaptor.
1987 FPM.addPass(std::move(NestedFPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001988 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001989 }
1990 if (Name == "loop") {
1991 LoopPassManager LPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001992 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1993 DebugLogging))
1994 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001995 // Add the nested pass manager with the appropriate adaptor.
Fedor Sergeev02e7f022017-12-29 08:16:06 +00001996 FPM.addPass(
1997 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00001998 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00001999 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002000 if (auto Count = parseRepeatPassName(Name)) {
2001 FunctionPassManager NestedFPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002002 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
2003 VerifyEachPass, DebugLogging))
2004 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002005 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002006 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002007 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002008
2009 for (auto &C : FunctionPipelineParsingCallbacks)
2010 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002011 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002012
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002013 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002014 return make_error<StringError>(
2015 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
2016 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002017 }
2018
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002019// Now expand the basic registered passes from the .inc file.
Chandler Carruth58944182014-04-21 08:08:50 +00002020#define FUNCTION_PASS(NAME, CREATE_PASS) \
2021 if (Name == NAME) { \
2022 FPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002023 return Error::success(); \
Chandler Carruth52eef882014-01-12 12:15:39 +00002024 }
Fedor Sergeevb7871402019-01-10 10:01:53 +00002025#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2026 if (checkParametrizedPassName(Name, NAME)) { \
2027 auto Params = parsePassParameters(PARSER, Name, NAME); \
2028 if (!Params) \
2029 return Params.takeError(); \
2030 FPM.addPass(CREATE_PASS(Params.get())); \
2031 return Error::success(); \
2032 }
Chandler Carruth628503e2015-01-06 02:10:51 +00002033#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
2034 if (Name == "require<" NAME ">") { \
Chandler Carruth9b35e6d2016-08-19 18:36:06 +00002035 FPM.addPass( \
2036 RequireAnalysisPass< \
2037 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002038 return Error::success(); \
Chandler Carruth3472ffb2015-01-06 04:49:44 +00002039 } \
2040 if (Name == "invalidate<" NAME ">") { \
Chandler Carruth470734b2016-02-26 12:30:18 +00002041 FPM.addPass(InvalidateAnalysisPass< \
2042 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002043 return Error::success(); \
Chandler Carruth628503e2015-01-06 02:10:51 +00002044 }
2045#include "PassRegistry.def"
2046
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002047 for (auto &C : FunctionPipelineParsingCallbacks)
2048 if (C(Name, FPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002049 return Error::success();
2050 return make_error<StringError>(
2051 formatv("unknown function pass '{0}'", Name).str(),
2052 inconvertibleErrorCode());
Chandler Carruthd8330982014-01-12 09:34:22 +00002053}
2054
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002055Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
2056 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth241bf242016-08-03 07:44:48 +00002057 StringRef Name = E.Name;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002058 auto &InnerPipeline = E.InnerPipeline;
2059
2060 // First handle complex passes like the pass managers which carry pipelines.
2061 if (!InnerPipeline.empty()) {
2062 if (Name == "loop") {
2063 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002064 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2065 VerifyEachPass, DebugLogging))
2066 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002067 // Add the nested pass manager with the appropriate adaptor.
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002068 LPM.addPass(std::move(NestedLPM));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002069 return Error::success();
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002070 }
Chandler Carruth241bf242016-08-03 07:44:48 +00002071 if (auto Count = parseRepeatPassName(Name)) {
2072 LoopPassManager NestedLPM(DebugLogging);
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002073 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2074 VerifyEachPass, DebugLogging))
2075 return Err;
Chandler Carrutha053a882016-08-04 03:52:53 +00002076 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002077 return Error::success();
Chandler Carruth241bf242016-08-03 07:44:48 +00002078 }
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002079
2080 for (auto &C : LoopPipelineParsingCallbacks)
2081 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002082 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002083
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002084 // Normal passes can't have pipelines.
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002085 return make_error<StringError>(
2086 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2087 inconvertibleErrorCode());
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002088 }
2089
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002090// Now expand the basic registered passes from the .inc file.
Justin Bognereecc3c82016-02-25 07:23:08 +00002091#define LOOP_PASS(NAME, CREATE_PASS) \
2092 if (Name == NAME) { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002093 LPM.addPass(CREATE_PASS); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002094 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002095 }
Serguei Katkov40a3b962019-04-22 10:35:07 +00002096#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2097 if (checkParametrizedPassName(Name, NAME)) { \
2098 auto Params = parsePassParameters(PARSER, Name, NAME); \
2099 if (!Params) \
2100 return Params.takeError(); \
2101 LPM.addPass(CREATE_PASS(Params.get())); \
2102 return Error::success(); \
2103 }
Justin Bognereecc3c82016-02-25 07:23:08 +00002104#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2105 if (Name == "require<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002106 LPM.addPass(RequireAnalysisPass< \
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002107 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2108 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2109 LPMUpdater &>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002110 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002111 } \
2112 if (Name == "invalidate<" NAME ">") { \
Chandler Carruthfdc6ba12016-08-03 09:14:03 +00002113 LPM.addPass(InvalidateAnalysisPass< \
Chandler Carruth470734b2016-02-26 12:30:18 +00002114 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002115 return Error::success(); \
Justin Bognereecc3c82016-02-25 07:23:08 +00002116 }
2117#include "PassRegistry.def"
2118
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002119 for (auto &C : LoopPipelineParsingCallbacks)
2120 if (C(Name, LPM, InnerPipeline))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002121 return Error::success();
2122 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2123 inconvertibleErrorCode());
Justin Bognereecc3c82016-02-25 07:23:08 +00002124}
2125
Chandler Carruthedf59962016-02-18 09:45:17 +00002126bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
Chandler Carruth45a9c202016-03-11 09:15:11 +00002127#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2128 if (Name == NAME) { \
2129 AA.registerModuleAnalysis< \
2130 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2131 return true; \
2132 }
Chandler Carruthedf59962016-02-18 09:45:17 +00002133#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2134 if (Name == NAME) { \
Chandler Carruth58dde8c2016-02-26 12:17:54 +00002135 AA.registerFunctionAnalysis< \
2136 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
Chandler Carruthedf59962016-02-18 09:45:17 +00002137 return true; \
2138 }
2139#include "PassRegistry.def"
2140
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002141 for (auto &C : AAParsingCallbacks)
2142 if (C(Name, AA))
2143 return true;
Chandler Carruthedf59962016-02-18 09:45:17 +00002144 return false;
2145}
2146
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002147Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002148 ArrayRef<PipelineElement> Pipeline,
Chandler Carruth1ff77242015-03-07 09:02:36 +00002149 bool VerifyEachPass,
2150 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002151 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002152 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2153 return Err;
2154 // FIXME: No verifier support for Loop passes!
2155 }
2156 return Error::success();
2157}
2158
2159Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2160 ArrayRef<PipelineElement> Pipeline,
2161 bool VerifyEachPass,
2162 bool DebugLogging) {
2163 for (const auto &Element : Pipeline) {
2164 if (auto Err =
2165 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2166 return Err;
2167 if (VerifyEachPass)
2168 FPM.addPass(VerifierPass());
2169 }
2170 return Error::success();
2171}
2172
2173Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2174 ArrayRef<PipelineElement> Pipeline,
2175 bool VerifyEachPass,
2176 bool DebugLogging) {
2177 for (const auto &Element : Pipeline) {
2178 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2179 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002180 // FIXME: No verifier support for CGSCC passes!
Chandler Carruth572e3402014-04-21 11:12:00 +00002181 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002182 return Error::success();
Chandler Carruth572e3402014-04-21 11:12:00 +00002183}
2184
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002185void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2186 FunctionAnalysisManager &FAM,
2187 CGSCCAnalysisManager &CGAM,
2188 ModuleAnalysisManager &MAM) {
2189 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2190 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
NAKAMURA Takumia42f5282016-05-16 10:13:37 +00002191 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2192 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2193 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2194 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2195 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2196}
2197
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002198Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2199 ArrayRef<PipelineElement> Pipeline,
2200 bool VerifyEachPass,
2201 bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002202 for (const auto &Element : Pipeline) {
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002203 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2204 return Err;
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002205 if (VerifyEachPass)
2206 MPM.addPass(VerifierPass());
Chandler Carruth66445382014-01-11 08:16:35 +00002207 }
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002208 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002209}
2210
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002211// Primary pass pipeline description parsing routine for a \c ModulePassManager
Chandler Carruth66445382014-01-11 08:16:35 +00002212// FIXME: Should this routine accept a TargetMachine or require the caller to
2213// pre-populate the analysis managers with target-specific stuff?
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002214Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2215 StringRef PipelineText,
2216 bool VerifyEachPass, bool DebugLogging) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002217 auto Pipeline = parsePipelineText(PipelineText);
2218 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002219 return make_error<StringError>(
2220 formatv("invalid pipeline '{0}'", PipelineText).str(),
2221 inconvertibleErrorCode());
Chandler Carruth66445382014-01-11 08:16:35 +00002222
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002223 // If the first name isn't at the module layer, wrap the pipeline up
2224 // automatically.
2225 StringRef FirstName = Pipeline->front().Name;
Chandler Carruth66445382014-01-11 08:16:35 +00002226
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002227 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2228 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002229 Pipeline = {{"cgscc", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002230 } else if (isFunctionPassName(FirstName,
2231 FunctionPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002232 Pipeline = {{"function", std::move(*Pipeline)}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002233 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Chandler Carruth6cb2ab22016-08-03 03:21:41 +00002234 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002235 } else {
2236 for (auto &C : TopLevelPipelineParsingCallbacks)
2237 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002238 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002239
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002240 // Unknown pass or pipeline name!
2241 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2242 return make_error<StringError>(
2243 formatv("unknown {0} name '{1}'",
2244 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2245 .str(),
2246 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002247 }
Chandler Carruth572e3402014-04-21 11:12:00 +00002248 }
2249
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002250 if (auto Err =
2251 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2252 return Err;
2253 return Error::success();
Chandler Carruth66445382014-01-11 08:16:35 +00002254}
Chandler Carruthedf59962016-02-18 09:45:17 +00002255
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002256// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002257Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2258 StringRef PipelineText,
2259 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002260 auto Pipeline = parsePipelineText(PipelineText);
2261 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002262 return make_error<StringError>(
2263 formatv("invalid pipeline '{0}'", PipelineText).str(),
2264 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002265
2266 StringRef FirstName = Pipeline->front().Name;
2267 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002268 return make_error<StringError>(
2269 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2270 PipelineText)
2271 .str(),
2272 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002273
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002274 if (auto Err =
2275 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2276 return Err;
2277 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002278}
2279
2280// Primary pass pipeline description parsing routine for a \c
2281// FunctionPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002282Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2283 StringRef PipelineText,
2284 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002285 auto Pipeline = parsePipelineText(PipelineText);
2286 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002287 return make_error<StringError>(
2288 formatv("invalid pipeline '{0}'", PipelineText).str(),
2289 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002290
2291 StringRef FirstName = Pipeline->front().Name;
2292 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002293 return make_error<StringError>(
2294 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2295 PipelineText)
2296 .str(),
2297 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002298
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002299 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2300 DebugLogging))
2301 return Err;
2302 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002303}
2304
2305// Primary pass pipeline description parsing routine for a \c LoopPassManager
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002306Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2307 StringRef PipelineText,
2308 bool VerifyEachPass, bool DebugLogging) {
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002309 auto Pipeline = parsePipelineText(PipelineText);
2310 if (!Pipeline || Pipeline->empty())
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002311 return make_error<StringError>(
2312 formatv("invalid pipeline '{0}'", PipelineText).str(),
2313 inconvertibleErrorCode());
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002314
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002315 if (auto Err =
2316 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2317 return Err;
2318
2319 return Error::success();
Philip Pfaffe730f2f92017-07-10 10:57:55 +00002320}
2321
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002322Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
Chandler Carruth060ad612016-12-23 20:38:19 +00002323 // If the pipeline just consists of the word 'default' just replace the AA
2324 // manager with our default one.
2325 if (PipelineText == "default") {
2326 AA = buildDefaultAAPipeline();
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002327 return Error::success();
Chandler Carruth060ad612016-12-23 20:38:19 +00002328 }
2329
Chandler Carruthedf59962016-02-18 09:45:17 +00002330 while (!PipelineText.empty()) {
2331 StringRef Name;
2332 std::tie(Name, PipelineText) = PipelineText.split(',');
2333 if (!parseAAPassName(AA, Name))
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002334 return make_error<StringError>(
2335 formatv("unknown alias analysis name '{0}'", Name).str(),
2336 inconvertibleErrorCode());
Chandler Carruthedf59962016-02-18 09:45:17 +00002337 }
2338
Fedor Sergeevbd6b2132018-10-17 10:36:23 +00002339 return Error::success();
Chandler Carruthedf59962016-02-18 09:45:17 +00002340}