blob: 743acc5af305061a35ae73c2efa09ef9d927b8ee [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf2836d12007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
Eugene Zelenko900b6332017-08-29 22:32:07 +000016#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000019#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/STLExtras.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/Statistic.h"
Jun Bum Lim90b6b502016-12-16 20:38:39 +000024#include "llvm/Analysis/BlockFrequencyInfo.h"
25#include "llvm/Analysis/BranchProbabilityInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000026#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000028#include "llvm/Analysis/LoopInfo.h"
Zaara Syeda3a7578c2017-05-31 17:12:38 +000029#include "llvm/Analysis/MemoryBuiltins.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000030#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000031#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000032#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000033#include "llvm/Transforms/Utils/Local.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000034#include "llvm/Analysis/ValueTracking.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000035#include "llvm/CodeGen/Analysis.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000036#include "llvm/CodeGen/ISDOpcodes.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000037#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000038#include "llvm/CodeGen/TargetLowering.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000039#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000040#include "llvm/CodeGen/TargetSubtargetInfo.h"
Craig Topper2fa14362018-03-29 17:21:10 +000041#include "llvm/CodeGen/ValueTypes.h"
Nico Weber432a3882018-04-30 14:59:11 +000042#include "llvm/Config/llvm-config.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000043#include "llvm/IR/Argument.h"
44#include "llvm/IR/Attributes.h"
45#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000046#include "llvm/IR/CallSite.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000047#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000051#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000053#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000054#include "llvm/IR/GlobalValue.h"
55#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/IRBuilder.h"
57#include "llvm/IR/InlineAsm.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000058#include "llvm/IR/InstrTypes.h"
59#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000060#include "llvm/IR/Instructions.h"
61#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000062#include "llvm/IR/Intrinsics.h"
63#include "llvm/IR/LLVMContext.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000064#include "llvm/IR/MDBuilder.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000065#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000067#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000068#include "llvm/IR/Statepoint.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000069#include "llvm/IR/Type.h"
70#include "llvm/IR/Use.h"
71#include "llvm/IR/User.h"
72#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000073#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000074#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000075#include "llvm/Pass.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000076#include "llvm/Support/BlockFrequency.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000077#include "llvm/Support/BranchProbability.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000078#include "llvm/Support/Casting.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000079#include "llvm/Support/CommandLine.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000080#include "llvm/Support/Compiler.h"
Evan Chengd3d80172007-12-05 23:58:20 +000081#include "llvm/Support/Debug.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000082#include "llvm/Support/ErrorHandling.h"
David Blaikie13e77db2018-03-23 23:58:25 +000083#include "llvm/Support/MachineValueType.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000084#include "llvm/Support/MathExtras.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000085#include "llvm/Support/raw_ostream.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000086#include "llvm/Target/TargetMachine.h"
87#include "llvm/Target/TargetOptions.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000088#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000089#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000090#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000091#include <algorithm>
92#include <cassert>
93#include <cstdint>
94#include <iterator>
95#include <limits>
96#include <memory>
97#include <utility>
98#include <vector>
Zaara Syeda3a7578c2017-05-31 17:12:38 +000099
Chris Lattnerf2836d12007-03-31 04:06:36 +0000100using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +0000101using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000102
Chandler Carruth1b9dde02014-04-22 02:02:50 +0000103#define DEBUG_TYPE "codegenprepare"
104
Cameron Zwarichced753f2011-01-05 17:27:27 +0000105STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +0000106STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
107STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +0000108STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
109 "sunken Cmps");
110STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
111 "of sunken Casts");
112STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
113 "computations were sunk");
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000114STATISTIC(NumMemoryInstsPhiCreated,
115 "Number of phis created when address "
116 "computations were sunk to memory instructions");
117STATISTIC(NumMemoryInstsSelectCreated,
118 "Number of select created when address "
119 "computations were sunk to memory instructions");
Evan Cheng0663f232011-03-21 01:19:09 +0000120STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
121STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +0000122STATISTIC(NumAndsAdded,
123 "Number of and mask instructions added to form ext loads");
124STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +0000125STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +0000126STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000127STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +0000128STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +0000129
Cameron Zwarich338d3622011-03-11 21:52:04 +0000130static cl::opt<bool> DisableBranchOpts(
131 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
132 cl::desc("Disable branch optimizations in CodeGenPrepare"));
133
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000134static cl::opt<bool>
135 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
136 cl::desc("Disable GC optimizations in CodeGenPrepare"));
137
Benjamin Kramer3d38c172012-05-06 14:25:16 +0000138static cl::opt<bool> DisableSelectToBranch(
139 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
140 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000141
Hal Finkelc3998302014-04-12 00:59:48 +0000142static cl::opt<bool> AddrSinkUsingGEPs(
Eli Friedman5fba1e52017-04-06 22:42:18 +0000143 "addr-sink-using-gep", cl::Hidden, cl::init(true),
Hal Finkelc3998302014-04-12 00:59:48 +0000144 cl::desc("Address sinking in CGP using GEPs."));
145
Tim Northovercea0abb2014-03-29 08:22:29 +0000146static cl::opt<bool> EnableAndCmpSinking(
147 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
148 cl::desc("Enable sinkinig and/cmp into branches."));
149
Quentin Colombetc32615d2014-10-31 17:52:53 +0000150static cl::opt<bool> DisableStoreExtract(
151 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
152 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
153
154static cl::opt<bool> StressStoreExtract(
155 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
156 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
157
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000158static cl::opt<bool> DisableExtLdPromotion(
159 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
160 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
161 "CodeGenPrepare"));
162
163static cl::opt<bool> StressExtLdPromotion(
164 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
165 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
166 "optimization in CodeGenPrepare"));
167
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000168static cl::opt<bool> DisablePreheaderProtect(
169 "disable-preheader-prot", cl::Hidden, cl::init(false),
170 cl::desc("Disable protection against removing loop preheaders"));
171
Dehao Chen302b69c2016-10-18 20:42:47 +0000172static cl::opt<bool> ProfileGuidedSectionPrefix(
David Callahan5960d9b12017-06-14 20:35:33 +0000173 "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
Dehao Chen302b69c2016-10-18 20:42:47 +0000174 cl::desc("Use profile info to add section prefix for hot/cold functions"));
175
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000176static cl::opt<unsigned> FreqRatioToSkipMerge(
177 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
178 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
179 "(frequency of destination block) is greater than this ratio"));
180
Wei Mia2f0b592016-12-22 19:44:45 +0000181static cl::opt<bool> ForceSplitStore(
182 "force-split-store", cl::Hidden, cl::init(false),
183 cl::desc("Force store splitting no matter what the target query says."));
184
Jun Bum Limdee55652017-04-03 19:20:07 +0000185static cl::opt<bool>
186EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
187 cl::desc("Enable merging of redundant sexts when one is dominating"
188 " the other."), cl::init(true));
189
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000190static cl::opt<bool> DisableComplexAddrModes(
Serguei Katkovd4df7442017-11-29 09:48:50 +0000191 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000192 cl::desc("Disables combining addressing modes with different parts "
193 "in optimizeMemoryInst."));
194
195static cl::opt<bool>
196AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
197 cl::desc("Allow creation of Phis in Address sinking."));
198
199static cl::opt<bool>
Serguei Katkov9fe05242018-01-26 06:26:56 +0000200AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000201 cl::desc("Allow creation of selects in Address sinking."));
202
John Brawn70cdb5b2017-11-24 14:10:45 +0000203static cl::opt<bool> AddrSinkCombineBaseReg(
204 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
205 cl::desc("Allow combining of BaseReg field in Address sinking."));
206
207static cl::opt<bool> AddrSinkCombineBaseGV(
208 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
209 cl::desc("Allow combining of BaseGV field in Address sinking."));
210
211static cl::opt<bool> AddrSinkCombineBaseOffs(
212 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
213 cl::desc("Allow combining of BaseOffs field in Address sinking."));
214
215static cl::opt<bool> AddrSinkCombineScaledReg(
216 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
217 cl::desc("Allow combining of ScaledReg field in Address sinking."));
218
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000219static cl::opt<bool>
220 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
221 cl::init(true),
222 cl::desc("Enable splitting large offset of GEP."));
223
Eric Christopherc1ea1492008-09-24 05:32:41 +0000224namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000225
226using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
227using TypeIsSExt = PointerIntPair<Type *, 1, bool>;
228using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
229using SExts = SmallVector<Instruction *, 16>;
230using ValueToSExts = DenseMap<Value *, SExts>;
231
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000232class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000233
Chris Lattner2dd09db2009-09-02 06:11:42 +0000234 class CodeGenPrepare : public FunctionPass {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000235 const TargetMachine *TM = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000236 const TargetSubtargetInfo *SubtargetInfo;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000237 const TargetLowering *TLI = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000238 const TargetRegisterInfo *TRI;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000239 const TargetTransformInfo *TTI = nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000240 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000241 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000242 std::unique_ptr<BlockFrequencyInfo> BFI;
243 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000244
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000245 /// As we scan instructions optimizing them, this is the next instruction
246 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000247 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000248
Evan Cheng0663f232011-03-21 01:19:09 +0000249 /// Keeps track of non-local addresses that have been sunk into a block.
250 /// This allows us to avoid inserting duplicate code for blocks with
Simon Dardis230f4532017-11-24 16:45:28 +0000251 /// multiple load/stores of the same address. The usage of WeakTrackingVH
252 /// enables SunkAddrs to be treated as a cache whose entries can be
253 /// invalidated if a sunken address computation has been erased.
254 ValueMap<Value*, WeakTrackingVH> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000255
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000256 /// Keeps track of all instructions inserted for the current function.
257 SetOfInstrs InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000258
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000259 /// Keeps track of the type of the related instruction before their
260 /// promotion for the current function.
261 InstrToOrigTy PromotedInsts;
262
Jun Bum Limdee55652017-04-03 19:20:07 +0000263 /// Keep track of instructions removed during promotion.
264 SetOfInstrs RemovedInsts;
265
266 /// Keep track of sext chains based on their initial value.
267 DenseMap<Value *, Instruction *> SeenChainsForSExt;
268
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000269 /// Keep track of GEPs accessing the same data structures such as structs or
270 /// arrays that are candidates to be split later because of their large
271 /// size.
272 DenseMap<
273 AssertingVH<Value>,
274 SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
275 LargeOffsetGEPMap;
276
277 /// Keep track of new GEP base after splitting the GEPs having large offset.
278 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
279
280 /// Map serial numbers to Large offset GEPs.
281 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
282
Jun Bum Limdee55652017-04-03 19:20:07 +0000283 /// Keep track of SExt promoted.
284 ValueToSExts ValToSExtendedUses;
285
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000286 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000287 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000288
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000289 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000290 bool OptSize;
291
Mehdi Amini4fe37982015-07-07 18:45:17 +0000292 /// DataLayout for the Function being processed.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000293 const DataLayout *DL = nullptr;
Mehdi Amini4fe37982015-07-07 18:45:17 +0000294
Chris Lattnerf2836d12007-03-31 04:06:36 +0000295 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000296 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000297
298 CodeGenPrepare() : FunctionPass(ID) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000299 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
300 }
Eugene Zelenko900b6332017-08-29 22:32:07 +0000301
Craig Topper4584cd52014-03-07 09:26:03 +0000302 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000303
Mehdi Amini117296c2016-10-01 02:56:57 +0000304 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000305
Craig Topper4584cd52014-03-07 09:26:03 +0000306 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000307 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000308 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000309 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000310 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000311 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000312 }
313
Chris Lattnerf2836d12007-03-31 04:06:36 +0000314 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000315 bool eliminateFallThrough(Function &F);
316 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000317 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000318 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
319 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000320 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
321 bool isPreheader);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000322 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
323 bool optimizeInst(Instruction *I, bool &ModifiedDT);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000324 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000325 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000326 bool optimizeInlineAsmInst(CallInst *CS);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000327 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000328 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000329 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000330 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000331 bool optimizeSelectInst(SelectInst *SI);
332 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000333 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000334 bool optimizeExtractElementInst(Instruction *Inst);
335 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
336 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000337 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
338 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
339 bool tryToPromoteExts(TypePromotionTransaction &TPT,
340 const SmallVectorImpl<Instruction *> &Exts,
341 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
342 unsigned CreatedInstsCost = 0);
Jun Bum Limdee55652017-04-03 19:20:07 +0000343 bool mergeSExts(Function &F);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000344 bool splitLargeGEPOffsets();
Jun Bum Limdee55652017-04-03 19:20:07 +0000345 bool performAddressTypePromotion(
346 Instruction *&Inst,
347 bool AllowPromotionWithoutCommonHeader,
348 bool HasPromoted, TypePromotionTransaction &TPT,
349 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000350 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000351 bool simplifyOffsetableRelocate(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000352 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000353
354} // end anonymous namespace
Devang Patel09f162c2007-05-01 21:15:47 +0000355
Devang Patel8c78a0b2007-05-03 01:11:54 +0000356char CodeGenPrepare::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000357
Matthias Braun1527baa2017-05-25 21:26:32 +0000358INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000359 "Optimize for code generation", false, false)
Dehao Chen302b69c2016-10-18 20:42:47 +0000360INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000361INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000362 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000363
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000364FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000365
Chris Lattnerf2836d12007-03-31 04:06:36 +0000366bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000367 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000368 return false;
369
Mehdi Amini4fe37982015-07-07 18:45:17 +0000370 DL = &F.getParent()->getDataLayout();
371
Chris Lattnerf2836d12007-03-31 04:06:36 +0000372 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000373 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000374 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000375 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000376
Devang Patel8f606d72011-03-24 15:35:25 +0000377 ModifiedDT = false;
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000378 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
379 TM = &TPC->getTM<TargetMachine>();
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000380 SubtargetInfo = TM->getSubtargetImpl(F);
381 TLI = SubtargetInfo->getTargetLowering();
382 TRI = SubtargetInfo->getRegisterInfo();
383 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000384 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000385 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000386 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000387 BPI.reset(new BranchProbabilityInfo(F, *LI));
388 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000389 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000390
Easwaran Raman0d55b552017-11-14 19:31:51 +0000391 ProfileSummaryInfo *PSI =
392 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen302b69c2016-10-18 20:42:47 +0000393 if (ProfileGuidedSectionPrefix) {
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000394 if (PSI->isFunctionHotInCallGraph(&F, *BFI))
Dehao Chen302b69c2016-10-18 20:42:47 +0000395 F.setSectionPrefix(".hot");
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000396 else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
Teresa Johnson720d9b42017-05-09 01:43:24 +0000397 F.setSectionPrefix(".unlikely");
Dehao Chen302b69c2016-10-18 20:42:47 +0000398 }
399
Preston Gurdcdf540d2012-09-04 18:22:17 +0000400 /// This optimization identifies DIV instructions that can be
401 /// profitably bypassed and carried out with a shorter, faster divide.
Easwaran Raman0d55b552017-11-14 19:31:51 +0000402 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
403 TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000404 const DenseMap<unsigned int, unsigned int> &BypassWidths =
405 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000406 BasicBlock* BB = &*F.begin();
407 while (BB != nullptr) {
408 // bypassSlowDivision may create new BBs, but we don't want to reapply the
409 // optimization to those blocks.
410 BasicBlock* Next = BB->getNextNode();
411 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
412 BB = Next;
413 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000414 }
415
416 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000417 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000418 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000419
Devang Patel53771ba2011-08-18 00:50:51 +0000420 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000421 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000422 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000423 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000424
Geoff Berry5d534b62017-02-21 18:53:14 +0000425 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000426 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000427
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000428 // Split some critical edges where one of the sources is an indirect branch,
429 // to help generate sane code for PHIs involving such edges.
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000430 EverMadeChange |= SplitIndirectBrCriticalEdges(F);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000431
Chris Lattnerc3748562007-04-02 01:35:34 +0000432 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000433 while (MadeChange) {
434 MadeChange = false;
Jun Bum Limdee55652017-04-03 19:20:07 +0000435 SeenChainsForSExt.clear();
436 ValToSExtendedUses.clear();
437 RemovedInsts.clear();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000438 LargeOffsetGEPMap.clear();
439 LargeOffsetGEPID.clear();
Hans Wennborg02fbc712012-09-19 07:48:16 +0000440 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000441 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000442 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000443 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000444
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000445 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000446 if (ModifiedDTOnIteration)
447 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000448 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000449 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
450 MadeChange |= mergeSExts(F);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000451 if (!LargeOffsetGEPMap.empty())
452 MadeChange |= splitLargeGEPOffsets();
Jun Bum Limdee55652017-04-03 19:20:07 +0000453
454 // Really free removed instructions during promotion.
455 for (Instruction *I : RemovedInsts)
Reid Kleckner96ab8722017-05-18 17:24:10 +0000456 I->deleteValue();
Jun Bum Limdee55652017-04-03 19:20:07 +0000457
Chris Lattnerf2836d12007-03-31 04:06:36 +0000458 EverMadeChange |= MadeChange;
459 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000460
461 SunkAddrs.clear();
462
Cameron Zwarich338d3622011-03-11 21:52:04 +0000463 if (!DisableBranchOpts) {
464 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000465 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000466 for (BasicBlock &BB : F) {
467 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
468 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000469 if (!MadeChange) continue;
470
471 for (SmallVectorImpl<BasicBlock*>::iterator
472 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
473 if (pred_begin(*II) == pred_end(*II))
474 WorkList.insert(*II);
475 }
476
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000477 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000478 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000479 while (!WorkList.empty()) {
480 BasicBlock *BB = *WorkList.begin();
481 WorkList.erase(BB);
482 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
483
484 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000485
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000486 for (SmallVectorImpl<BasicBlock*>::iterator
487 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
488 if (pred_begin(*II) == pred_end(*II))
489 WorkList.insert(*II);
490 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000491
Nadav Rotem70409992012-08-14 05:19:07 +0000492 // Merge pairs of basic blocks with unconditional branches, connected by
493 // a single edge.
494 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000495 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000496
Cameron Zwarich338d3622011-03-11 21:52:04 +0000497 EverMadeChange |= MadeChange;
498 }
499
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000500 if (!DisableGCOpts) {
501 SmallVector<Instruction *, 2> Statepoints;
502 for (BasicBlock &BB : F)
503 for (Instruction &I : BB)
504 if (isStatepoint(I))
505 Statepoints.push_back(&I);
506 for (auto &I : Statepoints)
507 EverMadeChange |= simplifyOffsetableRelocate(*I);
508 }
509
Chris Lattnerf2836d12007-03-31 04:06:36 +0000510 return EverMadeChange;
511}
512
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000513/// Merge basic blocks which are connected by a single edge, where one of the
514/// basic blocks has a single successor pointing to the other basic block,
515/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000516bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000517 bool Changed = false;
518 // Scan all of the blocks in the function, except for the entry block.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000519 // Use a temporary array to avoid iterator being invalidated when
520 // deleting blocks.
521 SmallVector<WeakTrackingVH, 16> Blocks;
522 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
523 Blocks.push_back(&Block);
524
525 for (auto &Block : Blocks) {
526 auto *BB = cast_or_null<BasicBlock>(Block);
527 if (!BB)
528 continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000529 // If the destination block has a single pred, then this is a trivial
530 // edge, just collapse it.
531 BasicBlock *SinglePred = BB->getSinglePredecessor();
532
Evan Cheng64a223a2012-09-28 23:58:57 +0000533 // Don't merge if BB's address is taken.
534 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000535
536 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
537 if (Term && !Term->isConditional()) {
538 Changed = true;
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000539 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000540
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000541 // Merge BB into SinglePred and delete it.
542 MergeBlockIntoPredecessor(BB);
Nadav Rotem70409992012-08-14 05:19:07 +0000543 }
544 }
545 return Changed;
546}
547
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000548/// Find a destination block from BB if BB is mergeable empty block.
549BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
550 // If this block doesn't end with an uncond branch, ignore it.
551 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
552 if (!BI || !BI->isUnconditional())
553 return nullptr;
554
555 // If the instruction before the branch (skipping debug info) isn't a phi
556 // node, then other stuff is happening here.
557 BasicBlock::iterator BBI = BI->getIterator();
558 if (BBI != BB->begin()) {
559 --BBI;
560 while (isa<DbgInfoIntrinsic>(BBI)) {
561 if (BBI == BB->begin())
562 break;
563 --BBI;
564 }
565 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
566 return nullptr;
567 }
568
569 // Do not break infinite loops.
570 BasicBlock *DestBB = BI->getSuccessor(0);
571 if (DestBB == BB)
572 return nullptr;
573
574 if (!canMergeBlocks(BB, DestBB))
575 DestBB = nullptr;
576
577 return DestBB;
578}
579
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000580/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
581/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
582/// edges in ways that are non-optimal for isel. Start by eliminating these
583/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000584bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000585 SmallPtrSet<BasicBlock *, 16> Preheaders;
586 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
587 while (!LoopList.empty()) {
588 Loop *L = LoopList.pop_back_val();
589 LoopList.insert(LoopList.end(), L->begin(), L->end());
590 if (BasicBlock *Preheader = L->getLoopPreheader())
591 Preheaders.insert(Preheader);
592 }
593
Chris Lattnerc3748562007-04-02 01:35:34 +0000594 bool MadeChange = false;
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000595 // Copy blocks into a temporary array to avoid iterator invalidation issues
596 // as we remove them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000597 // Note that this intentionally skips the entry block.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000598 SmallVector<WeakTrackingVH, 16> Blocks;
599 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
600 Blocks.push_back(&Block);
601
602 for (auto &Block : Blocks) {
603 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
604 if (!BB)
605 continue;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000606 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
607 if (!DestBB ||
608 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000609 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000610
Sanjay Patelfc580a62015-09-21 23:03:16 +0000611 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000612 MadeChange = true;
613 }
614 return MadeChange;
615}
616
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000617bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
618 BasicBlock *DestBB,
619 bool isPreheader) {
620 // Do not delete loop preheaders if doing so would create a critical edge.
621 // Loop preheaders can be good locations to spill registers. If the
622 // preheader is deleted and we create a critical edge, registers may be
623 // spilled in the loop body instead.
624 if (!DisablePreheaderProtect && isPreheader &&
625 !(BB->getSinglePredecessor() &&
626 BB->getSinglePredecessor()->getSingleSuccessor()))
627 return false;
628
629 // Try to skip merging if the unique predecessor of BB is terminated by a
630 // switch or indirect branch instruction, and BB is used as an incoming block
631 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
632 // add COPY instructions in the predecessor of BB instead of BB (if it is not
633 // merged). Note that the critical edge created by merging such blocks wont be
634 // split in MachineSink because the jump table is not analyzable. By keeping
635 // such empty block (BB), ISel will place COPY instructions in BB, not in the
636 // predecessor of BB.
637 BasicBlock *Pred = BB->getUniquePredecessor();
638 if (!Pred ||
639 !(isa<SwitchInst>(Pred->getTerminator()) ||
640 isa<IndirectBrInst>(Pred->getTerminator())))
641 return true;
642
643 if (BB->getTerminator() != BB->getFirstNonPHI())
644 return true;
645
646 // We use a simple cost heuristic which determine skipping merging is
647 // profitable if the cost of skipping merging is less than the cost of
648 // merging : Cost(skipping merging) < Cost(merging BB), where the
649 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
650 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
651 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
652 // Freq(Pred) / Freq(BB) > 2.
653 // Note that if there are multiple empty blocks sharing the same incoming
654 // value for the PHIs in the DestBB, we consider them together. In such
655 // case, Cost(merging BB) will be the sum of their frequencies.
656
657 if (!isa<PHINode>(DestBB->begin()))
658 return true;
659
660 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
661
662 // Find all other incoming blocks from which incoming values of all PHIs in
663 // DestBB are the same as the ones from BB.
664 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
665 ++PI) {
666 BasicBlock *DestBBPred = *PI;
667 if (DestBBPred == BB)
668 continue;
669
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000670 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
671 return DestPN.getIncomingValueForBlock(BB) ==
672 DestPN.getIncomingValueForBlock(DestBBPred);
673 }))
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000674 SameIncomingValueBBs.insert(DestBBPred);
675 }
676
677 // See if all BB's incoming values are same as the value from Pred. In this
678 // case, no reason to skip merging because COPYs are expected to be place in
679 // Pred already.
680 if (SameIncomingValueBBs.count(Pred))
681 return true;
682
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000683 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
684 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
685
686 for (auto SameValueBB : SameIncomingValueBBs)
687 if (SameValueBB->getUniquePredecessor() == Pred &&
688 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
689 BBFreq += BFI->getBlockFreq(SameValueBB);
690
691 return PredFreq.getFrequency() <=
692 BBFreq.getFrequency() * FreqRatioToSkipMerge;
693}
694
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000695/// Return true if we can merge BB into DestBB if there is a single
696/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000697/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000698bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000699 const BasicBlock *DestBB) const {
700 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
701 // the successor. If there are more complex condition (e.g. preheaders),
702 // don't mess around with them.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000703 for (const PHINode &PN : BB->phis()) {
704 for (const User *U : PN.users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000705 const Instruction *UI = cast<Instruction>(U);
706 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000707 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000708 // If User is inside DestBB block and it is a PHINode then check
709 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000710 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000711 if (UI->getParent() == DestBB) {
712 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000713 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
714 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
715 if (Insn && Insn->getParent() == BB &&
716 Insn->getParent() != UPN->getIncomingBlock(I))
717 return false;
718 }
719 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000720 }
721 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000722
Chris Lattnerc3748562007-04-02 01:35:34 +0000723 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
724 // and DestBB may have conflicting incoming values for the block. If so, we
725 // can't merge the block.
726 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
727 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000728
Chris Lattnerc3748562007-04-02 01:35:34 +0000729 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000730 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000731 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
732 // It is faster to get preds from a PHI than with pred_iterator.
733 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
734 BBPreds.insert(BBPN->getIncomingBlock(i));
735 } else {
736 BBPreds.insert(pred_begin(BB), pred_end(BB));
737 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000738
Chris Lattnerc3748562007-04-02 01:35:34 +0000739 // Walk the preds of DestBB.
740 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
741 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
742 if (BBPreds.count(Pred)) { // Common predecessor?
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000743 for (const PHINode &PN : DestBB->phis()) {
744 const Value *V1 = PN.getIncomingValueForBlock(Pred);
745 const Value *V2 = PN.getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000746
Chris Lattnerc3748562007-04-02 01:35:34 +0000747 // If V2 is a phi node in BB, look up what the mapped value will be.
748 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
749 if (V2PN->getParent() == BB)
750 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000751
Chris Lattnerc3748562007-04-02 01:35:34 +0000752 // If there is a conflict, bail out.
753 if (V1 != V2) return false;
754 }
755 }
756 }
757
758 return true;
759}
760
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000761/// Eliminate a basic block that has only phi's and an unconditional branch in
762/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000763void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000764 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
765 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000766
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000767 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
768 << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000769
Chris Lattnerc3748562007-04-02 01:35:34 +0000770 // If the destination block has a single pred, then this is a trivial edge,
771 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000772 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000773 if (SinglePred != DestBB) {
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000774 assert(SinglePred == BB &&
775 "Single predecessor not the same as predecessor");
776 // Merge DestBB into SinglePred/BB and delete it.
777 MergeBlockIntoPredecessor(DestBB);
778 // Note: BB(=SinglePred) will not be deleted on this path.
779 // DestBB(=its single successor) is the one that was deleted.
780 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000781 return;
782 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000783 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000784
Chris Lattnerc3748562007-04-02 01:35:34 +0000785 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
786 // to handle the new incoming edges it is about to have.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000787 for (PHINode &PN : DestBB->phis()) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000788 // Remove the incoming value for BB, and remember it.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000789 Value *InVal = PN.removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000790
Chris Lattnerc3748562007-04-02 01:35:34 +0000791 // Two options: either the InVal is a phi node defined in BB or it is some
792 // value that dominates BB.
793 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
794 if (InValPhi && InValPhi->getParent() == BB) {
795 // Add all of the input values of the input PHI as inputs of this phi.
796 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000797 PN.addIncoming(InValPhi->getIncomingValue(i),
798 InValPhi->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000799 } else {
800 // Otherwise, add one instance of the dominating value for each edge that
801 // we will be adding.
802 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
803 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000804 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000805 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000806 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000807 PN.addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000808 }
809 }
810 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000811
Chris Lattnerc3748562007-04-02 01:35:34 +0000812 // The PHIs are now updated, change everything that refers to BB to use
813 // DestBB and remove BB.
814 BB->replaceAllUsesWith(DestBB);
815 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000816 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000817
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000818 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000819}
820
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000821// Computes a map of base pointer relocation instructions to corresponding
822// derived pointer relocation instructions given a vector of all relocate calls
823static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000824 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
825 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
826 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000827 // Collect information in two maps: one primarily for locating the base object
828 // while filling the second map; the second map is the final structure holding
829 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000830 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
831 for (auto *ThisRelocate : AllRelocateCalls) {
832 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
833 ThisRelocate->getDerivedPtrIndex());
834 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000835 }
836 for (auto &Item : RelocateIdxMap) {
837 std::pair<unsigned, unsigned> Key = Item.first;
838 if (Key.first == Key.second)
839 // Base relocation: nothing to insert
840 continue;
841
Manuel Jacob83eefa62016-01-05 04:03:00 +0000842 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000843 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000844
845 // We're iterating over RelocateIdxMap so we cannot modify it.
846 auto MaybeBase = RelocateIdxMap.find(BaseKey);
847 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000848 // TODO: We might want to insert a new base object relocate and gep off
849 // that, if there are enough derived object relocates.
850 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000851
852 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000853 }
854}
855
856// Accepts a GEP and extracts the operands into a vector provided they're all
857// small integer constants
858static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
859 SmallVectorImpl<Value *> &OffsetV) {
860 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
861 // Only accept small constant integer operands
862 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
863 if (!Op || Op->getZExtValue() > 20)
864 return false;
865 }
866
867 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
868 OffsetV.push_back(GEP->getOperand(i));
869 return true;
870}
871
872// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
873// replace, computes a replacement, and affects it.
874static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000875simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
876 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000877 bool MadeChange = false;
Serguei Katkov9e5604d2017-08-17 05:48:30 +0000878 // We must ensure the relocation of derived pointer is defined after
879 // relocation of base pointer. If we find a relocation corresponding to base
880 // defined earlier than relocation of base then we move relocation of base
881 // right before found relocation. We consider only relocation in the same
882 // basic block as relocation of base. Relocations from other basic block will
883 // be skipped by optimization and we do not care about them.
884 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
885 &*R != RelocatedBase; ++R)
886 if (auto RI = dyn_cast<GCRelocateInst>(R))
887 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
888 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
889 RelocatedBase->moveBefore(RI);
890 break;
891 }
892
Manuel Jacob83eefa62016-01-05 04:03:00 +0000893 for (GCRelocateInst *ToReplace : Targets) {
894 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000895 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000896 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000897 // A duplicate relocate call. TODO: coalesce duplicates.
898 continue;
899 }
900
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000901 if (RelocatedBase->getParent() != ToReplace->getParent()) {
902 // Base and derived relocates are in different basic blocks.
903 // In this case transform is only valid when base dominates derived
904 // relocate. However it would be too expensive to check dominance
905 // for each such relocate, so we skip the whole transformation.
906 continue;
907 }
908
Manuel Jacob83eefa62016-01-05 04:03:00 +0000909 Value *Base = ToReplace->getBasePtr();
910 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000911 if (!Derived || Derived->getPointerOperand() != Base)
912 continue;
913
914 SmallVector<Value *, 2> OffsetV;
915 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
916 continue;
917
918 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000919 assert(RelocatedBase->getNextNode() &&
920 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000921
922 // Insert after RelocatedBase
923 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000924 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000925
926 // If gc_relocate does not match the actual type, cast it to the right type.
927 // In theory, there must be a bitcast after gc_relocate if the type does not
928 // match, and we should reuse it to get the derived pointer. But it could be
929 // cases like this:
930 // bb1:
931 // ...
932 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
933 // br label %merge
934 //
935 // bb2:
936 // ...
937 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
938 // br label %merge
939 //
940 // merge:
941 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
942 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
943 //
944 // In this case, we can not find the bitcast any more. So we insert a new bitcast
945 // no matter there is already one or not. In this way, we can handle all cases, and
946 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000947 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000948 if (RelocatedBase->getType() != Base->getType()) {
949 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000950 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000951 }
David Blaikie68d535c2015-03-24 22:38:16 +0000952 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000953 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000954 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000955 // If the newly generated derived pointer's type does not match the original derived
956 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000957 Value *ActualReplacement = Replacement;
958 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000959 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000960 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000961 }
962 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000963 ToReplace->eraseFromParent();
964
965 MadeChange = true;
966 }
967 return MadeChange;
968}
969
970// Turns this:
971//
972// %base = ...
973// %ptr = gep %base + 15
974// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
975// %base' = relocate(%tok, i32 4, i32 4)
976// %ptr' = relocate(%tok, i32 4, i32 5)
977// %val = load %ptr'
978//
979// into this:
980//
981// %base = ...
982// %ptr = gep %base + 15
983// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
984// %base' = gc.relocate(%tok, i32 4, i32 4)
985// %ptr' = gep %base' + 15
986// %val = load %ptr'
987bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
988 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000989 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000990
991 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000992 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000993 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000994 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000995
996 // We need atleast one base pointer relocation + one derived pointer
997 // relocation to mangle
998 if (AllRelocateCalls.size() < 2)
999 return false;
1000
1001 // RelocateInstMap is a mapping from the base relocate instruction to the
1002 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +00001003 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001004 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1005 if (RelocateInstMap.empty())
1006 return false;
1007
1008 for (auto &Item : RelocateInstMap)
1009 // Item.first is the RelocatedBase to offset against
1010 // Item.second is the vector of Targets to replace
1011 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1012 return MadeChange;
1013}
1014
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001015/// SinkCast - Sink the specified cast instruction into its user blocks
1016static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001017 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001018
Chris Lattnerf2836d12007-03-31 04:06:36 +00001019 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001020 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001021
Chris Lattnerf2836d12007-03-31 04:06:36 +00001022 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001023 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001024 UI != E; ) {
1025 Use &TheUse = UI.getUse();
1026 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001027
Chris Lattnerf2836d12007-03-31 04:06:36 +00001028 // Figure out which BB this cast is used in. For PHI's this is the
1029 // appropriate predecessor block.
1030 BasicBlock *UserBB = User->getParent();
1031 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001032 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001033 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001034
Chris Lattnerf2836d12007-03-31 04:06:36 +00001035 // Preincrement use iterator so we don't invalidate it.
1036 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001037
David Majnemer0c80e2e2016-04-27 19:36:38 +00001038 // The first insertion point of a block containing an EH pad is after the
1039 // pad. If the pad is the user, we cannot sink the cast past the pad.
1040 if (User->isEHPad())
1041 continue;
1042
Andrew Kaylord0430e82015-11-23 19:16:15 +00001043 // If the block selected to receive the cast is an EH pad that does not
1044 // allow non-PHI instructions before the terminator, we can't sink the
1045 // cast.
1046 if (UserBB->getTerminator()->isEHPad())
1047 continue;
1048
Chris Lattnerf2836d12007-03-31 04:06:36 +00001049 // If this user is in the same block as the cast, don't change the cast.
1050 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001051
Chris Lattnerf2836d12007-03-31 04:06:36 +00001052 // If we have already inserted a cast into this block, use it.
1053 CastInst *&InsertedCast = InsertedCasts[UserBB];
1054
1055 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001056 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001057 assert(InsertPt != UserBB->end());
1058 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1059 CI->getType(), "", &*InsertPt);
Vedant Kumar9374c042018-05-23 22:03:48 +00001060 InsertedCast->setDebugLoc(CI->getDebugLoc());
Chris Lattnerf2836d12007-03-31 04:06:36 +00001061 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001062
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001063 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001064 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001065 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001066 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001067 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001068
Chris Lattnerf2836d12007-03-31 04:06:36 +00001069 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001070 if (CI->use_empty()) {
Adrian Prantl261ac8b2017-11-03 21:55:03 +00001071 salvageDebugInfo(*CI);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001072 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001073 MadeChange = true;
1074 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001075
Chris Lattnerf2836d12007-03-31 04:06:36 +00001076 return MadeChange;
1077}
1078
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001079/// If the specified cast instruction is a noop copy (e.g. it's casting from
1080/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1081/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001082///
1083/// Return true if any changes are made.
Mehdi Amini44ede332015-07-09 02:09:04 +00001084static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1085 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001086 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1087 // than sinking only nop casts, but is helpful on some platforms.
1088 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1089 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1090 ASC->getDestAddressSpace()))
1091 return false;
1092 }
1093
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001094 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001095 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1096 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001097
1098 // This is an fp<->int conversion?
1099 if (SrcVT.isInteger() != DstVT.isInteger())
1100 return false;
1101
1102 // If this is an extension, it will be a zero or sign extension, which
1103 // isn't a noop.
1104 if (SrcVT.bitsLT(DstVT)) return false;
1105
1106 // If these values will be promoted, find out what they will be promoted
1107 // to. This helps us consider truncates on PPC as noop copies when they
1108 // are.
1109 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1110 TargetLowering::TypePromoteInteger)
1111 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1112 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1113 TargetLowering::TypePromoteInteger)
1114 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1115
1116 // If, after promotion, these are the same types, this is a noop copy.
1117 if (SrcVT != DstVT)
1118 return false;
1119
1120 return SinkCast(CI);
1121}
1122
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001123/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1124/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001125///
1126/// Return true if any changes were made.
1127static bool CombineUAddWithOverflow(CmpInst *CI) {
1128 Value *A, *B;
1129 Instruction *AddI;
1130 if (!match(CI,
1131 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1132 return false;
1133
1134 Type *Ty = AddI->getType();
1135 if (!isa<IntegerType>(Ty))
1136 return false;
1137
1138 // We don't want to move around uses of condition values this late, so we we
1139 // check if it is legal to create the call to the intrinsic in the basic
1140 // block containing the icmp:
1141
1142 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1143 return false;
1144
1145#ifndef NDEBUG
1146 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1147 // for now:
1148 if (AddI->hasOneUse())
1149 assert(*AddI->user_begin() == CI && "expected!");
1150#endif
1151
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001152 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001153 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1154
1155 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1156
1157 auto *UAddWithOverflow =
1158 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1159 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1160 auto *Overflow =
1161 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1162
1163 CI->replaceAllUsesWith(Overflow);
1164 AddI->replaceAllUsesWith(UAdd);
1165 CI->eraseFromParent();
1166 AddI->eraseFromParent();
1167 return true;
1168}
1169
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001170/// Sink the given CmpInst into user blocks to reduce the number of virtual
1171/// registers that must be created and coalesced. This is a clear win except on
1172/// targets with multiple condition code registers (PowerPC), where it might
1173/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001174///
1175/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001176static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001177 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001178
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001179 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001180 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001181 return false;
1182
1183 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001184 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001185
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001186 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001187 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001188 UI != E; ) {
1189 Use &TheUse = UI.getUse();
1190 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001191
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001192 // Preincrement use iterator so we don't invalidate it.
1193 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001194
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001195 // Don't bother for PHI nodes.
1196 if (isa<PHINode>(User))
1197 continue;
1198
1199 // Figure out which BB this cmp is used in.
1200 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001201
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001202 // If this user is in the same block as the cmp, don't change the cmp.
1203 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001204
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001205 // If we have already inserted a cmp into this block, use it.
1206 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1207
1208 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001209 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001210 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001211 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001212 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1213 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001214 // Propagate the debug info.
1215 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001216 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001217
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001218 // Replace a use of the cmp with a use of the new cmp.
1219 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001220 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001221 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001222 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001223
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001224 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001225 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001226 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001227 MadeChange = true;
1228 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001229
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001230 return MadeChange;
1231}
1232
Peter Zotovf87e5502016-04-03 17:11:53 +00001233static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001234 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001235 return true;
1236
1237 if (CombineUAddWithOverflow(CI))
1238 return true;
1239
1240 return false;
1241}
1242
Geoff Berry5d534b62017-02-21 18:53:14 +00001243/// Duplicate and sink the given 'and' instruction into user blocks where it is
1244/// used in a compare to allow isel to generate better code for targets where
1245/// this operation can be combined.
1246///
1247/// Return true if any changes are made.
1248static bool sinkAndCmp0Expression(Instruction *AndI,
1249 const TargetLowering &TLI,
1250 SetOfInstrs &InsertedInsts) {
1251 // Double-check that we're not trying to optimize an instruction that was
1252 // already optimized by some other part of this pass.
1253 assert(!InsertedInsts.count(AndI) &&
1254 "Attempting to optimize already optimized and instruction");
1255 (void) InsertedInsts;
1256
1257 // Nothing to do for single use in same basic block.
1258 if (AndI->hasOneUse() &&
1259 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1260 return false;
1261
1262 // Try to avoid cases where sinking/duplicating is likely to increase register
1263 // pressure.
1264 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1265 !isa<ConstantInt>(AndI->getOperand(1)) &&
1266 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1267 return false;
1268
1269 for (auto *U : AndI->users()) {
1270 Instruction *User = cast<Instruction>(U);
1271
1272 // Only sink for and mask feeding icmp with 0.
1273 if (!isa<ICmpInst>(User))
1274 return false;
1275
1276 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1277 if (!CmpC || !CmpC->isZero())
1278 return false;
1279 }
1280
1281 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1282 return false;
1283
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001284 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1285 LLVM_DEBUG(AndI->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001286
1287 // Push the 'and' into the same block as the icmp 0. There should only be
1288 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1289 // others, so we don't need to keep track of which BBs we insert into.
1290 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1291 UI != E; ) {
1292 Use &TheUse = UI.getUse();
1293 Instruction *User = cast<Instruction>(*UI);
1294
1295 // Preincrement use iterator so we don't invalidate it.
1296 ++UI;
1297
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001298 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
Geoff Berry5d534b62017-02-21 18:53:14 +00001299
1300 // Keep the 'and' in the same place if the use is already in the same block.
1301 Instruction *InsertPt =
1302 User->getParent() == AndI->getParent() ? AndI : User;
1303 Instruction *InsertedAnd =
1304 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1305 AndI->getOperand(1), "", InsertPt);
1306 // Propagate the debug info.
1307 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1308
1309 // Replace a use of the 'and' with a use of the new 'and'.
1310 TheUse = InsertedAnd;
1311 ++NumAndUses;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001312 LLVM_DEBUG(User->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001313 }
1314
1315 // We removed all uses, nuke the and.
1316 AndI->eraseFromParent();
1317 return true;
1318}
1319
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001320/// Check if the candidates could be combined with a shift instruction, which
1321/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001322/// 1. Truncate instruction
1323/// 2. And instruction and the imm is a mask of the low bits:
1324/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001325static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001326 if (!isa<TruncInst>(User)) {
1327 if (User->getOpcode() != Instruction::And ||
1328 !isa<ConstantInt>(User->getOperand(1)))
1329 return false;
1330
Quentin Colombetd4f44692014-04-22 01:20:34 +00001331 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001332
Quentin Colombetd4f44692014-04-22 01:20:34 +00001333 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001334 return false;
1335 }
1336 return true;
1337}
1338
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001339/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001340static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001341SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1342 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001343 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001344 BasicBlock *UserBB = User->getParent();
1345 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1346 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1347 bool MadeChange = false;
1348
1349 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1350 TruncE = TruncI->user_end();
1351 TruncUI != TruncE;) {
1352
1353 Use &TruncTheUse = TruncUI.getUse();
1354 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1355 // Preincrement use iterator so we don't invalidate it.
1356
1357 ++TruncUI;
1358
1359 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1360 if (!ISDOpcode)
1361 continue;
1362
Tim Northovere2239ff2014-07-29 10:20:22 +00001363 // If the use is actually a legal node, there will not be an
1364 // implicit truncate.
1365 // FIXME: always querying the result type is just an
1366 // approximation; some nodes' legality is determined by the
1367 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001368 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001369 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001370 continue;
1371
1372 // Don't bother for PHI nodes.
1373 if (isa<PHINode>(TruncUser))
1374 continue;
1375
1376 BasicBlock *TruncUserBB = TruncUser->getParent();
1377
1378 if (UserBB == TruncUserBB)
1379 continue;
1380
1381 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1382 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1383
1384 if (!InsertedShift && !InsertedTrunc) {
1385 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001386 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001387 // Sink the shift
1388 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001389 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1390 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001391 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001392 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1393 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001394
1395 // Sink the trunc
1396 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1397 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001398 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001399
1400 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001401 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001402
1403 MadeChange = true;
1404
1405 TruncTheUse = InsertedTrunc;
1406 }
1407 }
1408 return MadeChange;
1409}
1410
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001411/// Sink the shift *right* instruction into user blocks if the uses could
1412/// potentially be combined with this shift instruction and generate BitExtract
1413/// instruction. It will only be applied if the architecture supports BitExtract
1414/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001415/// BB1:
1416/// %x.extract.shift = lshr i64 %arg1, 32
1417/// BB2:
1418/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1419/// ==>
1420///
1421/// BB2:
1422/// %x.extract.shift.1 = lshr i64 %arg1, 32
1423/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1424///
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001425/// CodeGen will recognize the pattern in BB2 and generate BitExtract
Yi Jiangd069f632014-04-21 19:34:27 +00001426/// instruction.
1427/// Return true if any changes are made.
1428static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001429 const TargetLowering &TLI,
1430 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001431 BasicBlock *DefBB = ShiftI->getParent();
1432
1433 /// Only insert instructions in each block once.
1434 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1435
Mehdi Amini44ede332015-07-09 02:09:04 +00001436 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001437
1438 bool MadeChange = false;
1439 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1440 UI != E;) {
1441 Use &TheUse = UI.getUse();
1442 Instruction *User = cast<Instruction>(*UI);
1443 // Preincrement use iterator so we don't invalidate it.
1444 ++UI;
1445
1446 // Don't bother for PHI nodes.
1447 if (isa<PHINode>(User))
1448 continue;
1449
1450 if (!isExtractBitsCandidateUse(User))
1451 continue;
1452
1453 BasicBlock *UserBB = User->getParent();
1454
1455 if (UserBB == DefBB) {
1456 // If the shift and truncate instruction are in the same BB. The use of
1457 // the truncate(TruncUse) may still introduce another truncate if not
1458 // legal. In this case, we would like to sink both shift and truncate
1459 // instruction to the BB of TruncUse.
1460 // for example:
1461 // BB1:
1462 // i64 shift.result = lshr i64 opnd, imm
1463 // trunc.result = trunc shift.result to i16
1464 //
1465 // BB2:
1466 // ----> We will have an implicit truncate here if the architecture does
1467 // not have i16 compare.
1468 // cmp i16 trunc.result, opnd2
1469 //
1470 if (isa<TruncInst>(User) && shiftIsLegal
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001471 // If the type of the truncate is legal, no truncate will be
Yi Jiangd069f632014-04-21 19:34:27 +00001472 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001473 &&
1474 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001475 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001476 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001477
1478 continue;
1479 }
1480 // If we have already inserted a shift into this block, use it.
1481 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1482
1483 if (!InsertedShift) {
1484 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001485 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001486
1487 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001488 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1489 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001490 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001491 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1492 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001493
1494 MadeChange = true;
1495 }
1496
1497 // Replace a use of the shift with a use of the new shift.
1498 TheUse = InsertedShift;
1499 }
1500
1501 // If we removed all uses, nuke the shift.
1502 if (ShiftI->use_empty())
1503 ShiftI->eraseFromParent();
1504
1505 return MadeChange;
1506}
1507
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001508/// If counting leading or trailing zeros is an expensive operation and a zero
1509/// input is defined, add a check for zero to avoid calling the intrinsic.
1510///
1511/// We want to transform:
1512/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1513///
1514/// into:
1515/// entry:
1516/// %cmpz = icmp eq i64 %A, 0
1517/// br i1 %cmpz, label %cond.end, label %cond.false
1518/// cond.false:
1519/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1520/// br label %cond.end
1521/// cond.end:
1522/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1523///
1524/// If the transform is performed, return true and set ModifiedDT to true.
1525static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1526 const TargetLowering *TLI,
1527 const DataLayout *DL,
1528 bool &ModifiedDT) {
1529 if (!TLI || !DL)
1530 return false;
1531
1532 // If a zero input is undefined, it doesn't make sense to despeculate that.
1533 if (match(CountZeros->getOperand(1), m_One()))
1534 return false;
1535
1536 // If it's cheap to speculate, there's nothing to do.
1537 auto IntrinsicID = CountZeros->getIntrinsicID();
1538 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1539 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1540 return false;
1541
1542 // Only handle legal scalar cases. Anything else requires too much work.
1543 Type *Ty = CountZeros->getType();
1544 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001545 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001546 return false;
1547
1548 // The intrinsic will be sunk behind a compare against zero and branch.
1549 BasicBlock *StartBlock = CountZeros->getParent();
1550 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1551
1552 // Create another block after the count zero intrinsic. A PHI will be added
1553 // in this block to select the result of the intrinsic or the bit-width
1554 // constant if the input to the intrinsic is zero.
1555 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1556 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1557
1558 // Set up a builder to create a compare, conditional branch, and PHI.
1559 IRBuilder<> Builder(CountZeros->getContext());
1560 Builder.SetInsertPoint(StartBlock->getTerminator());
1561 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1562
1563 // Replace the unconditional branch that was created by the first split with
1564 // a compare against zero and a conditional branch.
1565 Value *Zero = Constant::getNullValue(Ty);
1566 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1567 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1568 StartBlock->getTerminator()->eraseFromParent();
1569
1570 // Create a PHI in the end block to select either the output of the intrinsic
1571 // or the bit width of the operand.
1572 Builder.SetInsertPoint(&EndBlock->front());
1573 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1574 CountZeros->replaceAllUsesWith(PN);
1575 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1576 PN->addIncoming(BitWidth, StartBlock);
1577 PN->addIncoming(CountZeros, CallBlock);
1578
1579 // We are explicitly handling the zero case, so we can set the intrinsic's
1580 // undefined zero argument to 'true'. This will also prevent reprocessing the
1581 // intrinsic; we only despeculate when a zero input is defined.
1582 CountZeros->setArgOperand(1, Builder.getTrue());
1583 ModifiedDT = true;
1584 return true;
1585}
1586
Sanjay Patel3b8974b2017-06-08 20:00:09 +00001587bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001588 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001589
Chris Lattner7a277142011-01-15 07:14:54 +00001590 // Lower inline assembly if we can.
1591 // If we found an inline asm expession, and if the target knows how to
1592 // lower it to normal LLVM code, do so now.
1593 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1594 if (TLI->ExpandInlineAsm(CI)) {
1595 // Avoid invalidating the iterator.
1596 CurInstIterator = BB->begin();
1597 // Avoid processing instructions out of order, which could cause
1598 // reuse before a value is defined.
1599 SunkAddrs.clear();
1600 return true;
1601 }
1602 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001603 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001604 return true;
1605 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001606
John Brawn0dbcd652015-03-18 12:01:59 +00001607 // Align the pointer arguments to this call if the target thinks it's a good
1608 // idea
1609 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001610 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001611 for (auto &Arg : CI->arg_operands()) {
1612 // We want to align both objects whose address is used directly and
1613 // objects whose address is used in casts and GEPs, though it only makes
1614 // sense for GEPs if the offset is a multiple of the desired alignment and
1615 // if size - offset meets the size threshold.
1616 if (!Arg->getType()->isPointerTy())
1617 continue;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001618 APInt Offset(DL->getIndexSizeInBits(
Mehdi Amini4fe37982015-07-07 18:45:17 +00001619 cast<PointerType>(Arg->getType())->getAddressSpace()),
1620 0);
1621 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001622 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001623 if ((Offset2 & (PrefAlign-1)) != 0)
1624 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001625 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001626 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1627 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001628 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001629 // Global variables can only be aligned if they are defined in this
1630 // object (i.e. they are uniquely initialized in this object), and
1631 // over-aligning global variables that have an explicit section is
1632 // forbidden.
1633 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001634 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001635 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001636 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001637 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001638 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001639 }
1640 // If this is a memcpy (or similar) then we may be able to improve the
1641 // alignment
1642 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Daniel Neilsonbe58a222018-01-31 17:24:53 +00001643 unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
1644 if (DestAlign > MI->getDestAlignment())
1645 MI->setDestAlignment(DestAlign);
1646 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1647 unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
1648 if (SrcAlign > MTI->getSourceAlignment())
1649 MTI->setSourceAlignment(SrcAlign);
1650 }
John Brawn0dbcd652015-03-18 12:01:59 +00001651 }
1652 }
1653
Philip Reamesac115ed2016-03-09 23:13:12 +00001654 // If we have a cold call site, try to sink addressing computation into the
1655 // cold block. This interacts with our handling for loads and stores to
1656 // ensure that we can fold all uses of a potential addressing computation
1657 // into their uses. TODO: generalize this to work over profiling data
1658 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1659 for (auto &Arg : CI->arg_operands()) {
1660 if (!Arg->getType()->isPointerTy())
1661 continue;
1662 unsigned AS = Arg->getType()->getPointerAddressSpace();
1663 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1664 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001665
Eric Christopher4b7948e2010-03-11 02:41:03 +00001666 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001667 if (II) {
1668 switch (II->getIntrinsicID()) {
1669 default: break;
1670 case Intrinsic::objectsize: {
1671 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00001672 ConstantInt *RetVal =
1673 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001674 // Substituting this can cause recursive simplifications, which can
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001675 // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case
1676 // this
Sanjoy Das2cbeb002017-04-26 16:37:05 +00001677 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001678 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001679 WeakTrackingVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001680
Sanjay Patel545a4562016-01-20 18:59:16 +00001681 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001682
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001683 // If the iterator instruction was recursively deleted, start over at the
1684 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001685 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001686 CurInstIterator = BB->begin();
1687 SunkAddrs.clear();
1688 }
1689 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001690 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001691 case Intrinsic::aarch64_stlxr:
1692 case Intrinsic::aarch64_stxr: {
1693 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1694 if (!ExtVal || !ExtVal->hasOneUse() ||
1695 ExtVal->getParent() == CI->getParent())
1696 return false;
1697 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1698 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001699 // Mark this instruction as "inserted by CGP", so that other
1700 // optimizations don't touch it.
1701 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001702 return true;
1703 }
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001704 case Intrinsic::launder_invariant_group:
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001705 II->replaceAllUsesWith(II->getArgOperand(0));
1706 II->eraseFromParent();
1707 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001708
1709 case Intrinsic::cttz:
1710 case Intrinsic::ctlz:
1711 // If counting zeros is expensive, try to avoid it.
1712 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001713 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001714
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001715 if (TLI) {
1716 SmallVector<Value*, 2> PtrOps;
1717 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001718 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1719 while (!PtrOps.empty()) {
1720 Value *PtrVal = PtrOps.pop_back_val();
1721 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1722 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001723 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001724 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001725 }
Pete Cooper615fd892012-03-13 20:59:56 +00001726 }
1727
Eric Christopher4b7948e2010-03-11 02:41:03 +00001728 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001729 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001730
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001731 // Lower all default uses of _chk calls. This is very similar
1732 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001733 // to fortified library functions (e.g. __memcpy_chk) that have the default
1734 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001735 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001736 if (Value *V = Simplifier.optimizeCall(CI)) {
1737 CI->replaceAllUsesWith(V);
1738 CI->eraseFromParent();
1739 return true;
1740 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001741
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001742 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001743}
Chris Lattner1b93be52011-01-15 07:25:29 +00001744
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001745/// Look for opportunities to duplicate return instructions to the predecessor
1746/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001747/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001748/// bb0:
1749/// %tmp0 = tail call i32 @f0()
1750/// br label %return
1751/// bb1:
1752/// %tmp1 = tail call i32 @f1()
1753/// br label %return
1754/// bb2:
1755/// %tmp2 = tail call i32 @f2()
1756/// br label %return
1757/// return:
1758/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1759/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001760/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001761///
1762/// =>
1763///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001764/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001765/// bb0:
1766/// %tmp0 = tail call i32 @f0()
1767/// ret i32 %tmp0
1768/// bb1:
1769/// %tmp1 = tail call i32 @f1()
1770/// ret i32 %tmp1
1771/// bb2:
1772/// %tmp2 = tail call i32 @f2()
1773/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001774/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001775bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001776 if (!TLI)
1777 return false;
1778
Michael Kuperstein71321562016-09-07 20:29:49 +00001779 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1780 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001781 return false;
1782
Craig Topperc0196b12014-04-14 00:51:57 +00001783 PHINode *PN = nullptr;
1784 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001785 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001786 if (V) {
1787 BCI = dyn_cast<BitCastInst>(V);
1788 if (BCI)
1789 V = BCI->getOperand(0);
1790
1791 PN = dyn_cast<PHINode>(V);
1792 if (!PN)
1793 return false;
1794 }
Evan Cheng0663f232011-03-21 01:19:09 +00001795
Cameron Zwarich4649f172011-03-24 04:52:10 +00001796 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001797 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001798
Cameron Zwarich4649f172011-03-24 04:52:10 +00001799 // Make sure there are no instructions between the PHI and return, or that the
1800 // return is the first instruction in the block.
1801 if (PN) {
1802 BasicBlock::iterator BI = BB->begin();
1803 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001804 if (&*BI == BCI)
1805 // Also skip over the bitcast.
1806 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001807 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001808 return false;
1809 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001810 BasicBlock::iterator BI = BB->begin();
1811 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001812 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001813 return false;
1814 }
Evan Cheng0663f232011-03-21 01:19:09 +00001815
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001816 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1817 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001818 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001819 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001820 if (PN) {
1821 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1822 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1823 // Make sure the phi value is indeed produced by the tail call.
1824 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001825 TLI->mayBeEmittedAsTailCall(CI) &&
1826 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001827 TailCalls.push_back(CI);
1828 }
1829 } else {
1830 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001831 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001832 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001833 continue;
1834
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001835 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001836 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1837 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001838 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1839 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001840 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001841
Cameron Zwarich4649f172011-03-24 04:52:10 +00001842 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001843 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1844 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001845 TailCalls.push_back(CI);
1846 }
Evan Cheng0663f232011-03-21 01:19:09 +00001847 }
1848
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001849 bool Changed = false;
1850 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1851 CallInst *CI = TailCalls[i];
1852 CallSite CS(CI);
1853
1854 // Conservatively require the attributes of the call to match those of the
1855 // return. Ignore noalias because it doesn't affect the call sequence.
Reid Klecknerb5180542017-03-21 16:57:19 +00001856 AttributeList CalleeAttrs = CS.getAttributes();
1857 if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1858 .removeAttribute(Attribute::NoAlias) !=
1859 AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1860 .removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001861 continue;
1862
1863 // Make sure the call instruction is followed by an unconditional branch to
1864 // the return block.
1865 BasicBlock *CallBB = CI->getParent();
1866 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1867 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1868 continue;
1869
1870 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00001871 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001872 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001873 ++NumRetsDup;
1874 }
1875
1876 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001877 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001878 BB->eraseFromParent();
1879
1880 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001881}
1882
Chris Lattner728f9022008-11-25 07:09:13 +00001883//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001884// Memory Optimization
1885//===----------------------------------------------------------------------===//
1886
Chandler Carruthc8925912013-01-05 02:09:22 +00001887namespace {
1888
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001889/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00001890/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001891struct ExtAddrMode : public TargetLowering::AddrMode {
Eugene Zelenko900b6332017-08-29 22:32:07 +00001892 Value *BaseReg = nullptr;
1893 Value *ScaledReg = nullptr;
John Brawn736bf002017-10-03 13:08:22 +00001894 Value *OriginalValue = nullptr;
1895
1896 enum FieldName {
1897 NoField = 0x00,
1898 BaseRegField = 0x01,
1899 BaseGVField = 0x02,
1900 BaseOffsField = 0x04,
1901 ScaledRegField = 0x08,
1902 ScaleField = 0x10,
1903 MultipleFields = 0xff
1904 };
Eugene Zelenko900b6332017-08-29 22:32:07 +00001905
1906 ExtAddrMode() = default;
1907
Chandler Carruthc8925912013-01-05 02:09:22 +00001908 void print(raw_ostream &OS) const;
1909 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001910
John Brawn736bf002017-10-03 13:08:22 +00001911 FieldName compare(const ExtAddrMode &other) {
1912 // First check that the types are the same on each field, as differing types
1913 // is something we can't cope with later on.
1914 if (BaseReg && other.BaseReg &&
1915 BaseReg->getType() != other.BaseReg->getType())
1916 return MultipleFields;
1917 if (BaseGV && other.BaseGV &&
1918 BaseGV->getType() != other.BaseGV->getType())
1919 return MultipleFields;
1920 if (ScaledReg && other.ScaledReg &&
1921 ScaledReg->getType() != other.ScaledReg->getType())
1922 return MultipleFields;
1923
1924 // Check each field to see if it differs.
1925 unsigned Result = NoField;
1926 if (BaseReg != other.BaseReg)
1927 Result |= BaseRegField;
1928 if (BaseGV != other.BaseGV)
1929 Result |= BaseGVField;
1930 if (BaseOffs != other.BaseOffs)
1931 Result |= BaseOffsField;
1932 if (ScaledReg != other.ScaledReg)
1933 Result |= ScaledRegField;
1934 // Don't count 0 as being a different scale, because that actually means
1935 // unscaled (which will already be counted by having no ScaledReg).
1936 if (Scale && other.Scale && Scale != other.Scale)
1937 Result |= ScaleField;
1938
1939 if (countPopulation(Result) > 1)
1940 return MultipleFields;
1941 else
1942 return static_cast<FieldName>(Result);
1943 }
1944
John Brawn4b476482017-11-27 11:29:15 +00001945 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
1946 // with no offset.
John Brawn736bf002017-10-03 13:08:22 +00001947 bool isTrivial() {
John Brawn4b476482017-11-27 11:29:15 +00001948 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
1949 // trivial if at most one of these terms is nonzero, except that BaseGV and
1950 // BaseReg both being zero actually means a null pointer value, which we
1951 // consider to be 'non-zero' here.
1952 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
Chandler Carruthc8925912013-01-05 02:09:22 +00001953 }
John Brawn70cdb5b2017-11-24 14:10:45 +00001954
1955 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
1956 switch (Field) {
1957 default:
1958 return nullptr;
1959 case BaseRegField:
1960 return BaseReg;
1961 case BaseGVField:
1962 return BaseGV;
1963 case ScaledRegField:
1964 return ScaledReg;
1965 case BaseOffsField:
1966 return ConstantInt::get(IntPtrTy, BaseOffs);
1967 }
1968 }
1969
1970 void SetCombinedField(FieldName Field, Value *V,
1971 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
1972 switch (Field) {
1973 default:
1974 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
1975 break;
1976 case ExtAddrMode::BaseRegField:
1977 BaseReg = V;
1978 break;
1979 case ExtAddrMode::BaseGVField:
1980 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
1981 // in the BaseReg field.
1982 assert(BaseReg == nullptr);
1983 BaseReg = V;
1984 BaseGV = nullptr;
1985 break;
1986 case ExtAddrMode::ScaledRegField:
1987 ScaledReg = V;
1988 // If we have a mix of scaled and unscaled addrmodes then we want scale
1989 // to be the scale and not zero.
1990 if (!Scale)
1991 for (const ExtAddrMode &AM : AddrModes)
1992 if (AM.Scale) {
1993 Scale = AM.Scale;
1994 break;
1995 }
1996 break;
1997 case ExtAddrMode::BaseOffsField:
1998 // The offset is no longer a constant, so it goes in ScaledReg with a
1999 // scale of 1.
2000 assert(ScaledReg == nullptr);
2001 ScaledReg = V;
2002 Scale = 1;
2003 BaseOffs = 0;
2004 break;
2005 }
2006 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002007};
2008
Eugene Zelenko900b6332017-08-29 22:32:07 +00002009} // end anonymous namespace
2010
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002011#ifndef NDEBUG
2012static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2013 AM.print(OS);
2014 return OS;
2015}
2016#endif
2017
Aaron Ballman615eb472017-10-15 14:32:27 +00002018#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthc8925912013-01-05 02:09:22 +00002019void ExtAddrMode::print(raw_ostream &OS) const {
2020 bool NeedPlus = false;
2021 OS << "[";
2022 if (BaseGV) {
2023 OS << (NeedPlus ? " + " : "")
2024 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002025 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002026 NeedPlus = true;
2027 }
2028
Richard Trieuc0f91212014-05-30 03:15:17 +00002029 if (BaseOffs) {
2030 OS << (NeedPlus ? " + " : "")
2031 << BaseOffs;
2032 NeedPlus = true;
2033 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002034
2035 if (BaseReg) {
2036 OS << (NeedPlus ? " + " : "")
2037 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002038 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002039 NeedPlus = true;
2040 }
2041 if (Scale) {
2042 OS << (NeedPlus ? " + " : "")
2043 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002044 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002045 }
2046
2047 OS << ']';
2048}
2049
Yaron Kereneb2a2542016-01-29 20:50:44 +00002050LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002051 print(dbgs());
2052 dbgs() << '\n';
2053}
2054#endif
2055
Eugene Zelenko900b6332017-08-29 22:32:07 +00002056namespace {
2057
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002058/// This class provides transaction based operation on the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002059/// Every change made through this class is recorded in the internal state and
2060/// can be undone (rollback) until commit is called.
2061class TypePromotionTransaction {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002062 /// This represents the common interface of the individual transaction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002063 /// Each class implements the logic for doing one specific modification on
2064 /// the IR via the TypePromotionTransaction.
2065 class TypePromotionAction {
2066 protected:
2067 /// The Instruction modified.
2068 Instruction *Inst;
2069
2070 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002071 /// Constructor of the action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002072 /// The constructor performs the related action on the IR.
2073 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2074
Eugene Zelenko900b6332017-08-29 22:32:07 +00002075 virtual ~TypePromotionAction() = default;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002076
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002077 /// Undo the modification done by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002078 /// When this method is called, the IR must be in the same state as it was
2079 /// before this action was applied.
2080 /// \pre Undoing the action works if and only if the IR is in the exact same
2081 /// state as it was directly after this action was applied.
2082 virtual void undo() = 0;
2083
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002084 /// Advocate every change made by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002085 /// When the results on the IR of the action are to be kept, it is important
2086 /// to call this function, otherwise hidden information may be kept forever.
2087 virtual void commit() {
2088 // Nothing to be done, this action is not doing anything.
2089 }
2090 };
2091
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002092 /// Utility to remember the position of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002093 class InsertionHandler {
2094 /// Position of an instruction.
2095 /// Either an instruction:
2096 /// - Is the first in a basic block: BB is used.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002097 /// - Has a previous instruction: PrevInst is used.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002098 union {
2099 Instruction *PrevInst;
2100 BasicBlock *BB;
2101 } Point;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002102
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002103 /// Remember whether or not the instruction had a previous instruction.
2104 bool HasPrevInstruction;
2105
2106 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002107 /// Record the position of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002108 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002109 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002110 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2111 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002112 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002113 else
2114 Point.BB = Inst->getParent();
2115 }
2116
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002117 /// Insert \p Inst at the recorded position.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002118 void insert(Instruction *Inst) {
2119 if (HasPrevInstruction) {
2120 if (Inst->getParent())
2121 Inst->removeFromParent();
2122 Inst->insertAfter(Point.PrevInst);
2123 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002124 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002125 if (Inst->getParent())
2126 Inst->moveBefore(Position);
2127 else
2128 Inst->insertBefore(Position);
2129 }
2130 }
2131 };
2132
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002133 /// Move an instruction before another.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002134 class InstructionMoveBefore : public TypePromotionAction {
2135 /// Original position of the instruction.
2136 InsertionHandler Position;
2137
2138 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002139 /// Move \p Inst before \p Before.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002140 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2141 : TypePromotionAction(Inst), Position(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002142 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
2143 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002144 Inst->moveBefore(Before);
2145 }
2146
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002147 /// Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002148 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002149 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002150 Position.insert(Inst);
2151 }
2152 };
2153
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002154 /// Set the operand of an instruction with a new value.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002155 class OperandSetter : public TypePromotionAction {
2156 /// Original operand of the instruction.
2157 Value *Origin;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002158
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002159 /// Index of the modified instruction.
2160 unsigned Idx;
2161
2162 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002163 /// Set \p Idx operand of \p Inst with \p NewVal.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002164 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2165 : TypePromotionAction(Inst), Idx(Idx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002166 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2167 << "for:" << *Inst << "\n"
2168 << "with:" << *NewVal << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002169 Origin = Inst->getOperand(Idx);
2170 Inst->setOperand(Idx, NewVal);
2171 }
2172
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002173 /// Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002174 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002175 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2176 << "for: " << *Inst << "\n"
2177 << "with: " << *Origin << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002178 Inst->setOperand(Idx, Origin);
2179 }
2180 };
2181
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002182 /// Hide the operands of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002183 /// Do as if this instruction was not using any of its operands.
2184 class OperandsHider : public TypePromotionAction {
2185 /// The list of original operands.
2186 SmallVector<Value *, 4> OriginalValues;
2187
2188 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002189 /// Remove \p Inst from the uses of the operands of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002190 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002191 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002192 unsigned NumOpnds = Inst->getNumOperands();
2193 OriginalValues.reserve(NumOpnds);
2194 for (unsigned It = 0; It < NumOpnds; ++It) {
2195 // Save the current operand.
2196 Value *Val = Inst->getOperand(It);
2197 OriginalValues.push_back(Val);
2198 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002199 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002200 // that we are not willing to pay.
2201 Inst->setOperand(It, UndefValue::get(Val->getType()));
2202 }
2203 }
2204
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002205 /// Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002206 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002207 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002208 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2209 Inst->setOperand(It, OriginalValues[It]);
2210 }
2211 };
2212
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002213 /// Build a truncate instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002214 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002215 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002216
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002217 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002218 /// Build a truncate instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002219 /// result.
2220 /// trunc Opnd to Ty.
2221 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2222 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002223 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002224 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002225 }
2226
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002227 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002228 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002229
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002230 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002231 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002232 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002233 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2234 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002235 }
2236 };
2237
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002238 /// Build a sign extension instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002239 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002240 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002241
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002242 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002243 /// Build a sign extension instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002244 /// result.
2245 /// sext Opnd to Ty.
2246 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002247 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002248 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002249 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002250 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002251 }
2252
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002253 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002254 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002255
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002256 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002257 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002258 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002259 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2260 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002261 }
2262 };
2263
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002264 /// Build a zero extension instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002265 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002266 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002267
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002268 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002269 /// Build a zero extension instruction of \p Opnd producing a \p Ty
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002270 /// result.
2271 /// zext Opnd to Ty.
2272 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002273 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002274 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002275 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002276 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002277 }
2278
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002279 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002280 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002281
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002282 /// Remove the built instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002283 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002284 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002285 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2286 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002287 }
2288 };
2289
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002290 /// Mutate an instruction to another type.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002291 class TypeMutator : public TypePromotionAction {
2292 /// Record the original type.
2293 Type *OrigTy;
2294
2295 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002296 /// Mutate the type of \p Inst into \p NewTy.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002297 TypeMutator(Instruction *Inst, Type *NewTy)
2298 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002299 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2300 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002301 Inst->mutateType(NewTy);
2302 }
2303
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002304 /// Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002305 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002306 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2307 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002308 Inst->mutateType(OrigTy);
2309 }
2310 };
2311
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002312 /// Replace the uses of an instruction by another instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002313 class UsesReplacer : public TypePromotionAction {
2314 /// Helper structure to keep track of the replaced uses.
2315 struct InstructionAndIdx {
2316 /// The instruction using the instruction.
2317 Instruction *Inst;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002318
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002319 /// The index where this instruction is used for Inst.
2320 unsigned Idx;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002321
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002322 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2323 : Inst(Inst), Idx(Idx) {}
2324 };
2325
2326 /// Keep track of the original uses (pair Instruction, Index).
2327 SmallVector<InstructionAndIdx, 4> OriginalUses;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002328
2329 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002330
2331 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002332 /// Replace all the use of \p Inst by \p New.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002333 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002334 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2335 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002336 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002337 for (Use &U : Inst->uses()) {
2338 Instruction *UserI = cast<Instruction>(U.getUser());
2339 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002340 }
2341 // Now, we can replace the uses.
2342 Inst->replaceAllUsesWith(New);
2343 }
2344
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002345 /// Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002346 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002347 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002348 for (use_iterator UseIt = OriginalUses.begin(),
2349 EndIt = OriginalUses.end();
2350 UseIt != EndIt; ++UseIt) {
2351 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2352 }
2353 }
2354 };
2355
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002356 /// Remove an instruction from the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002357 class InstructionRemover : public TypePromotionAction {
2358 /// Original position of the instruction.
2359 InsertionHandler Inserter;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002360
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002361 /// Helper structure to hide all the link to the instruction. In other
2362 /// words, this helps to do as if the instruction was removed.
2363 OperandsHider Hider;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002364
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002365 /// Keep track of the uses replaced, if any.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002366 UsesReplacer *Replacer = nullptr;
2367
Jun Bum Limdee55652017-04-03 19:20:07 +00002368 /// Keep track of instructions removed.
2369 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002370
2371 public:
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002372 /// Remove all reference of \p Inst and optionally replace all its
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002373 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002374 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002375 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002376 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2377 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002378 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Eugene Zelenko900b6332017-08-29 22:32:07 +00002379 RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002380 if (New)
2381 Replacer = new UsesReplacer(Inst, New);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002382 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002383 RemovedInsts.insert(Inst);
2384 /// The instructions removed here will be freed after completing
2385 /// optimizeBlock() for all blocks as we need to keep track of the
2386 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002387 Inst->removeFromParent();
2388 }
2389
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002390 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002391
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002392 /// Resurrect the instruction and reassign it to the proper uses if
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002393 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002394 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002395 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002396 Inserter.insert(Inst);
2397 if (Replacer)
2398 Replacer->undo();
2399 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002400 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002401 }
2402 };
2403
2404public:
2405 /// Restoration point.
2406 /// The restoration point is a pointer to an action instead of an iterator
2407 /// because the iterator may be invalidated but not the pointer.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002408 using ConstRestorationPt = const TypePromotionAction *;
Jun Bum Limdee55652017-04-03 19:20:07 +00002409
2410 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2411 : RemovedInsts(RemovedInsts) {}
2412
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002413 /// Advocate every changes made in that transaction.
2414 void commit();
Eugene Zelenko900b6332017-08-29 22:32:07 +00002415
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002416 /// Undo all the changes made after the given point.
2417 void rollback(ConstRestorationPt Point);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002418
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002419 /// Get the current restoration point.
2420 ConstRestorationPt getRestorationPoint() const;
2421
2422 /// \name API for IR modification with state keeping to support rollback.
2423 /// @{
2424 /// Same as Instruction::setOperand.
2425 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002426
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002427 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002428 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002429
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002430 /// Same as Value::replaceAllUsesWith.
2431 void replaceAllUsesWith(Instruction *Inst, Value *New);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002432
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002433 /// Same as Value::mutateType.
2434 void mutateType(Instruction *Inst, Type *NewTy);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002435
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002436 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002437 Value *createTrunc(Instruction *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002438
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002439 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002440 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002441
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002442 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002443 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002444
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002445 /// Same as Instruction::moveBefore.
2446 void moveBefore(Instruction *Inst, Instruction *Before);
2447 /// @}
2448
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002449private:
2450 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002451 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002452
2453 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2454
Jun Bum Limdee55652017-04-03 19:20:07 +00002455 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002456};
2457
Eugene Zelenko900b6332017-08-29 22:32:07 +00002458} // end anonymous namespace
2459
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002460void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2461 Value *NewVal) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002462 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2463 Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002464}
2465
2466void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2467 Value *NewVal) {
2468 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002469 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2470 Inst, RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002471}
2472
2473void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2474 Value *New) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002475 Actions.push_back(
2476 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002477}
2478
2479void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002480 Actions.push_back(
2481 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002482}
2483
Quentin Colombetac55b152014-09-16 22:36:07 +00002484Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2485 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002486 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002487 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002488 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002489 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002490}
2491
Quentin Colombetac55b152014-09-16 22:36:07 +00002492Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2493 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002494 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002495 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002496 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002497 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002498}
2499
Quentin Colombetac55b152014-09-16 22:36:07 +00002500Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2501 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002502 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002503 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002504 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002505 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002506}
2507
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002508void TypePromotionTransaction::moveBefore(Instruction *Inst,
2509 Instruction *Before) {
2510 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002511 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2512 Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002513}
2514
2515TypePromotionTransaction::ConstRestorationPt
2516TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002517 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002518}
2519
2520void TypePromotionTransaction::commit() {
2521 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002522 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002523 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002524 Actions.clear();
2525}
2526
2527void TypePromotionTransaction::rollback(
2528 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002529 while (!Actions.empty() && Point != Actions.back().get()) {
2530 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002531 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002532 }
2533}
2534
Eugene Zelenko900b6332017-08-29 22:32:07 +00002535namespace {
2536
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002537/// A helper class for matching addressing modes.
Chandler Carruthc8925912013-01-05 02:09:22 +00002538///
2539/// This encapsulates the logic for matching the target-legal addressing modes.
2540class AddressingModeMatcher {
2541 SmallVectorImpl<Instruction*> &AddrModeInsts;
2542 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002543 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002544 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002545
2546 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2547 /// the memory instruction that we're computing this address for.
2548 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002549 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002550 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002551
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002552 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002553 /// part of the return value of this addressing mode matching stuff.
2554 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002555
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002556 /// The instructions inserted by other CodeGenPrepare optimizations.
2557 const SetOfInstrs &InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002558
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002559 /// A map from the instructions to their type before promotion.
2560 InstrToOrigTy &PromotedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002561
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002562 /// The ongoing transaction where every action should be registered.
2563 TypePromotionTransaction &TPT;
2564
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002565 // A GEP which has too large offset to be folded into the addressing mode.
2566 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
2567
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002568 /// This is set to true when we should not do profitability checks.
2569 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002570 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002571
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002572 AddressingModeMatcher(
2573 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
2574 const TargetRegisterInfo &TRI, Type *AT, unsigned AS, Instruction *MI,
2575 ExtAddrMode &AM, const SetOfInstrs &InsertedInsts,
2576 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
2577 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002578 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002579 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2580 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002581 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002582 IgnoreProfitability = false;
2583 }
Stephen Lin837bba12013-07-15 17:55:02 +00002584
Eugene Zelenko900b6332017-08-29 22:32:07 +00002585public:
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002586 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002587 /// give an access type of AccessTy. This returns a list of involved
2588 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002589 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002590 /// optimizations.
2591 /// \p PromotedInsts maps the instructions to their type before promotion.
2592 /// \p The ongoing transaction where every action should be registered.
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002593 static ExtAddrMode
2594 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
2595 SmallVectorImpl<Instruction *> &AddrModeInsts,
2596 const TargetLowering &TLI, const TargetRegisterInfo &TRI,
2597 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
2598 TypePromotionTransaction &TPT,
2599 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002600 ExtAddrMode Result;
2601
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002602 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002603 MemoryInst, Result, InsertedInsts,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002604 PromotedInsts, TPT, LargeOffsetGEP)
2605 .matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002606 (void)Success; assert(Success && "Couldn't select *anything*?");
2607 return Result;
2608 }
Eugene Zelenko900b6332017-08-29 22:32:07 +00002609
Chandler Carruthc8925912013-01-05 02:09:22 +00002610private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002611 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2612 bool matchAddr(Value *V, unsigned Depth);
2613 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002614 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002615 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002616 ExtAddrMode &AMBefore,
2617 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002618 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2619 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002620 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002621};
2622
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002623/// Keep track of simplification of Phi nodes.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002624/// Accept the set of all phi nodes and erase phi node from this set
2625/// if it is simplified.
2626class SimplificationTracker {
2627 DenseMap<Value *, Value *> Storage;
2628 const SimplifyQuery &SQ;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002629 // Tracks newly created Phi nodes. We use a SetVector to get deterministic
2630 // order when iterating over the set in MatchPhiSet.
2631 SmallSetVector<PHINode *, 32> AllPhiNodes;
2632 // Tracks newly created Select nodes.
2633 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002634
2635public:
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002636 SimplificationTracker(const SimplifyQuery &sq)
2637 : SQ(sq) {}
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002638
2639 Value *Get(Value *V) {
2640 do {
2641 auto SV = Storage.find(V);
2642 if (SV == Storage.end())
2643 return V;
2644 V = SV->second;
2645 } while (true);
2646 }
2647
2648 Value *Simplify(Value *Val) {
2649 SmallVector<Value *, 32> WorkList;
2650 SmallPtrSet<Value *, 32> Visited;
2651 WorkList.push_back(Val);
2652 while (!WorkList.empty()) {
2653 auto P = WorkList.pop_back_val();
2654 if (!Visited.insert(P).second)
2655 continue;
2656 if (auto *PI = dyn_cast<Instruction>(P))
2657 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
2658 for (auto *U : PI->users())
2659 WorkList.push_back(cast<Value>(U));
2660 Put(PI, V);
2661 PI->replaceAllUsesWith(V);
2662 if (auto *PHI = dyn_cast<PHINode>(PI))
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002663 AllPhiNodes.remove(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002664 if (auto *Select = dyn_cast<SelectInst>(PI))
2665 AllSelectNodes.erase(Select);
2666 PI->eraseFromParent();
2667 }
2668 }
2669 return Get(Val);
2670 }
2671
2672 void Put(Value *From, Value *To) {
2673 Storage.insert({ From, To });
2674 }
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002675
2676 void ReplacePhi(PHINode *From, PHINode *To) {
2677 Value* OldReplacement = Get(From);
2678 while (OldReplacement != From) {
2679 From = To;
2680 To = dyn_cast<PHINode>(OldReplacement);
2681 OldReplacement = Get(From);
2682 }
2683 assert(Get(To) == To && "Replacement PHI node is already replaced.");
2684 Put(From, To);
2685 From->replaceAllUsesWith(To);
2686 AllPhiNodes.remove(From);
2687 From->eraseFromParent();
2688 }
2689
2690 SmallSetVector<PHINode *, 32>& newPhiNodes() { return AllPhiNodes; }
2691
2692 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
2693
2694 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
2695
2696 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
2697
2698 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
2699
2700 void destroyNewNodes(Type *CommonType) {
2701 // For safe erasing, replace the uses with dummy value first.
2702 auto Dummy = UndefValue::get(CommonType);
2703 for (auto I : AllPhiNodes) {
2704 I->replaceAllUsesWith(Dummy);
2705 I->eraseFromParent();
2706 }
2707 AllPhiNodes.clear();
2708 for (auto I : AllSelectNodes) {
2709 I->replaceAllUsesWith(Dummy);
2710 I->eraseFromParent();
2711 }
2712 AllSelectNodes.clear();
2713 }
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002714};
2715
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002716/// A helper class for combining addressing modes.
John Brawn736bf002017-10-03 13:08:22 +00002717class AddressingModeCombiner {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002718 typedef std::pair<Value *, BasicBlock *> ValueInBB;
2719 typedef DenseMap<ValueInBB, Value *> FoldAddrToValueMapping;
2720 typedef std::pair<PHINode *, PHINode *> PHIPair;
2721
John Brawn736bf002017-10-03 13:08:22 +00002722private:
2723 /// The addressing modes we've collected.
2724 SmallVector<ExtAddrMode, 16> AddrModes;
2725
2726 /// The field in which the AddrModes differ, when we have more than one.
2727 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
2728
2729 /// Are the AddrModes that we have all just equal to their original values?
2730 bool AllAddrModesTrivial = true;
2731
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002732 /// Common Type for all different fields in addressing modes.
2733 Type *CommonType;
2734
2735 /// SimplifyQuery for simplifyInstruction utility.
2736 const SimplifyQuery &SQ;
2737
2738 /// Original Address.
2739 ValueInBB Original;
2740
John Brawn736bf002017-10-03 13:08:22 +00002741public:
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002742 AddressingModeCombiner(const SimplifyQuery &_SQ, ValueInBB OriginalValue)
2743 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
2744
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002745 /// Get the combined AddrMode
John Brawn736bf002017-10-03 13:08:22 +00002746 const ExtAddrMode &getAddrMode() const {
2747 return AddrModes[0];
2748 }
2749
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002750 /// Add a new AddrMode if it's compatible with the AddrModes we already
John Brawn736bf002017-10-03 13:08:22 +00002751 /// have.
2752 /// \return True iff we succeeded in doing so.
2753 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
2754 // Take note of if we have any non-trivial AddrModes, as we need to detect
2755 // when all AddrModes are trivial as then we would introduce a phi or select
2756 // which just duplicates what's already there.
2757 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
2758
2759 // If this is the first addrmode then everything is fine.
2760 if (AddrModes.empty()) {
2761 AddrModes.emplace_back(NewAddrMode);
2762 return true;
2763 }
2764
2765 // Figure out how different this is from the other address modes, which we
2766 // can do just by comparing against the first one given that we only care
2767 // about the cumulative difference.
2768 ExtAddrMode::FieldName ThisDifferentField =
2769 AddrModes[0].compare(NewAddrMode);
2770 if (DifferentField == ExtAddrMode::NoField)
2771 DifferentField = ThisDifferentField;
2772 else if (DifferentField != ThisDifferentField)
2773 DifferentField = ExtAddrMode::MultipleFields;
2774
Serguei Katkov17e57942018-01-23 12:07:49 +00002775 // If NewAddrMode differs in more than one dimension we cannot handle it.
2776 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
2777
2778 // If Scale Field is different then we reject.
2779 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
2780
Serguei Katkov4d1dd6b2018-01-09 04:37:06 +00002781 // We also must reject the case when base offset is different and
2782 // scale reg is not null, we cannot handle this case due to merge of
2783 // different offsets will be used as ScaleReg.
Serguei Katkov17e57942018-01-23 12:07:49 +00002784 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
2785 !NewAddrMode.ScaledReg);
John Brawn736bf002017-10-03 13:08:22 +00002786
Serguei Katkov17e57942018-01-23 12:07:49 +00002787 // We also must reject the case when GV is different and BaseReg installed
2788 // due to we want to use base reg as a merge of GV values.
2789 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
2790 !NewAddrMode.HasBaseReg);
2791
2792 // Even if NewAddMode is the same we still need to collect it due to
2793 // original value is different. And later we will need all original values
2794 // as anchors during finding the common Phi node.
2795 if (CanHandle)
2796 AddrModes.emplace_back(NewAddrMode);
2797 else
2798 AddrModes.clear();
2799
2800 return CanHandle;
John Brawn736bf002017-10-03 13:08:22 +00002801 }
2802
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002803 /// Combine the addressing modes we've collected into a single
John Brawn736bf002017-10-03 13:08:22 +00002804 /// addressing mode.
2805 /// \return True iff we successfully combined them or we only had one so
2806 /// didn't need to combine them anyway.
2807 bool combineAddrModes() {
2808 // If we have no AddrModes then they can't be combined.
2809 if (AddrModes.size() == 0)
2810 return false;
2811
2812 // A single AddrMode can trivially be combined.
Serguei Katkov505359f2017-11-20 05:42:36 +00002813 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
John Brawn736bf002017-10-03 13:08:22 +00002814 return true;
2815
2816 // If the AddrModes we collected are all just equal to the value they are
2817 // derived from then combining them wouldn't do anything useful.
2818 if (AllAddrModesTrivial)
2819 return false;
2820
John Brawn70cdb5b2017-11-24 14:10:45 +00002821 if (!addrModeCombiningAllowed())
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002822 return false;
2823
2824 // Build a map between <original value, basic block where we saw it> to
2825 // value of base register.
Serguei Katkov50364592017-11-29 05:51:26 +00002826 // Bail out if there is no common type.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002827 FoldAddrToValueMapping Map;
Serguei Katkov50364592017-11-29 05:51:26 +00002828 if (!initializeMap(Map))
2829 return false;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002830
2831 Value *CommonValue = findCommon(Map);
2832 if (CommonValue)
John Brawn70cdb5b2017-11-24 14:10:45 +00002833 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002834 return CommonValue != nullptr;
2835 }
2836
2837private:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002838 /// Initialize Map with anchor values. For address seen in some BB
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002839 /// we set the value of different field saw in this address.
2840 /// If address is not an instruction than basic block is set to null.
2841 /// At the same time we find a common type for different field we will
2842 /// use to create new Phi/Select nodes. Keep it in CommonType field.
Serguei Katkov50364592017-11-29 05:51:26 +00002843 /// Return false if there is no common type found.
2844 bool initializeMap(FoldAddrToValueMapping &Map) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002845 // Keep track of keys where the value is null. We will need to replace it
2846 // with constant null when we know the common type.
2847 SmallVector<ValueInBB, 2> NullValue;
John Brawn70cdb5b2017-11-24 14:10:45 +00002848 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002849 for (auto &AM : AddrModes) {
2850 BasicBlock *BB = nullptr;
2851 if (Instruction *I = dyn_cast<Instruction>(AM.OriginalValue))
2852 BB = I->getParent();
2853
John Brawn70cdb5b2017-11-24 14:10:45 +00002854 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002855 if (DV) {
Serguei Katkov50364592017-11-29 05:51:26 +00002856 auto *Type = DV->getType();
2857 if (CommonType && CommonType != Type)
2858 return false;
2859 CommonType = Type;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002860 Map[{ AM.OriginalValue, BB }] = DV;
2861 } else {
2862 NullValue.push_back({ AM.OriginalValue, BB });
2863 }
2864 }
2865 assert(CommonType && "At least one non-null value must be!");
2866 for (auto VIBB : NullValue)
2867 Map[VIBB] = Constant::getNullValue(CommonType);
Serguei Katkov50364592017-11-29 05:51:26 +00002868 return true;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002869 }
2870
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002871 /// We have mapping between value A and basic block where value A
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002872 /// seen to other value B where B was a field in addressing mode represented
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002873 /// by A. Also we have an original value C representing an address in some
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002874 /// basic block. Traversing from C through phi and selects we ended up with
2875 /// A's in a map. This utility function tries to find a value V which is a
2876 /// field in addressing mode C and traversing through phi nodes and selects
2877 /// we will end up in corresponded values B in a map.
2878 /// The utility will create a new Phi/Selects if needed.
2879 // The simple example looks as follows:
2880 // BB1:
2881 // p1 = b1 + 40
2882 // br cond BB2, BB3
2883 // BB2:
2884 // p2 = b2 + 40
2885 // br BB3
2886 // BB3:
2887 // p = phi [p1, BB1], [p2, BB2]
2888 // v = load p
2889 // Map is
2890 // <p1, BB1> -> b1
2891 // <p2, BB2> -> b2
2892 // Request is
2893 // <p, BB3> -> ?
2894 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3
2895 Value *findCommon(FoldAddrToValueMapping &Map) {
Eric Christopherd72f78e2018-01-09 23:25:38 +00002896 // Tracks the simplification of newly created phi nodes. The reason we use
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002897 // this mapping is because we will add new created Phi nodes in AddrToBase.
2898 // Simplification of Phi nodes is recursive, so some Phi node may
2899 // be simplified after we added it to AddrToBase.
2900 // Using this mapping we can find the current value in AddrToBase.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002901 SimplificationTracker ST(SQ);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002902
2903 // First step, DFS to create PHI nodes for all intermediate blocks.
2904 // Also fill traverse order for the second step.
2905 SmallVector<ValueInBB, 32> TraverseOrder;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002906 InsertPlaceholders(Map, TraverseOrder, ST);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002907
2908 // Second Step, fill new nodes by merged values and simplify if possible.
2909 FillPlaceholders(Map, TraverseOrder, ST);
2910
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002911 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
2912 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002913 return nullptr;
2914 }
2915
2916 // Now we'd like to match New Phi nodes to existed ones.
2917 unsigned PhiNotMatchedCount = 0;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002918 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
2919 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002920 return nullptr;
2921 }
2922
2923 auto *Result = ST.Get(Map.find(Original)->second);
2924 if (Result) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002925 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
2926 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002927 }
2928 return Result;
2929 }
2930
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002931 /// Try to match PHI node to Candidate.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002932 /// Matcher tracks the matched Phi nodes.
2933 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002934 SmallSetVector<PHIPair, 8> &Matcher,
2935 SmallSetVector<PHINode *, 32> &PhiNodesToMatch) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002936 SmallVector<PHIPair, 8> WorkList;
2937 Matcher.insert({ PHI, Candidate });
2938 WorkList.push_back({ PHI, Candidate });
2939 SmallSet<PHIPair, 8> Visited;
2940 while (!WorkList.empty()) {
2941 auto Item = WorkList.pop_back_val();
2942 if (!Visited.insert(Item).second)
2943 continue;
2944 // We iterate over all incoming values to Phi to compare them.
2945 // If values are different and both of them Phi and the first one is a
2946 // Phi we added (subject to match) and both of them is in the same basic
2947 // block then we can match our pair if values match. So we state that
2948 // these values match and add it to work list to verify that.
2949 for (auto B : Item.first->blocks()) {
2950 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
2951 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
2952 if (FirstValue == SecondValue)
2953 continue;
2954
2955 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
2956 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
2957
2958 // One of them is not Phi or
2959 // The first one is not Phi node from the set we'd like to match or
2960 // Phi nodes from different basic blocks then
2961 // we will not be able to match.
2962 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
2963 FirstPhi->getParent() != SecondPhi->getParent())
2964 return false;
2965
2966 // If we already matched them then continue.
2967 if (Matcher.count({ FirstPhi, SecondPhi }))
2968 continue;
2969 // So the values are different and does not match. So we need them to
2970 // match.
2971 Matcher.insert({ FirstPhi, SecondPhi });
2972 // But me must check it.
2973 WorkList.push_back({ FirstPhi, SecondPhi });
2974 }
2975 }
2976 return true;
2977 }
2978
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002979 /// For the given set of PHI nodes (in the SimplificationTracker) try
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002980 /// to find their equivalents.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002981 /// Returns false if this matching fails and creation of new Phi is disabled.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002982 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002983 unsigned &PhiNotMatchedCount) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002984 // Use a SetVector for Matched to make sure we do replacements (ReplacePhi)
2985 // in a deterministic order below.
2986 SmallSetVector<PHIPair, 8> Matched;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002987 SmallPtrSet<PHINode *, 8> WillNotMatch;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002988 SmallSetVector<PHINode *, 32> &PhiNodesToMatch = ST.newPhiNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002989 while (PhiNodesToMatch.size()) {
2990 PHINode *PHI = *PhiNodesToMatch.begin();
2991
2992 // Add us, if no Phi nodes in the basic block we do not match.
2993 WillNotMatch.clear();
2994 WillNotMatch.insert(PHI);
2995
2996 // Traverse all Phis until we found equivalent or fail to do that.
2997 bool IsMatched = false;
2998 for (auto &P : PHI->getParent()->phis()) {
2999 if (&P == PHI)
3000 continue;
3001 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3002 break;
3003 // If it does not match, collect all Phi nodes from matcher.
3004 // if we end up with no match, them all these Phi nodes will not match
3005 // later.
3006 for (auto M : Matched)
3007 WillNotMatch.insert(M.first);
3008 Matched.clear();
3009 }
3010 if (IsMatched) {
Serguei Katkova20e05b2018-03-12 03:50:07 +00003011 // Replace all matched values and erase them.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003012 for (auto MV : Matched)
3013 ST.ReplacePhi(MV.first, MV.second);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003014 Matched.clear();
3015 continue;
3016 }
3017 // If we are not allowed to create new nodes then bail out.
3018 if (!AllowNewPhiNodes)
3019 return false;
3020 // Just remove all seen values in matcher. They will not match anything.
3021 PhiNotMatchedCount += WillNotMatch.size();
3022 for (auto *P : WillNotMatch)
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003023 PhiNodesToMatch.remove(P);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003024 }
3025 return true;
3026 }
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003027 /// Fill the placeholder with values from predecessors and simplify it.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003028 void FillPlaceholders(FoldAddrToValueMapping &Map,
3029 SmallVectorImpl<ValueInBB> &TraverseOrder,
3030 SimplificationTracker &ST) {
3031 while (!TraverseOrder.empty()) {
3032 auto Current = TraverseOrder.pop_back_val();
3033 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
3034 Value *CurrentValue = Current.first;
3035 BasicBlock *CurrentBlock = Current.second;
3036 Value *V = Map[Current];
3037
3038 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3039 // CurrentValue also must be Select.
3040 auto *CurrentSelect = cast<SelectInst>(CurrentValue);
3041 auto *TrueValue = CurrentSelect->getTrueValue();
3042 ValueInBB TrueItem = { TrueValue, isa<Instruction>(TrueValue)
3043 ? CurrentBlock
3044 : nullptr };
3045 assert(Map.find(TrueItem) != Map.end() && "No True Value!");
Serguei Katkovb0b67a82017-12-18 04:25:07 +00003046 Select->setTrueValue(ST.Get(Map[TrueItem]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003047 auto *FalseValue = CurrentSelect->getFalseValue();
3048 ValueInBB FalseItem = { FalseValue, isa<Instruction>(FalseValue)
3049 ? CurrentBlock
3050 : nullptr };
3051 assert(Map.find(FalseItem) != Map.end() && "No False Value!");
Serguei Katkovb0b67a82017-12-18 04:25:07 +00003052 Select->setFalseValue(ST.Get(Map[FalseItem]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003053 } else {
3054 // Must be a Phi node then.
3055 PHINode *PHI = cast<PHINode>(V);
3056 // Fill the Phi node with values from predecessors.
3057 bool IsDefinedInThisBB =
3058 cast<Instruction>(CurrentValue)->getParent() == CurrentBlock;
3059 auto *CurrentPhi = dyn_cast<PHINode>(CurrentValue);
3060 for (auto B : predecessors(CurrentBlock)) {
3061 Value *PV = IsDefinedInThisBB
3062 ? CurrentPhi->getIncomingValueForBlock(B)
3063 : CurrentValue;
3064 ValueInBB item = { PV, isa<Instruction>(PV) ? B : nullptr };
3065 assert(Map.find(item) != Map.end() && "No predecessor Value!");
3066 PHI->addIncoming(ST.Get(Map[item]), B);
3067 }
3068 }
3069 // Simplify if possible.
3070 Map[Current] = ST.Simplify(V);
3071 }
3072 }
3073
3074 /// Starting from value recursively iterates over predecessors up to known
3075 /// ending values represented in a map. For each traversed block inserts
3076 /// a placeholder Phi or Select.
3077 /// Reports all new created Phi/Select nodes by adding them to set.
3078 /// Also reports and order in what basic blocks have been traversed.
3079 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3080 SmallVectorImpl<ValueInBB> &TraverseOrder,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003081 SimplificationTracker &ST) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003082 SmallVector<ValueInBB, 32> Worklist;
3083 assert((isa<PHINode>(Original.first) || isa<SelectInst>(Original.first)) &&
3084 "Address must be a Phi or Select node");
3085 auto *Dummy = UndefValue::get(CommonType);
3086 Worklist.push_back(Original);
3087 while (!Worklist.empty()) {
3088 auto Current = Worklist.pop_back_val();
3089 // If value is not an instruction it is something global, constant,
3090 // parameter and we can say that this value is observable in any block.
3091 // Set block to null to denote it.
3092 // Also please take into account that it is how we build anchors.
3093 if (!isa<Instruction>(Current.first))
3094 Current.second = nullptr;
3095 // if it is already visited or it is an ending value then skip it.
3096 if (Map.find(Current) != Map.end())
3097 continue;
3098 TraverseOrder.push_back(Current);
3099
3100 Value *CurrentValue = Current.first;
3101 BasicBlock *CurrentBlock = Current.second;
3102 // CurrentValue must be a Phi node or select. All others must be covered
3103 // by anchors.
3104 Instruction *CurrentI = cast<Instruction>(CurrentValue);
3105 bool IsDefinedInThisBB = CurrentI->getParent() == CurrentBlock;
3106
Vedant Kumare0b5f862018-05-10 23:01:54 +00003107 unsigned PredCount = pred_size(CurrentBlock);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003108 // if Current Value is not defined in this basic block we are interested
3109 // in values in predecessors.
3110 if (!IsDefinedInThisBB) {
3111 assert(PredCount && "Unreachable block?!");
3112 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3113 &CurrentBlock->front());
3114 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003115 ST.insertNewPhi(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003116 // Add all predecessors in work list.
3117 for (auto B : predecessors(CurrentBlock))
3118 Worklist.push_back({ CurrentValue, B });
3119 continue;
3120 }
3121 // Value is defined in this basic block.
3122 if (SelectInst *OrigSelect = dyn_cast<SelectInst>(CurrentI)) {
3123 // Is it OK to get metadata from OrigSelect?!
3124 // Create a Select placeholder with dummy value.
3125 SelectInst *Select =
3126 SelectInst::Create(OrigSelect->getCondition(), Dummy, Dummy,
3127 OrigSelect->getName(), OrigSelect, OrigSelect);
3128 Map[Current] = Select;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003129 ST.insertNewSelect(Select);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003130 // We are interested in True and False value in this basic block.
3131 Worklist.push_back({ OrigSelect->getTrueValue(), CurrentBlock });
3132 Worklist.push_back({ OrigSelect->getFalseValue(), CurrentBlock });
3133 } else {
3134 // It must be a Phi node then.
3135 auto *CurrentPhi = cast<PHINode>(CurrentI);
3136 // Create new Phi node for merge of bases.
3137 assert(PredCount && "Unreachable block?!");
3138 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3139 &CurrentBlock->front());
3140 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003141 ST.insertNewPhi(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003142
3143 // Add all predecessors in work list.
3144 for (auto B : predecessors(CurrentBlock))
3145 Worklist.push_back({ CurrentPhi->getIncomingValueForBlock(B), B });
3146 }
3147 }
John Brawn736bf002017-10-03 13:08:22 +00003148 }
John Brawn70cdb5b2017-11-24 14:10:45 +00003149
3150 bool addrModeCombiningAllowed() {
3151 if (DisableComplexAddrModes)
3152 return false;
3153 switch (DifferentField) {
3154 default:
3155 return false;
3156 case ExtAddrMode::BaseRegField:
3157 return AddrSinkCombineBaseReg;
3158 case ExtAddrMode::BaseGVField:
3159 return AddrSinkCombineBaseGV;
3160 case ExtAddrMode::BaseOffsField:
3161 return AddrSinkCombineBaseOffs;
3162 case ExtAddrMode::ScaledRegField:
3163 return AddrSinkCombineScaledReg;
3164 }
3165 }
John Brawn736bf002017-10-03 13:08:22 +00003166};
Eugene Zelenko900b6332017-08-29 22:32:07 +00003167} // end anonymous namespace
3168
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003169/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003170/// Return true and update AddrMode if this addr mode is legal for the target,
3171/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003172bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003173 unsigned Depth) {
3174 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3175 // mode. Just process that directly.
3176 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003177 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003178
Chandler Carruthc8925912013-01-05 02:09:22 +00003179 // If the scale is 0, it takes nothing to add this.
3180 if (Scale == 0)
3181 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003182
Chandler Carruthc8925912013-01-05 02:09:22 +00003183 // If we already have a scale of this value, we can add to it, otherwise, we
3184 // need an available scale field.
3185 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3186 return false;
3187
3188 ExtAddrMode TestAddrMode = AddrMode;
3189
3190 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3191 // [A+B + A*7] -> [B+A*8].
3192 TestAddrMode.Scale += Scale;
3193 TestAddrMode.ScaledReg = ScaleReg;
3194
3195 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003196 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003197 return false;
3198
3199 // It was legal, so commit it.
3200 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003201
Chandler Carruthc8925912013-01-05 02:09:22 +00003202 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3203 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3204 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003205 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003206 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3207 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3208 TestAddrMode.ScaledReg = AddLHS;
3209 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003210
Chandler Carruthc8925912013-01-05 02:09:22 +00003211 // If this addressing mode is legal, commit it and remember that we folded
3212 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003213 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003214 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3215 AddrMode = TestAddrMode;
3216 return true;
3217 }
3218 }
3219
3220 // Otherwise, not (x+c)*scale, just return what we have.
3221 return true;
3222}
3223
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003224/// This is a little filter, which returns true if an addressing computation
3225/// involving I might be folded into a load/store accessing it.
3226/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003227/// the set of instructions that MatchOperationAddr can.
3228static bool MightBeFoldableInst(Instruction *I) {
3229 switch (I->getOpcode()) {
3230 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003231 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003232 // Don't touch identity bitcasts.
3233 if (I->getType() == I->getOperand(0)->getType())
3234 return false;
3235 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3236 case Instruction::PtrToInt:
3237 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3238 return true;
3239 case Instruction::IntToPtr:
3240 // We know the input is intptr_t, so this is foldable.
3241 return true;
3242 case Instruction::Add:
3243 return true;
3244 case Instruction::Mul:
3245 case Instruction::Shl:
3246 // Can only handle X*C and X << C.
3247 return isa<ConstantInt>(I->getOperand(1));
3248 case Instruction::GetElementPtr:
3249 return true;
3250 default:
3251 return false;
3252 }
3253}
3254
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003255/// Check whether or not \p Val is a legal instruction for \p TLI.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003256/// \note \p Val is assumed to be the product of some type promotion.
3257/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3258/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003259static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3260 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003261 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3262 if (!PromotedInst)
3263 return false;
3264 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3265 // If the ISDOpcode is undefined, it was undefined before the promotion.
3266 if (!ISDOpcode)
3267 return true;
3268 // Otherwise, check if the promoted instruction is legal or not.
3269 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003270 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003271}
3272
Eugene Zelenko900b6332017-08-29 22:32:07 +00003273namespace {
3274
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003275/// Hepler class to perform type promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003276class TypePromotionHelper {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003277 /// Utility function to check whether or not a sign or zero extension
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003278 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3279 /// either using the operands of \p Inst or promoting \p Inst.
3280 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003281 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003282 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003283 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003284 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003285 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003286 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003287 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003288 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3289 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003290
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003291 /// Utility function to determine if \p OpIdx should be promoted when
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003292 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003293 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003294 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003295 }
3296
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003297 /// Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003298 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003299 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003300 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003301 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003302 /// Newly added extensions are inserted in \p Exts.
3303 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003304 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003305 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003306 static Value *promoteOperandForTruncAndAnyExt(
3307 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003308 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003309 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003310 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003311
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003312 /// Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003313 /// operand is promotable and is not a supported trunc or sext.
3314 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003315 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003316 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003317 /// Newly added extensions are inserted in \p Exts.
3318 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003319 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003320 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003321 static Value *promoteOperandForOther(Instruction *Ext,
3322 TypePromotionTransaction &TPT,
3323 InstrToOrigTy &PromotedInsts,
3324 unsigned &CreatedInstsCost,
3325 SmallVectorImpl<Instruction *> *Exts,
3326 SmallVectorImpl<Instruction *> *Truncs,
3327 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003328
3329 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003330 static Value *signExtendOperandForOther(
3331 Instruction *Ext, TypePromotionTransaction &TPT,
3332 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3333 SmallVectorImpl<Instruction *> *Exts,
3334 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3335 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3336 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003337 }
3338
3339 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003340 static Value *zeroExtendOperandForOther(
3341 Instruction *Ext, TypePromotionTransaction &TPT,
3342 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3343 SmallVectorImpl<Instruction *> *Exts,
3344 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3345 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3346 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003347 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003348
3349public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003350 /// Type for the utility function that promotes the operand of Ext.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003351 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3352 InstrToOrigTy &PromotedInsts,
3353 unsigned &CreatedInstsCost,
3354 SmallVectorImpl<Instruction *> *Exts,
3355 SmallVectorImpl<Instruction *> *Truncs,
3356 const TargetLowering &TLI);
3357
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003358 /// Given a sign/zero extend instruction \p Ext, return the appropriate
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003359 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003360 /// \return NULL if no promotable action is possible with the current
3361 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003362 /// \p InsertedInsts keeps track of all the instructions inserted by the
3363 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003364 /// because we do not want to promote these instructions as CodeGenPrepare
3365 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3366 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003367 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003368 const TargetLowering &TLI,
3369 const InstrToOrigTy &PromotedInsts);
3370};
3371
Eugene Zelenko900b6332017-08-29 22:32:07 +00003372} // end anonymous namespace
3373
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003374bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003375 Type *ConsideredExtType,
3376 const InstrToOrigTy &PromotedInsts,
3377 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003378 // The promotion helper does not know how to deal with vector types yet.
3379 // To be able to fix that, we would need to fix the places where we
3380 // statically extend, e.g., constants and such.
3381 if (Inst->getType()->isVectorTy())
3382 return false;
3383
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003384 // We can always get through zext.
3385 if (isa<ZExtInst>(Inst))
3386 return true;
3387
3388 // sext(sext) is ok too.
3389 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003390 return true;
3391
3392 // We can get through binary operator, if it is legal. In other words, the
3393 // binary operator must have a nuw or nsw flag.
3394 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3395 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003396 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3397 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003398 return true;
3399
Guozhi Weic4c6b542018-06-05 21:03:52 +00003400 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
3401 if ((Inst->getOpcode() == Instruction::And ||
3402 Inst->getOpcode() == Instruction::Or))
3403 return true;
3404
3405 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
3406 if (Inst->getOpcode() == Instruction::Xor) {
3407 const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1));
3408 // Make sure it is not a NOT.
3409 if (Cst && !Cst->getValue().isAllOnesValue())
3410 return true;
3411 }
3412
3413 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
3414 // It may change a poisoned value into a regular value, like
3415 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
3416 // poisoned value regular value
3417 // It should be OK since undef covers valid value.
3418 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
3419 return true;
3420
3421 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
3422 // It may change a poisoned value into a regular value, like
3423 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
3424 // poisoned value regular value
3425 // It should be OK since undef covers valid value.
3426 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
3427 const Instruction *ExtInst =
3428 dyn_cast<const Instruction>(*Inst->user_begin());
3429 if (ExtInst->hasOneUse()) {
3430 const Instruction *AndInst =
3431 dyn_cast<const Instruction>(*ExtInst->user_begin());
3432 if (AndInst && AndInst->getOpcode() == Instruction::And) {
3433 const ConstantInt *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
3434 if (Cst &&
3435 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
3436 return true;
3437 }
3438 }
3439 }
3440
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003441 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003442 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003443 if (!isa<TruncInst>(Inst))
3444 return false;
3445
3446 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003447 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003448 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003449 if (!OpndVal->getType()->isIntegerTy() ||
3450 OpndVal->getType()->getIntegerBitWidth() >
3451 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003452 return false;
3453
3454 // If the operand of the truncate is not an instruction, we will not have
3455 // any information on the dropped bits.
3456 // (Actually we could for constant but it is not worth the extra logic).
3457 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3458 if (!Opnd)
3459 return false;
3460
3461 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003462 // I.e., check that trunc just drops extended bits of the same kind of
3463 // the extension.
3464 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003465 const Type *OpndType;
3466 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003467 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3468 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003469 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3470 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003471 else
3472 return false;
3473
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003474 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003475 return Inst->getType()->getIntegerBitWidth() >=
3476 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003477}
3478
3479TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003480 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003481 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003482 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3483 "Unexpected instruction type");
3484 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3485 Type *ExtTy = Ext->getType();
3486 bool IsSExt = isa<SExtInst>(Ext);
3487 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003488 // get through.
3489 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003490 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003491 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003492
3493 // Do not promote if the operand has been added by codegenprepare.
3494 // Otherwise, it means we are undoing an optimization that is likely to be
3495 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003496 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003497 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003498
3499 // SExt or Trunc instructions.
3500 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003501 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3502 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003503 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003504
3505 // Regular instruction.
3506 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003507 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003508 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003509 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003510}
3511
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003512Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003513 Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003514 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003515 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003516 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003517 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3518 // get through it and this method should not be called.
3519 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003520 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003521 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003522 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003523 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003524 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003525 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003526 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003527 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3528 TPT.replaceAllUsesWith(SExt, ZExt);
3529 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003530 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003531 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003532 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3533 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003534 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3535 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003536 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003537
3538 // Remove dead code.
3539 if (SExtOpnd->use_empty())
3540 TPT.eraseInstruction(SExtOpnd);
3541
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003542 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003543 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003544 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003545 if (ExtInst) {
3546 if (Exts)
3547 Exts->push_back(ExtInst);
3548 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3549 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003550 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003551 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003552
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003553 // At this point we have: ext ty opnd to ty.
3554 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3555 Value *NextVal = ExtInst->getOperand(0);
3556 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003557 return NextVal;
3558}
3559
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003560Value *TypePromotionHelper::promoteOperandForOther(
3561 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003562 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003563 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003564 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3565 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003566 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003567 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003568 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003569 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003570 if (!ExtOpnd->hasOneUse()) {
3571 // ExtOpnd will be promoted.
3572 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003573 // promoted version.
3574 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003575 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003576 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
Quentin Colombetac55b152014-09-16 22:36:07 +00003577 // Insert it just after the definition.
Sanjay Patel674d2c22017-08-29 14:07:48 +00003578 ITrunc->moveAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003579 if (Truncs)
3580 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003581 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003582
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003583 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003584 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003585 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003586 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003587 }
3588
3589 // Get through the Instruction:
3590 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003591 // 2. Replace the uses of Ext by Inst.
3592 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003593
3594 // Remember the original type of the instruction before promotion.
3595 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003596 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3597 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003598 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003599 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003600 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003601 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003602 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003603 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003604
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003605 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003606 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003607 ++OpIdx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003608 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003609 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3610 !shouldExtOperand(ExtOpnd, OpIdx)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003611 LLVM_DEBUG(dbgs() << "No need to propagate\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003612 continue;
3613 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003614 // Check if we can statically extend the operand.
3615 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003616 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003617 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003618 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3619 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3620 : Cst->getValue().zext(BitWidth);
3621 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003622 continue;
3623 }
3624 // UndefValue are typed, so we have to statically sign extend them.
3625 if (isa<UndefValue>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003626 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003627 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003628 continue;
3629 }
3630
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003631 // Otherwise we have to explicitly sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003632 // Check if Ext was reused to extend an operand.
3633 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003634 // If yes, create a new one.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003635 LLVM_DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003636 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3637 : TPT.createZExt(Ext, Opnd, Ext->getType());
3638 if (!isa<Instruction>(ValForExtOpnd)) {
3639 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3640 continue;
3641 }
3642 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003643 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003644 if (Exts)
3645 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003646 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003647
3648 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003649 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3650 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003651 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003652 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003653 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003654 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003655 if (ExtForOpnd == Ext) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003656 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003657 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003658 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003659 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003660}
3661
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003662/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003663/// \p NewCost gives the cost of extension instructions created by the
3664/// promotion.
3665/// \p OldCost gives the cost of extension instructions before the promotion
3666/// plus the number of instructions that have been
3667/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003668/// \p PromotedOperand is the value that has been promoted.
3669/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003670bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003671 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003672 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
3673 << '\n');
Quentin Colombet1b274f92015-03-10 21:48:15 +00003674 // The cost of the new extensions is greater than the cost of the
3675 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003676 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003677 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003678 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003679 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003680 return true;
3681 // The promotion is neutral but it may help folding the sign extension in
3682 // loads for instance.
3683 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003684 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003685}
3686
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003687/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003688/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003689/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003690/// If \p MovedAway is not NULL, it contains the information of whether or
3691/// not AddrInst has to be folded into the addressing mode on success.
3692/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3693/// because it has been moved away.
3694/// Thus AddrInst must not be added in the matched instructions.
3695/// This state can happen when AddrInst is a sext, since it may be moved away.
3696/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3697/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003698bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003699 unsigned Depth,
3700 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003701 // Avoid exponential behavior on extremely deep expression trees.
3702 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003703
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003704 // By default, all matched instructions stay in place.
3705 if (MovedAway)
3706 *MovedAway = false;
3707
Chandler Carruthc8925912013-01-05 02:09:22 +00003708 switch (Opcode) {
3709 case Instruction::PtrToInt:
3710 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003711 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003712 case Instruction::IntToPtr: {
3713 auto AS = AddrInst->getType()->getPointerAddressSpace();
3714 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003715 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003716 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003717 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003718 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003719 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003720 case Instruction::BitCast:
3721 // BitCast is always a noop, and we can handle it as long as it is
3722 // int->int or pointer->pointer (we don't want int<->fp or something).
3723 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3724 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3725 // Don't touch identity bitcasts. These were probably put here by LSR,
3726 // and we don't want to mess around with them. Assume it knows what it
3727 // is doing.
3728 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003729 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003730 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003731 case Instruction::AddrSpaceCast: {
3732 unsigned SrcAS
3733 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3734 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3735 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003736 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003737 return false;
3738 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003739 case Instruction::Add: {
3740 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3741 ExtAddrMode BackupAddrMode = AddrMode;
3742 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003743 // Start a transaction at this point.
3744 // The LHS may match but not the RHS.
3745 // Therefore, we need a higher level restoration point to undo partially
3746 // matched operation.
3747 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3748 TPT.getRestorationPoint();
3749
Sanjay Patelfc580a62015-09-21 23:03:16 +00003750 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3751 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003752 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003753
Chandler Carruthc8925912013-01-05 02:09:22 +00003754 // Restore the old addr mode info.
3755 AddrMode = BackupAddrMode;
3756 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003757 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003758
Chandler Carruthc8925912013-01-05 02:09:22 +00003759 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003760 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3761 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003762 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003763
Chandler Carruthc8925912013-01-05 02:09:22 +00003764 // Otherwise we definitely can't merge the ADD in.
3765 AddrMode = BackupAddrMode;
3766 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003767 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003768 break;
3769 }
3770 //case Instruction::Or:
3771 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3772 //break;
3773 case Instruction::Mul:
3774 case Instruction::Shl: {
3775 // Can only handle X*C and X << C.
3776 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Philip Reames9c3cbee2017-10-30 23:59:51 +00003777 if (!RHS || RHS->getBitWidth() > 64)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003778 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003779 int64_t Scale = RHS->getSExtValue();
3780 if (Opcode == Instruction::Shl)
3781 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003782
Sanjay Patelfc580a62015-09-21 23:03:16 +00003783 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003784 }
3785 case Instruction::GetElementPtr: {
3786 // Scan the GEP. We check it if it contains constant offsets and at most
3787 // one variable offset.
3788 int VariableOperand = -1;
3789 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003790
Chandler Carruthc8925912013-01-05 02:09:22 +00003791 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003792 gep_type_iterator GTI = gep_type_begin(AddrInst);
3793 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003794 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003795 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003796 unsigned Idx =
3797 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3798 ConstantOffset += SL->getElementOffset(Idx);
3799 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003800 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003801 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
Haicheng Wu0be88252017-12-19 20:53:32 +00003802 ConstantOffset += CI->getSExtValue() * TypeSize;
Chandler Carruthc8925912013-01-05 02:09:22 +00003803 } else if (TypeSize) { // Scales of zero don't do anything.
3804 // We only allow one variable index at the moment.
3805 if (VariableOperand != -1)
3806 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003807
Chandler Carruthc8925912013-01-05 02:09:22 +00003808 // Remember the variable index.
3809 VariableOperand = i;
3810 VariableScale = TypeSize;
3811 }
3812 }
3813 }
Stephen Lin837bba12013-07-15 17:55:02 +00003814
Chandler Carruthc8925912013-01-05 02:09:22 +00003815 // A common case is for the GEP to only do a constant offset. In this case,
3816 // just add it to the disp field and check validity.
3817 if (VariableOperand == -1) {
3818 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003819 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003820 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003821 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003822 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003823 return true;
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00003824 } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
3825 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
3826 ConstantOffset > 0) {
3827 // Record GEPs with non-zero offsets as candidates for splitting in the
3828 // event that the offset cannot fit into the r+i addressing mode.
3829 // Simple and common case that only one GEP is used in calculating the
3830 // address for the memory access.
3831 Value *Base = AddrInst->getOperand(0);
3832 auto *BaseI = dyn_cast<Instruction>(Base);
3833 auto *GEP = cast<GetElementPtrInst>(AddrInst);
3834 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
3835 (BaseI && !isa<CastInst>(BaseI) &&
3836 !isa<GetElementPtrInst>(BaseI))) {
3837 // If the base is an instruction, make sure the GEP is not in the same
3838 // basic block as the base. If the base is an argument or global
3839 // value, make sure the GEP is not in the entry block. Otherwise,
3840 // instruction selection can undo the split. Also make sure the
3841 // parent block allows inserting non-PHI instructions before the
3842 // terminator.
3843 BasicBlock *Parent =
3844 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
3845 if (GEP->getParent() != Parent && !Parent->getTerminator()->isEHPad())
3846 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
3847 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003848 }
3849 AddrMode.BaseOffs -= ConstantOffset;
3850 return false;
3851 }
3852
3853 // Save the valid addressing mode in case we can't match.
3854 ExtAddrMode BackupAddrMode = AddrMode;
3855 unsigned OldSize = AddrModeInsts.size();
3856
3857 // See if the scale and offset amount is valid for this target.
3858 AddrMode.BaseOffs += ConstantOffset;
3859
3860 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003861 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003862 // If it couldn't be matched, just stuff the value in a register.
3863 if (AddrMode.HasBaseReg) {
3864 AddrMode = BackupAddrMode;
3865 AddrModeInsts.resize(OldSize);
3866 return false;
3867 }
3868 AddrMode.HasBaseReg = true;
3869 AddrMode.BaseReg = AddrInst->getOperand(0);
3870 }
3871
3872 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003873 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003874 Depth)) {
3875 // If it couldn't be matched, try stuffing the base into a register
3876 // instead of matching it, and retrying the match of the scale.
3877 AddrMode = BackupAddrMode;
3878 AddrModeInsts.resize(OldSize);
3879 if (AddrMode.HasBaseReg)
3880 return false;
3881 AddrMode.HasBaseReg = true;
3882 AddrMode.BaseReg = AddrInst->getOperand(0);
3883 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003884 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003885 VariableScale, Depth)) {
3886 // If even that didn't work, bail.
3887 AddrMode = BackupAddrMode;
3888 AddrModeInsts.resize(OldSize);
3889 return false;
3890 }
3891 }
3892
3893 return true;
3894 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003895 case Instruction::SExt:
3896 case Instruction::ZExt: {
3897 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3898 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003899 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003900
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003901 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003902 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003903 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003904 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003905 if (!TPH)
3906 return false;
3907
3908 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3909 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003910 unsigned CreatedInstsCost = 0;
3911 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003912 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003913 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003914 // SExt has been moved away.
3915 // Thus either it will be rematched later in the recursive calls or it is
3916 // gone. Anyway, we must not fold it into the addressing mode at this point.
3917 // E.g.,
3918 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003919 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003920 // addr = gep base, idx
3921 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003922 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003923 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3924 // addr = gep base, op <- match
3925 if (MovedAway)
3926 *MovedAway = true;
3927
3928 assert(PromotedOperand &&
3929 "TypePromotionHelper should have filtered out those cases");
3930
3931 ExtAddrMode BackupAddrMode = AddrMode;
3932 unsigned OldSize = AddrModeInsts.size();
3933
Sanjay Patelfc580a62015-09-21 23:03:16 +00003934 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003935 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003936 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003937 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003938 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003939 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003940 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003941 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003942 AddrMode = BackupAddrMode;
3943 AddrModeInsts.resize(OldSize);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003944 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003945 TPT.rollback(LastKnownGood);
3946 return false;
3947 }
3948 return true;
3949 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003950 }
3951 return false;
3952}
3953
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003954/// If we can, try to add the value of 'Addr' into the current addressing mode.
3955/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3956/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3957/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003958///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003959bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003960 // Start a transaction at this point that we will rollback if the matching
3961 // fails.
3962 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3963 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003964 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3965 // Fold in immediates if legal for the target.
3966 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003967 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003968 return true;
3969 AddrMode.BaseOffs -= CI->getSExtValue();
3970 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3971 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003972 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003973 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003974 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003975 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003976 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003977 }
3978 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3979 ExtAddrMode BackupAddrMode = AddrMode;
3980 unsigned OldSize = AddrModeInsts.size();
3981
3982 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003983 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003984 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003985 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003986 // to check here.
3987 if (MovedAway)
3988 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003989 // Okay, it's possible to fold this. Check to see if it is actually
3990 // *profitable* to do so. We use a simple cost model to avoid increasing
3991 // register pressure too much.
3992 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003993 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003994 AddrModeInsts.push_back(I);
3995 return true;
3996 }
Stephen Lin837bba12013-07-15 17:55:02 +00003997
Chandler Carruthc8925912013-01-05 02:09:22 +00003998 // It isn't profitable to do this, roll back.
3999 //cerr << "NOT FOLDING: " << *I;
4000 AddrMode = BackupAddrMode;
4001 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004002 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004003 }
4004 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00004005 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00004006 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004007 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004008 } else if (isa<ConstantPointerNull>(Addr)) {
4009 // Null pointer gets folded without affecting the addressing mode.
4010 return true;
4011 }
4012
4013 // Worse case, the target should support [reg] addressing modes. :)
4014 if (!AddrMode.HasBaseReg) {
4015 AddrMode.HasBaseReg = true;
4016 AddrMode.BaseReg = Addr;
4017 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004018 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004019 return true;
4020 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00004021 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004022 }
4023
4024 // If the base register is already taken, see if we can do [r+r].
4025 if (AddrMode.Scale == 0) {
4026 AddrMode.Scale = 1;
4027 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004028 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004029 return true;
4030 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00004031 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004032 }
4033 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004034 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004035 return false;
4036}
4037
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004038/// Check to see if all uses of OpVal by the specified inline asm call are due
4039/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00004040static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004041 const TargetLowering &TLI,
4042 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00004043 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00004044 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004045 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004046 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004047
Chandler Carruthc8925912013-01-05 02:09:22 +00004048 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4049 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00004050
Chandler Carruthc8925912013-01-05 02:09:22 +00004051 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004052 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00004053
4054 // If this asm operand is our Value*, and if it isn't an indirect memory
4055 // operand, we can't fold it!
4056 if (OpInfo.CallOperandVal == OpVal &&
4057 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4058 !OpInfo.isIndirect))
4059 return false;
4060 }
4061
4062 return true;
4063}
4064
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004065// Max number of memory uses to look at before aborting the search to conserve
4066// compile time.
4067static constexpr int MaxMemoryUsesToScan = 20;
4068
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004069/// Recursively walk all the uses of I until we find a memory use.
4070/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00004071/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00004072static bool FindAllMemoryUses(
4073 Instruction *I,
4074 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004075 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4076 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004077 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00004078 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00004079 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004080
Chandler Carruthc8925912013-01-05 02:09:22 +00004081 // If this is an obviously unfoldable instruction, bail out.
4082 if (!MightBeFoldableInst(I))
4083 return true;
4084
Philip Reamesac115ed2016-03-09 23:13:12 +00004085 const bool OptSize = I->getFunction()->optForSize();
4086
Chandler Carruthc8925912013-01-05 02:09:22 +00004087 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004088 for (Use &U : I->uses()) {
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004089 // Conservatively return true if we're seeing a large number or a deep chain
4090 // of users. This avoids excessive compilation times in pathological cases.
4091 if (SeenInsts++ >= MaxMemoryUsesToScan)
4092 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004093
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004094 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthcdf47882014-03-09 03:16:01 +00004095 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4096 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00004097 continue;
4098 }
Stephen Lin837bba12013-07-15 17:55:02 +00004099
Chandler Carruthcdf47882014-03-09 03:16:01 +00004100 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4101 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00004102 if (opNo != StoreInst::getPointerOperandIndex())
4103 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00004104 MemoryUses.push_back(std::make_pair(SI, opNo));
4105 continue;
4106 }
Stephen Lin837bba12013-07-15 17:55:02 +00004107
Matt Arsenault02d915b2017-03-15 22:35:20 +00004108 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4109 unsigned opNo = U.getOperandNo();
4110 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4111 return true; // Storing addr, not into addr.
4112 MemoryUses.push_back(std::make_pair(RMW, opNo));
4113 continue;
4114 }
4115
4116 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4117 unsigned opNo = U.getOperandNo();
4118 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4119 return true; // Storing addr, not into addr.
4120 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4121 continue;
4122 }
4123
Chandler Carruthcdf47882014-03-09 03:16:01 +00004124 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004125 // If this is a cold call, we can sink the addressing calculation into
4126 // the cold path. See optimizeCallInst
4127 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4128 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004129
Chandler Carruthc8925912013-01-05 02:09:22 +00004130 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4131 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004132
Chandler Carruthc8925912013-01-05 02:09:22 +00004133 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004134 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004135 return true;
4136 continue;
4137 }
Stephen Lin837bba12013-07-15 17:55:02 +00004138
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004139 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4140 SeenInsts))
Chandler Carruthc8925912013-01-05 02:09:22 +00004141 return true;
4142 }
4143
4144 return false;
4145}
4146
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004147/// Return true if Val is already known to be live at the use site that we're
4148/// folding it into. If so, there is no cost to include it in the addressing
4149/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4150/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004151bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004152 Value *KnownLive2) {
4153 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004154 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004155 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004156
Chandler Carruthc8925912013-01-05 02:09:22 +00004157 // All values other than instructions and arguments (e.g. constants) are live.
4158 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004159
Chandler Carruthc8925912013-01-05 02:09:22 +00004160 // If Val is a constant sized alloca in the entry block, it is live, this is
4161 // true because it is just a reference to the stack/frame pointer, which is
4162 // live for the whole function.
4163 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4164 if (AI->isStaticAlloca())
4165 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004166
Chandler Carruthc8925912013-01-05 02:09:22 +00004167 // Check to see if this value is already used in the memory instruction's
4168 // block. If so, it's already live into the block at the very least, so we
4169 // can reasonably fold it.
4170 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4171}
4172
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004173/// It is possible for the addressing mode of the machine to fold the specified
4174/// instruction into a load or store that ultimately uses it.
4175/// However, the specified instruction has multiple uses.
4176/// Given this, it may actually increase register pressure to fold it
4177/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004178///
4179/// X = ...
4180/// Y = X+1
4181/// use(Y) -> nonload/store
4182/// Z = Y+1
4183/// load Z
4184///
4185/// In this case, Y has multiple uses, and can be folded into the load of Z
4186/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4187/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4188/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4189/// number of computations either.
4190///
4191/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4192/// X was live across 'load Z' for other reasons, we actually *would* want to
4193/// fold the addressing mode in the Z case. This would make Y die earlier.
4194bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004195isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004196 ExtAddrMode &AMAfter) {
4197 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004198
Chandler Carruthc8925912013-01-05 02:09:22 +00004199 // AMBefore is the addressing mode before this instruction was folded into it,
4200 // and AMAfter is the addressing mode after the instruction was folded. Get
4201 // the set of registers referenced by AMAfter and subtract out those
4202 // referenced by AMBefore: this is the set of values which folding in this
4203 // address extends the lifetime of.
4204 //
4205 // Note that there are only two potential values being referenced here,
4206 // BaseReg and ScaleReg (global addresses are always available, as are any
4207 // folded immediates).
4208 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004209
Chandler Carruthc8925912013-01-05 02:09:22 +00004210 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4211 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004212 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004213 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004214 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004215 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004216
4217 // If folding this instruction (and it's subexprs) didn't extend any live
4218 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004219 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004220 return true;
4221
Philip Reamesac115ed2016-03-09 23:13:12 +00004222 // If all uses of this instruction can have the address mode sunk into them,
4223 // we can remove the addressing mode and effectively trade one live register
4224 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004225 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004226 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4227 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004228 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004229 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004230
Chandler Carruthc8925912013-01-05 02:09:22 +00004231 // Now that we know that all uses of this instruction are part of a chain of
4232 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004233 // into a memory use, loop over each of these memory operation uses and see
4234 // if they could *actually* fold the instruction. The assumption is that
4235 // addressing modes are cheap and that duplicating the computation involved
4236 // many times is worthwhile, even on a fastpath. For sinking candidates
4237 // (i.e. cold call sites), this serves as a way to prevent excessive code
4238 // growth since most architectures have some reasonable small and fast way to
4239 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004240 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4241 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4242 Instruction *User = MemoryUses[i].first;
4243 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004244
Chandler Carruthc8925912013-01-05 02:09:22 +00004245 // Get the access type of this use. If the use isn't a pointer, we don't
4246 // know what it accesses.
4247 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004248 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4249 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004250 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004251 Type *AddressAccessTy = AddrTy->getElementType();
4252 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004253
Chandler Carruthc8925912013-01-05 02:09:22 +00004254 // Do a match against the root of this address, ignoring profitability. This
4255 // will tell us if the addressing mode for the memory operation will
4256 // *actually* cover the shared instruction.
4257 ExtAddrMode Result;
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004258 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4259 0);
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004260 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4261 TPT.getRestorationPoint();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004262 AddressingModeMatcher Matcher(
4263 MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result,
4264 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Chandler Carruthc8925912013-01-05 02:09:22 +00004265 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004266 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004267 (void)Success; assert(Success && "Couldn't select *anything*?");
4268
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004269 // The match was to check the profitability, the changes made are not
4270 // part of the original matcher. Therefore, they should be dropped
4271 // otherwise the original matcher will not present the right state.
4272 TPT.rollback(LastKnownGood);
4273
Chandler Carruthc8925912013-01-05 02:09:22 +00004274 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004275 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004276 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004277
Chandler Carruthc8925912013-01-05 02:09:22 +00004278 MatchedAddrModeInsts.clear();
4279 }
Stephen Lin837bba12013-07-15 17:55:02 +00004280
Chandler Carruthc8925912013-01-05 02:09:22 +00004281 return true;
4282}
4283
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004284/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004285/// different basic block than BB.
4286static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4287 if (Instruction *I = dyn_cast<Instruction>(V))
4288 return I->getParent() != BB;
4289 return false;
4290}
4291
Philip Reamesac115ed2016-03-09 23:13:12 +00004292/// Sink addressing mode computation immediate before MemoryInst if doing so
4293/// can be done without increasing register pressure. The need for the
4294/// register pressure constraint means this can end up being an all or nothing
4295/// decision for all uses of the same addressing computation.
4296///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004297/// Load and Store Instructions often have addressing modes that can do
4298/// significant amounts of computation. As such, instruction selection will try
4299/// to get the load or store to do as much computation as possible for the
4300/// program. The problem is that isel can only see within a single block. As
4301/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004302///
4303/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004304/// operands. It's also used to sink addressing computations feeding into cold
4305/// call sites into their (cold) basic block.
4306///
4307/// The motivation for handling sinking into cold blocks is that doing so can
4308/// both enable other address mode sinking (by satisfying the register pressure
4309/// constraint above), and reduce register pressure globally (by removing the
4310/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004311bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004312 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004313 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004314
4315 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004316 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004317 SmallVector<Value*, 8> worklist;
4318 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004319 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004320
John Brawneb83c752017-10-03 13:04:15 +00004321 // Use a worklist to iteratively look through PHI and select nodes, and
4322 // ensure that the addressing mode obtained from the non-PHI/select roots of
John Brawn736bf002017-10-03 13:08:22 +00004323 // the graph are compatible.
John Brawneb83c752017-10-03 13:04:15 +00004324 bool PhiOrSelectSeen = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004325 SmallVector<Instruction*, 16> AddrModeInsts;
Serguei Katkovaee63752017-11-05 07:59:02 +00004326 const SimplifyQuery SQ(*DL, TLInfo);
4327 AddressingModeCombiner AddrModes(SQ, { Addr, MemoryInst->getParent() });
Jun Bum Limdee55652017-04-03 19:20:07 +00004328 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004329 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4330 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004331 while (!worklist.empty()) {
4332 Value *V = worklist.back();
4333 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004334
Serguei Katkov4ea855e2017-07-19 04:49:17 +00004335 // We allow traversing cyclic Phi nodes.
4336 // In case of success after this loop we ensure that traversing through
4337 // Phi nodes ends up with all cases to compute address of the form
4338 // BaseGV + Base + Scale * Index + Offset
4339 // where Scale and Offset are constans and BaseGV, Base and Index
4340 // are exactly the same Values in all cases.
4341 // It means that BaseGV, Scale and Offset dominate our memory instruction
4342 // and have the same value as they had in address computation represented
4343 // as Phi. So we can safely sink address computation to memory instruction.
4344 if (!Visited.insert(V).second)
4345 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00004346
Owen Anderson8ba5f392010-11-27 08:15:55 +00004347 // For a PHI node, push all of its incoming values.
4348 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004349 for (Value *IncValue : P->incoming_values())
4350 worklist.push_back(IncValue);
John Brawneb83c752017-10-03 13:04:15 +00004351 PhiOrSelectSeen = true;
4352 continue;
4353 }
4354 // Similar for select.
4355 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4356 worklist.push_back(SI->getFalseValue());
4357 worklist.push_back(SI->getTrueValue());
4358 PhiOrSelectSeen = true;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004359 continue;
4360 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004361
Philip Reamesac115ed2016-03-09 23:13:12 +00004362 // For non-PHIs, determine the addressing mode being computed. Note that
4363 // the result may differ depending on what other uses our candidate
4364 // addressing instructions might have.
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004365 AddrModeInsts.clear();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004366 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4367 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004368 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004369 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004370 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004371
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004372 GetElementPtrInst *GEP = LargeOffsetGEP.first;
4373 if (GEP && GEP->getParent() != MemoryInst->getParent() &&
4374 !NewGEPBases.count(GEP)) {
4375 // If splitting the underlying data structure can reduce the offset of a
4376 // GEP, collect the GEP. Skip the GEPs that are the new bases of
4377 // previously split data structures.
4378 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
4379 if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
4380 LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
4381 }
4382
4383 NewAddrMode.OriginalValue = V;
John Brawn736bf002017-10-03 13:08:22 +00004384 if (!AddrModes.addNewAddrMode(NewAddrMode))
4385 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004386 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004387
John Brawn736bf002017-10-03 13:08:22 +00004388 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4389 // or we have multiple but either couldn't combine them or combining them
4390 // wouldn't do anything useful, bail out now.
4391 if (!AddrModes.combineAddrModes()) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004392 TPT.rollback(LastKnownGood);
4393 return false;
4394 }
4395 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004396
John Brawn736bf002017-10-03 13:08:22 +00004397 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4398 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4399
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004400 // If all the instructions matched are already in this BB, don't do anything.
John Brawneb83c752017-10-03 13:04:15 +00004401 // If we saw a Phi node then it is not local definitely, and if we saw a select
4402 // then we want to push the address calculation past it even if it's already
4403 // in this BB.
4404 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
Justin Lebar838c7f52016-11-21 22:49:11 +00004405 return IsNonLocalValue(V, MemoryInst->getParent());
Serguei Katkov0b7b59a2017-07-11 06:24:44 +00004406 })) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004407 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
4408 << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004409 return false;
4410 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004411
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004412 // Insert this computation right after this user. Since our caller is
4413 // scanning from the top of the BB to the bottom, reuse of the expr are
4414 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004415 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004416
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004417 // Now that we determined the addressing expression we want to use and know
4418 // that we have to sink it into this block. Check to see if we have already
Simon Dardis230f4532017-11-24 16:45:28 +00004419 // done this for some other load/store instr in this block. If so, reuse
4420 // the computation. Before attempting reuse, check if the address is valid
4421 // as it may have been erased.
4422
4423 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
4424
4425 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004426 if (SunkAddr) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004427 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
4428 << " for " << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004429 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004430 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004431 } else if (AddrSinkUsingGEPs ||
David Blaikie8ad9a972018-03-28 22:28:50 +00004432 (!AddrSinkUsingGEPs.getNumOccurrences() && TM && TTI->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004433 // By default, we use the GEP-based method when AA is used later. This
4434 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004435 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4436 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004437 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004438 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004439
4440 // First, find the pointer.
4441 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4442 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004443 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004444 }
4445
4446 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4447 // We can't add more than one pointer together, nor can we scale a
4448 // pointer (both of which seem meaningless).
4449 if (ResultPtr || AddrMode.Scale != 1)
4450 return false;
4451
4452 ResultPtr = AddrMode.ScaledReg;
4453 AddrMode.Scale = 0;
4454 }
4455
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004456 // It is only safe to sign extend the BaseReg if we know that the math
4457 // required to create it did not overflow before we extend it. Since
4458 // the original IR value was tossed in favor of a constant back when
4459 // the AddrMode was created we need to bail out gracefully if widths
4460 // do not match instead of extending it.
4461 //
4462 // (See below for code to add the scale.)
4463 if (AddrMode.Scale) {
4464 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4465 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4466 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4467 return false;
4468 }
4469
Hal Finkelc3998302014-04-12 00:59:48 +00004470 if (AddrMode.BaseGV) {
4471 if (ResultPtr)
4472 return false;
4473
4474 ResultPtr = AddrMode.BaseGV;
4475 }
4476
4477 // If the real base value actually came from an inttoptr, then the matcher
4478 // will look through it and provide only the integer value. In that case,
4479 // use it here.
Keno Fischer05e4ac22017-06-29 20:28:59 +00004480 if (!DL->isNonIntegralPointerType(Addr->getType())) {
4481 if (!ResultPtr && AddrMode.BaseReg) {
4482 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4483 "sunkaddr");
4484 AddrMode.BaseReg = nullptr;
4485 } else if (!ResultPtr && AddrMode.Scale == 1) {
4486 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4487 "sunkaddr");
4488 AddrMode.Scale = 0;
4489 }
Hal Finkelc3998302014-04-12 00:59:48 +00004490 }
4491
4492 if (!ResultPtr &&
4493 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4494 SunkAddr = Constant::getNullValue(Addr->getType());
4495 } else if (!ResultPtr) {
4496 return false;
4497 } else {
4498 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004499 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4500 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004501
4502 // Start with the base register. Do this first so that subsequent address
4503 // matching finds it last, which will prevent it from trying to match it
4504 // as the scaled value in case it happens to be a mul. That would be
4505 // problematic if we've sunk a different mul for the scale, because then
4506 // we'd end up sinking both muls.
4507 if (AddrMode.BaseReg) {
4508 Value *V = AddrMode.BaseReg;
4509 if (V->getType() != IntPtrTy)
4510 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4511
4512 ResultIndex = V;
4513 }
4514
4515 // Add the scale value.
4516 if (AddrMode.Scale) {
4517 Value *V = AddrMode.ScaledReg;
4518 if (V->getType() == IntPtrTy) {
4519 // done.
Hal Finkelc3998302014-04-12 00:59:48 +00004520 } else {
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004521 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4522 cast<IntegerType>(V->getType())->getBitWidth() &&
4523 "We can't transform if ScaledReg is too narrow");
4524 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004525 }
4526
4527 if (AddrMode.Scale != 1)
4528 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4529 "sunkaddr");
4530 if (ResultIndex)
4531 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4532 else
4533 ResultIndex = V;
4534 }
4535
4536 // Add in the Base Offset if present.
4537 if (AddrMode.BaseOffs) {
4538 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4539 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004540 // We need to add this separately from the scale above to help with
4541 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004542 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004543 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004544 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004545 }
4546
4547 ResultIndex = V;
4548 }
4549
4550 if (!ResultIndex) {
4551 SunkAddr = ResultPtr;
4552 } else {
4553 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004554 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004555 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004556 }
4557
4558 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004559 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004560 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004561 } else {
Keno Fischer05e4ac22017-06-29 20:28:59 +00004562 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4563 // non-integral pointers, so in that case bail out now.
4564 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4565 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4566 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4567 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4568 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4569 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4570 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4571 (AddrMode.BaseGV &&
4572 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4573 return false;
4574
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004575 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4576 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004577 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004578 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004579
4580 // Start with the base register. Do this first so that subsequent address
4581 // matching finds it last, which will prevent it from trying to match it
4582 // as the scaled value in case it happens to be a mul. That would be
4583 // problematic if we've sunk a different mul for the scale, because then
4584 // we'd end up sinking both muls.
4585 if (AddrMode.BaseReg) {
4586 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004587 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004588 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004589 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004590 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004591 Result = V;
4592 }
4593
4594 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004595 if (AddrMode.Scale) {
4596 Value *V = AddrMode.ScaledReg;
4597 if (V->getType() == IntPtrTy) {
4598 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004599 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004600 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004601 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4602 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004603 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004604 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004605 // It is only safe to sign extend the BaseReg if we know that the math
4606 // required to create it did not overflow before we extend it. Since
4607 // the original IR value was tossed in favor of a constant back when
4608 // the AddrMode was created we need to bail out gracefully if widths
4609 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004610 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004611 if (I && (Result != AddrMode.BaseReg))
4612 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004613 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004614 }
4615 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004616 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4617 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004618 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004619 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004620 else
4621 Result = V;
4622 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004623
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004624 // Add in the BaseGV if present.
4625 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004626 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004627 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004628 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004629 else
4630 Result = V;
4631 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004632
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004633 // Add in the Base Offset if present.
4634 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004635 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004636 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004637 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004638 else
4639 Result = V;
4640 }
4641
Craig Topperc0196b12014-04-14 00:51:57 +00004642 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004643 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004644 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004645 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004646 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004647
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004648 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Simon Dardis230f4532017-11-24 16:45:28 +00004649 // Store the newly computed address into the cache. In the case we reused a
4650 // value, this should be idempotent.
4651 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004652
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004653 // If we have no uses, recursively delete the value and all dead instructions
4654 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004655 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004656 // This can cause recursive deletion, which can invalidate our iterator.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004657 // Use a WeakTrackingVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004658 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004659 WeakTrackingVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004660 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004661
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004662 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004663
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004664 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004665 // If the iterator instruction was recursively deleted, start over at the
4666 // start of the block.
4667 CurInstIterator = BB->begin();
4668 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004669 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004670 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004671 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004672 return true;
4673}
4674
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004675/// If there are any memory operands, use OptimizeMemoryInst to sink their
4676/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004677bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004678 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004679
Eric Christopher11e4df72015-02-26 22:38:43 +00004680 const TargetRegisterInfo *TRI =
Sanjay Patel4137d512017-06-07 14:29:52 +00004681 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004682 TargetLowering::AsmOperandInfoVector TargetConstraints =
4683 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004684 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004685 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4686 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004687
Evan Cheng1da25002008-02-26 02:42:37 +00004688 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004689 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004690
Eli Friedman666bbe32008-02-26 18:37:49 +00004691 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4692 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004693 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004694 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004695 } else if (OpInfo.Type == InlineAsm::isInput)
4696 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004697 }
4698
4699 return MadeChange;
4700}
4701
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004702/// Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004703/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00004704static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4705 assert(!Val->use_empty() && "Input must have at least one use");
4706 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004707 bool IsSExt = isa<SExtInst>(FirstUser);
4708 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00004709 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004710 const Instruction *UI = cast<Instruction>(U);
4711 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4712 return false;
4713 Type *CurTy = UI->getType();
4714 // Same input and output types: Same instruction after CSE.
4715 if (CurTy == ExtTy)
4716 continue;
4717
4718 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00004719 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004720 // b = sext ty1 a to ty2
4721 // c = sext ty1 a to ty3
4722 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00004723 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004724 // b = sext ty1 a to ty2
4725 // c = sext ty2 b to ty3
4726 // However, the last sext is not free.
4727 if (IsSExt)
4728 return false;
4729
4730 // This is a ZExt, maybe this is free to extend from one type to another.
4731 // In that case, we would not account for a different use.
4732 Type *NarrowTy;
4733 Type *LargeTy;
4734 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4735 CurTy->getScalarType()->getIntegerBitWidth()) {
4736 NarrowTy = CurTy;
4737 LargeTy = ExtTy;
4738 } else {
4739 NarrowTy = ExtTy;
4740 LargeTy = CurTy;
4741 }
4742
4743 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4744 return false;
4745 }
4746 // All uses are the same or can be derived from one another for free.
4747 return true;
4748}
4749
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004750/// Try to speculatively promote extensions in \p Exts and continue
Jun Bum Lim42301012017-03-17 19:05:21 +00004751/// promoting through newly promoted operands recursively as far as doing so is
4752/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4753/// When some promotion happened, \p TPT contains the proper state to revert
4754/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004755///
Jun Bum Lim42301012017-03-17 19:05:21 +00004756/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00004757bool CodeGenPrepare::tryToPromoteExts(
4758 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4759 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4760 unsigned CreatedInstsCost) {
4761 bool Promoted = false;
4762
4763 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004764 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004765 // Early check if we directly have ext(load).
4766 if (isa<LoadInst>(I->getOperand(0))) {
4767 ProfitablyMovedExts.push_back(I);
4768 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004769 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004770
4771 // Check whether or not we want to do any promotion. The reason we have
4772 // this check inside the for loop is to catch the case where an extension
4773 // is directly fed by a load because in such case the extension can be moved
4774 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004775 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00004776 return false;
4777
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004778 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00004779 TypePromotionHelper::Action TPH =
4780 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004781 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00004782 if (!TPH) {
4783 // Save the current extension as we cannot move up through its operand.
4784 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004785 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00004786 }
4787
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004788 // Save the current state.
4789 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4790 TPT.getRestorationPoint();
4791 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004792 unsigned NewCreatedInstsCost = 0;
4793 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004794 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004795 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4796 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004797 assert(PromotedVal &&
4798 "TypePromotionHelper should have filtered out those cases");
4799
4800 // We would be able to merge only one extension in a load.
4801 // Therefore, if we have more than 1 new extension we heuristically
4802 // cut this search path, because it means we degrade the code quality.
4803 // With exactly 2, the transformation is neutral, because we will merge
4804 // one extension but leave one. However, we optimistically keep going,
4805 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004806 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004807 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00004808 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004809 TotalCreatedInstsCost =
4810 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004811 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004812 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004813 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004814 // This promotion is not profitable, rollback to the previous state, and
4815 // save the current extension in ProfitablyMovedExts as the latest
4816 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004817 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00004818 ProfitablyMovedExts.push_back(I);
4819 continue;
4820 }
4821 // Continue promoting NewExts as far as doing so is profitable.
4822 SmallVector<Instruction *, 2> NewlyMovedExts;
4823 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4824 bool NewPromoted = false;
4825 for (auto ExtInst : NewlyMovedExts) {
4826 Instruction *MovedExt = cast<Instruction>(ExtInst);
4827 Value *ExtOperand = MovedExt->getOperand(0);
4828 // If we have reached to a load, we need this extra profitability check
4829 // as it could potentially be merged into an ext(load).
4830 if (isa<LoadInst>(ExtOperand) &&
4831 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4832 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
4833 continue;
4834
4835 ProfitablyMovedExts.push_back(MovedExt);
4836 NewPromoted = true;
4837 }
4838
4839 // If none of speculative promotions for NewExts is profitable, rollback
4840 // and save the current extension (I) as the last profitable extension.
4841 if (!NewPromoted) {
4842 TPT.rollback(LastKnownGood);
4843 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004844 continue;
4845 }
4846 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00004847 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004848 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004849 return Promoted;
4850}
4851
Jun Bum Limdee55652017-04-03 19:20:07 +00004852/// Merging redundant sexts when one is dominating the other.
4853bool CodeGenPrepare::mergeSExts(Function &F) {
4854 DominatorTree DT(F);
4855 bool Changed = false;
4856 for (auto &Entry : ValToSExtendedUses) {
4857 SExts &Insts = Entry.second;
4858 SExts CurPts;
4859 for (Instruction *Inst : Insts) {
4860 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
4861 Inst->getOperand(0) != Entry.first)
4862 continue;
4863 bool inserted = false;
4864 for (auto &Pt : CurPts) {
4865 if (DT.dominates(Inst, Pt)) {
4866 Pt->replaceAllUsesWith(Inst);
4867 RemovedInsts.insert(Pt);
4868 Pt->removeFromParent();
4869 Pt = Inst;
4870 inserted = true;
4871 Changed = true;
4872 break;
4873 }
4874 if (!DT.dominates(Pt, Inst))
4875 // Give up if we need to merge in a common dominator as the
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00004876 // experiments show it is not profitable.
Jun Bum Limdee55652017-04-03 19:20:07 +00004877 continue;
4878 Inst->replaceAllUsesWith(Pt);
4879 RemovedInsts.insert(Inst);
4880 Inst->removeFromParent();
4881 inserted = true;
4882 Changed = true;
4883 break;
4884 }
4885 if (!inserted)
4886 CurPts.push_back(Inst);
4887 }
4888 }
4889 return Changed;
4890}
4891
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004892// Spliting large data structures so that the GEPs accessing them can have
4893// smaller offsets so that they can be sunk to the same blocks as their users.
4894// For example, a large struct starting from %base is splitted into two parts
4895// where the second part starts from %new_base.
4896//
4897// Before:
4898// BB0:
4899// %base =
4900//
4901// BB1:
4902// %gep0 = gep %base, off0
4903// %gep1 = gep %base, off1
4904// %gep2 = gep %base, off2
4905//
4906// BB2:
4907// %load1 = load %gep0
4908// %load2 = load %gep1
4909// %load3 = load %gep2
4910//
4911// After:
4912// BB0:
4913// %base =
4914// %new_base = gep %base, off0
4915//
4916// BB1:
4917// %new_gep0 = %new_base
4918// %new_gep1 = gep %new_base, off1 - off0
4919// %new_gep2 = gep %new_base, off2 - off0
4920//
4921// BB2:
4922// %load1 = load i32, i32* %new_gep0
4923// %load2 = load i32, i32* %new_gep1
4924// %load3 = load i32, i32* %new_gep2
4925//
4926// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
4927// their offsets are smaller enough to fit into the addressing mode.
4928bool CodeGenPrepare::splitLargeGEPOffsets() {
4929 bool Changed = false;
4930 for (auto &Entry : LargeOffsetGEPMap) {
4931 Value *OldBase = Entry.first;
4932 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
4933 &LargeOffsetGEPs = Entry.second;
4934 auto compareGEPOffset =
4935 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
4936 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
4937 if (LHS.first == RHS.first)
4938 return false;
4939 if (LHS.second != RHS.second)
4940 return LHS.second < RHS.second;
4941 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
4942 };
4943 // Sorting all the GEPs of the same data structures based on the offsets.
4944 llvm::sort(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end(),
4945 compareGEPOffset);
4946 LargeOffsetGEPs.erase(
4947 std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()),
4948 LargeOffsetGEPs.end());
4949 // Skip if all the GEPs have the same offsets.
4950 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
4951 continue;
4952 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
4953 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
4954 Value *NewBaseGEP = nullptr;
4955
4956 auto LargeOffsetGEP = LargeOffsetGEPs.begin();
4957 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
4958 GetElementPtrInst *GEP = LargeOffsetGEP->first;
4959 int64_t Offset = LargeOffsetGEP->second;
4960 if (Offset != BaseOffset) {
4961 TargetLowering::AddrMode AddrMode;
4962 AddrMode.BaseOffs = Offset - BaseOffset;
4963 // The result type of the GEP might not be the type of the memory
4964 // access.
4965 if (!TLI->isLegalAddressingMode(*DL, AddrMode,
4966 GEP->getResultElementType(),
4967 GEP->getAddressSpace())) {
4968 // We need to create a new base if the offset to the current base is
4969 // too large to fit into the addressing mode. So, a very large struct
4970 // may be splitted into several parts.
4971 BaseGEP = GEP;
4972 BaseOffset = Offset;
4973 NewBaseGEP = nullptr;
4974 }
4975 }
4976
4977 // Generate a new GEP to replace the current one.
4978 IRBuilder<> Builder(GEP);
4979 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
4980 Type *I8PtrTy =
4981 Builder.getInt8PtrTy(GEP->getType()->getPointerAddressSpace());
4982 Type *I8Ty = Builder.getInt8Ty();
4983
4984 if (!NewBaseGEP) {
4985 // Create a new base if we don't have one yet. Find the insertion
4986 // pointer for the new base first.
4987 BasicBlock::iterator NewBaseInsertPt;
4988 BasicBlock *NewBaseInsertBB;
4989 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
4990 // If the base of the struct is an instruction, the new base will be
4991 // inserted close to it.
4992 NewBaseInsertBB = BaseI->getParent();
4993 if (isa<PHINode>(BaseI))
4994 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
4995 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
4996 NewBaseInsertBB =
4997 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
4998 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
4999 } else
5000 NewBaseInsertPt = std::next(BaseI->getIterator());
5001 } else {
5002 // If the current base is an argument or global value, the new base
5003 // will be inserted to the entry block.
5004 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
5005 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5006 }
5007 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
5008 // Create a new base.
5009 Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset);
5010 NewBaseGEP = OldBase;
5011 if (NewBaseGEP->getType() != I8PtrTy)
5012 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
5013 NewBaseGEP =
5014 NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep");
5015 NewGEPBases.insert(NewBaseGEP);
5016 }
5017
5018 Value *NewGEP = NewBaseGEP;
5019 if (Offset == BaseOffset) {
5020 if (GEP->getType() != I8PtrTy)
5021 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5022 } else {
5023 // Calculate the new offset for the new GEP.
5024 Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset);
5025 NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index);
5026
5027 if (GEP->getType() != I8PtrTy)
5028 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5029 }
5030 GEP->replaceAllUsesWith(NewGEP);
5031 LargeOffsetGEPID.erase(GEP);
5032 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
5033 GEP->eraseFromParent();
5034 Changed = true;
5035 }
5036 }
5037 return Changed;
5038}
5039
Jun Bum Lim42301012017-03-17 19:05:21 +00005040/// Return true, if an ext(load) can be formed from an extension in
5041/// \p MovedExts.
5042bool CodeGenPrepare::canFormExtLd(
5043 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
5044 Instruction *&Inst, bool HasPromoted) {
5045 for (auto *MovedExtInst : MovedExts) {
5046 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
5047 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
5048 Inst = MovedExtInst;
5049 break;
5050 }
5051 }
5052 if (!LI)
5053 return false;
5054
5055 // If they're already in the same block, there's nothing to do.
5056 // Make the cheap checks first if we did not promote.
5057 // If we promoted, we need to check if it is indeed profitable.
5058 if (!HasPromoted && LI->getParent() == Inst->getParent())
5059 return false;
5060
Haicheng Wuabdef9e2017-07-15 02:12:16 +00005061 return TLI->isExtLoad(LI, Inst, *DL);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005062}
5063
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005064/// Move a zext or sext fed by a load into the same basic block as the load,
5065/// unless conditions are unfavorable. This allows SelectionDAG to fold the
5066/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00005067///
Jun Bum Limdee55652017-04-03 19:20:07 +00005068/// E.g.,
5069/// \code
5070/// %ld = load i32* %addr
5071/// %add = add nuw i32 %ld, 4
5072/// %zext = zext i32 %add to i64
5073// \endcode
5074/// =>
5075/// \code
5076/// %ld = load i32* %addr
5077/// %zext = zext i32 %ld to i64
5078/// %add = add nuw i64 %zext, 4
5079/// \encode
5080/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
5081/// allow us to match zext(load i32*) to i64.
5082///
5083/// Also, try to promote the computations used to obtain a sign extended
5084/// value used into memory accesses.
5085/// E.g.,
5086/// \code
5087/// a = add nsw i32 b, 3
5088/// d = sext i32 a to i64
5089/// e = getelementptr ..., i64 d
5090/// \endcode
5091/// =>
5092/// \code
5093/// f = sext i32 b to i64
5094/// a = add nsw i64 f, 3
5095/// e = getelementptr ..., i64 a
5096/// \endcode
5097///
5098/// \p Inst[in/out] the extension may be modified during the process if some
5099/// promotions apply.
5100bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
5101 // ExtLoad formation and address type promotion infrastructure requires TLI to
5102 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00005103 if (!TLI)
5104 return false;
5105
Jun Bum Limdee55652017-04-03 19:20:07 +00005106 bool AllowPromotionWithoutCommonHeader = false;
5107 /// See if it is an interesting sext operations for the address type
5108 /// promotion before trying to promote it, e.g., the ones with the right
5109 /// type and used in memory accesses.
5110 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
5111 *Inst, AllowPromotionWithoutCommonHeader);
5112 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005113 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00005114 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005115 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00005116 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
5117 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00005118
Jun Bum Limdee55652017-04-03 19:20:07 +00005119 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00005120
Dan Gohman99429a02009-10-16 20:59:35 +00005121 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005122 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00005123 Instruction *ExtFedByLoad;
5124
5125 // Try to promote a chain of computation if it allows to form an extended
5126 // load.
5127 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
5128 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
5129 TPT.commit();
5130 // Move the extend into the same block as the load
Sanjay Patel674d2c22017-08-29 14:07:48 +00005131 ExtFedByLoad->moveAfter(LI);
Jun Bum Limdee55652017-04-03 19:20:07 +00005132 // CGP does not check if the zext would be speculatively executed when moved
5133 // to the same basic block as the load. Preserving its original location
5134 // would pessimize the debugging experience, as well as negatively impact
5135 // the quality of sample pgo. We don't want to use "line 0" as that has a
5136 // size cost in the line-table section and logically the zext can be seen as
5137 // part of the load. Therefore we conservatively reuse the same debug
5138 // location for the load and the zext.
5139 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
5140 ++NumExtsMoved;
5141 Inst = ExtFedByLoad;
5142 return true;
5143 }
5144
5145 // Continue promoting SExts if known as considerable depending on targets.
5146 if (ATPConsiderable &&
5147 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
5148 HasPromoted, TPT, SpeculativelyMovedExts))
5149 return true;
5150
5151 TPT.rollback(LastKnownGood);
5152 return false;
5153}
5154
5155// Perform address type promotion if doing so is profitable.
5156// If AllowPromotionWithoutCommonHeader == false, we should find other sext
5157// instructions that sign extended the same initial value. However, if
5158// AllowPromotionWithoutCommonHeader == true, we expect promoting the
5159// extension is just profitable.
5160bool CodeGenPrepare::performAddressTypePromotion(
5161 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
5162 bool HasPromoted, TypePromotionTransaction &TPT,
5163 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
5164 bool Promoted = false;
5165 SmallPtrSet<Instruction *, 1> UnhandledExts;
5166 bool AllSeenFirst = true;
5167 for (auto I : SpeculativelyMovedExts) {
5168 Value *HeadOfChain = I->getOperand(0);
5169 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
5170 SeenChainsForSExt.find(HeadOfChain);
5171 // If there is an unhandled SExt which has the same header, try to promote
5172 // it as well.
5173 if (AlreadySeen != SeenChainsForSExt.end()) {
5174 if (AlreadySeen->second != nullptr)
5175 UnhandledExts.insert(AlreadySeen->second);
5176 AllSeenFirst = false;
5177 }
5178 }
5179
5180 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
5181 SpeculativelyMovedExts.size() == 1)) {
5182 TPT.commit();
5183 if (HasPromoted)
5184 Promoted = true;
5185 for (auto I : SpeculativelyMovedExts) {
5186 Value *HeadOfChain = I->getOperand(0);
5187 SeenChainsForSExt[HeadOfChain] = nullptr;
5188 ValToSExtendedUses[HeadOfChain].push_back(I);
5189 }
5190 // Update Inst as promotion happen.
5191 Inst = SpeculativelyMovedExts.pop_back_val();
5192 } else {
5193 // This is the first chain visited from the header, keep the current chain
5194 // as unhandled. Defer to promote this until we encounter another SExt
5195 // chain derived from the same header.
5196 for (auto I : SpeculativelyMovedExts) {
5197 Value *HeadOfChain = I->getOperand(0);
5198 SeenChainsForSExt[HeadOfChain] = Inst;
5199 }
Dan Gohman99429a02009-10-16 20:59:35 +00005200 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005201 }
Dan Gohman99429a02009-10-16 20:59:35 +00005202
Jun Bum Limdee55652017-04-03 19:20:07 +00005203 if (!AllSeenFirst && !UnhandledExts.empty())
5204 for (auto VisitedSExt : UnhandledExts) {
5205 if (RemovedInsts.count(VisitedSExt))
5206 continue;
5207 TypePromotionTransaction TPT(RemovedInsts);
5208 SmallVector<Instruction *, 1> Exts;
5209 SmallVector<Instruction *, 2> Chains;
5210 Exts.push_back(VisitedSExt);
5211 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
5212 TPT.commit();
5213 if (HasPromoted)
5214 Promoted = true;
5215 for (auto I : Chains) {
5216 Value *HeadOfChain = I->getOperand(0);
5217 // Mark this as handled.
5218 SeenChainsForSExt[HeadOfChain] = nullptr;
5219 ValToSExtendedUses[HeadOfChain].push_back(I);
5220 }
5221 }
5222 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00005223}
5224
Sanjay Patelfc580a62015-09-21 23:03:16 +00005225bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00005226 BasicBlock *DefBB = I->getParent();
5227
Bob Wilsonff714f92010-09-21 21:44:14 +00005228 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00005229 // other uses of the source with result of extension.
5230 Value *Src = I->getOperand(0);
5231 if (Src->hasOneUse())
5232 return false;
5233
Evan Cheng2011df42007-12-13 07:50:36 +00005234 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00005235 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00005236 return false;
5237
Evan Cheng7bc89422007-12-12 00:51:06 +00005238 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00005239 // this block.
5240 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00005241 return false;
5242
Evan Chengd3d80172007-12-05 23:58:20 +00005243 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005244 for (User *U : I->users()) {
5245 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00005246
5247 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005248 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00005249 if (UserBB == DefBB) continue;
5250 DefIsLiveOut = true;
5251 break;
5252 }
5253 if (!DefIsLiveOut)
5254 return false;
5255
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00005256 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005257 for (User *U : Src->users()) {
5258 Instruction *UI = cast<Instruction>(U);
5259 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00005260 if (UserBB == DefBB) continue;
5261 // Be conservative. We don't want this xform to end up introducing
5262 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005263 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00005264 return false;
5265 }
5266
Evan Chengd3d80172007-12-05 23:58:20 +00005267 // InsertedTruncs - Only insert one trunc in each block once.
5268 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5269
5270 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005271 for (Use &U : Src->uses()) {
5272 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00005273
5274 // Figure out which BB this ext is used in.
5275 BasicBlock *UserBB = User->getParent();
5276 if (UserBB == DefBB) continue;
5277
5278 // Both src and def are live in this block. Rewrite the use.
5279 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5280
5281 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00005282 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005283 assert(InsertPt != UserBB->end());
5284 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005285 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00005286 }
5287
5288 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005289 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00005290 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00005291 MadeChange = true;
5292 }
5293
5294 return MadeChange;
5295}
5296
Geoff Berry5256fca2015-11-20 22:34:39 +00005297// Find loads whose uses only use some of the loaded value's bits. Add an "and"
5298// just after the load if the target can fold this into one extload instruction,
5299// with the hope of eliminating some of the other later "and" instructions using
5300// the loaded value. "and"s that are made trivially redundant by the insertion
5301// of the new "and" are removed by this function, while others (e.g. those whose
5302// path from the load goes through a phi) are left for isel to potentially
5303// remove.
5304//
5305// For example:
5306//
5307// b0:
5308// x = load i32
5309// ...
5310// b1:
5311// y = and x, 0xff
5312// z = use y
5313//
5314// becomes:
5315//
5316// b0:
5317// x = load i32
5318// x' = and x, 0xff
5319// ...
5320// b1:
5321// z = use x'
5322//
5323// whereas:
5324//
5325// b0:
5326// x1 = load i32
5327// ...
5328// b1:
5329// x2 = load i32
5330// ...
5331// b2:
5332// x = phi x1, x2
5333// y = and x, 0xff
5334//
5335// becomes (after a call to optimizeLoadExt for each load):
5336//
5337// b0:
5338// x1 = load i32
5339// x1' = and x1, 0xff
5340// ...
5341// b1:
5342// x2 = load i32
5343// x2' = and x2, 0xff
5344// ...
5345// b2:
5346// x = phi x1', x2'
5347// y = and x, 0xff
Geoff Berry5256fca2015-11-20 22:34:39 +00005348bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005349 if (!Load->isSimple() ||
5350 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5351 return false;
5352
Geoff Berry5d534b62017-02-21 18:53:14 +00005353 // Skip loads we've already transformed.
5354 if (Load->hasOneUse() &&
5355 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5356 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005357
5358 // Look at all uses of Load, looking through phis, to determine how many bits
5359 // of the loaded value are needed.
5360 SmallVector<Instruction *, 8> WorkList;
5361 SmallPtrSet<Instruction *, 16> Visited;
5362 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5363 for (auto *U : Load->users())
5364 WorkList.push_back(cast<Instruction>(U));
5365
5366 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5367 unsigned BitWidth = LoadResultVT.getSizeInBits();
5368 APInt DemandBits(BitWidth, 0);
5369 APInt WidestAndBits(BitWidth, 0);
5370
5371 while (!WorkList.empty()) {
5372 Instruction *I = WorkList.back();
5373 WorkList.pop_back();
5374
5375 // Break use-def graph loops.
5376 if (!Visited.insert(I).second)
5377 continue;
5378
5379 // For a PHI node, push all of its users.
5380 if (auto *Phi = dyn_cast<PHINode>(I)) {
5381 for (auto *U : Phi->users())
5382 WorkList.push_back(cast<Instruction>(U));
5383 continue;
5384 }
5385
5386 switch (I->getOpcode()) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005387 case Instruction::And: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005388 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5389 if (!AndC)
5390 return false;
5391 APInt AndBits = AndC->getValue();
5392 DemandBits |= AndBits;
5393 // Keep track of the widest and mask we see.
5394 if (AndBits.ugt(WidestAndBits))
5395 WidestAndBits = AndBits;
5396 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5397 AndsToMaybeRemove.push_back(I);
5398 break;
5399 }
5400
Eugene Zelenko900b6332017-08-29 22:32:07 +00005401 case Instruction::Shl: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005402 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5403 if (!ShlC)
5404 return false;
5405 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00005406 DemandBits.setLowBits(BitWidth - ShiftAmt);
Geoff Berry5256fca2015-11-20 22:34:39 +00005407 break;
5408 }
5409
Eugene Zelenko900b6332017-08-29 22:32:07 +00005410 case Instruction::Trunc: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005411 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5412 unsigned TruncBitWidth = TruncVT.getSizeInBits();
Craig Topperfc947bc2017-04-18 17:14:21 +00005413 DemandBits.setLowBits(TruncBitWidth);
Geoff Berry5256fca2015-11-20 22:34:39 +00005414 break;
5415 }
5416
5417 default:
5418 return false;
5419 }
5420 }
5421
5422 uint32_t ActiveBits = DemandBits.getActiveBits();
5423 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5424 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5425 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5426 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5427 // followed by an AND.
5428 // TODO: Look into removing this restriction by fixing backends to either
5429 // return false for isLoadExtLegal for i1 or have them select this pattern to
5430 // a single instruction.
5431 //
5432 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5433 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005434 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005435 WidestAndBits != DemandBits)
5436 return false;
5437
5438 LLVMContext &Ctx = Load->getType()->getContext();
5439 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5440 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5441
5442 // Reject cases that won't be matched as extloads.
5443 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5444 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5445 return false;
5446
5447 IRBuilder<> Builder(Load->getNextNode());
5448 auto *NewAnd = dyn_cast<Instruction>(
5449 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005450 // Mark this instruction as "inserted by CGP", so that other
5451 // optimizations don't touch it.
5452 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005453
5454 // Replace all uses of load with new and (except for the use of load in the
5455 // new and itself).
5456 Load->replaceAllUsesWith(NewAnd);
5457 NewAnd->setOperand(0, Load);
5458
5459 // Remove any and instructions that are now redundant.
5460 for (auto *And : AndsToMaybeRemove)
5461 // Check that the and mask is the same as the one we decided to put on the
5462 // new and.
5463 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5464 And->replaceAllUsesWith(NewAnd);
5465 if (&*CurInstIterator == And)
5466 CurInstIterator = std::next(And->getIterator());
5467 And->eraseFromParent();
5468 ++NumAndUses;
5469 }
5470
5471 ++NumAndsAdded;
5472 return true;
5473}
5474
Sanjay Patel69a50a12015-10-19 21:59:12 +00005475/// Check if V (an operand of a select instruction) is an expensive instruction
5476/// that is only used once.
5477static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5478 auto *I = dyn_cast<Instruction>(V);
5479 // If it's safe to speculatively execute, then it should not have side
5480 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005481 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5482 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005483}
5484
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005485/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005486static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005487 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005488 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005489 // If even a predictable select is cheap, then a branch can't be cheaper.
5490 if (!TLI->isPredictableSelectExpensive())
5491 return false;
5492
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005493 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005494 // whether a select is better represented as a branch.
5495
5496 // If metadata tells us that the select condition is obviously predictable,
5497 // then we want to replace the select with a branch.
5498 uint64_t TrueWeight, FalseWeight;
5499 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5500 uint64_t Max = std::max(TrueWeight, FalseWeight);
5501 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005502 if (Sum != 0) {
5503 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5504 if (Probability > TLI->getPredictableBranchThreshold())
5505 return true;
5506 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005507 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005508
5509 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5510
Sanjay Patel4e652762015-09-28 22:14:51 +00005511 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5512 // comparison condition. If the compare has more than one use, there's
5513 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005514 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005515 return false;
5516
Sanjay Patel69a50a12015-10-19 21:59:12 +00005517 // If either operand of the select is expensive and only needed on one side
5518 // of the select, we should form a branch.
5519 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5520 sinkSelectOperand(TTI, SI->getFalseValue()))
5521 return true;
5522
5523 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005524}
5525
Dehao Chen9bbb9412016-09-12 20:23:28 +00005526/// If \p isTrue is true, return the true value of \p SI, otherwise return
5527/// false value of \p SI. If the true/false value of \p SI is defined by any
5528/// select instructions in \p Selects, look through the defining select
5529/// instruction until the true/false value is not defined in \p Selects.
5530static Value *getTrueOrFalseValue(
5531 SelectInst *SI, bool isTrue,
5532 const SmallPtrSet<const Instruction *, 2> &Selects) {
5533 Value *V;
5534
5535 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5536 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005537 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005538 "The condition of DefSI does not match with SI");
5539 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5540 }
5541 return V;
5542}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005543
Nadav Rotem9d832022012-09-02 12:10:19 +00005544/// If we have a SelectInst that will likely profit from branch prediction,
5545/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005546bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00005547 // Find all consecutive select instructions that share the same condition.
5548 SmallVector<SelectInst *, 2> ASI;
5549 ASI.push_back(SI);
5550 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5551 It != SI->getParent()->end(); ++It) {
5552 SelectInst *I = dyn_cast<SelectInst>(&*It);
5553 if (I && SI->getCondition() == I->getCondition()) {
5554 ASI.push_back(I);
5555 } else {
5556 break;
5557 }
5558 }
5559
5560 SelectInst *LastSI = ASI.back();
5561 // Increment the current iterator to skip all the rest of select instructions
5562 // because they will be either "not lowered" or "all lowered" to branch.
5563 CurInstIterator = std::next(LastSI->getIterator());
5564
Nadav Rotem9d832022012-09-02 12:10:19 +00005565 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5566
5567 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00005568 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
5569 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005570 return false;
5571
Nadav Rotem9d832022012-09-02 12:10:19 +00005572 TargetLowering::SelectSupportKind SelectKind;
5573 if (VectorCond)
5574 SelectKind = TargetLowering::VectorMaskSelect;
5575 else if (SI->getType()->isVectorTy())
5576 SelectKind = TargetLowering::ScalarCondVectorVal;
5577 else
5578 SelectKind = TargetLowering::ScalarValSelect;
5579
Sanjay Pateld66607b2016-04-26 17:11:17 +00005580 if (TLI->isSelectSupported(SelectKind) &&
5581 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5582 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005583
5584 ModifiedDT = true;
5585
Sanjay Patel69a50a12015-10-19 21:59:12 +00005586 // Transform a sequence like this:
5587 // start:
5588 // %cmp = cmp uge i32 %a, %b
5589 // %sel = select i1 %cmp, i32 %c, i32 %d
5590 //
5591 // Into:
5592 // start:
5593 // %cmp = cmp uge i32 %a, %b
5594 // br i1 %cmp, label %select.true, label %select.false
5595 // select.true:
5596 // br label %select.end
5597 // select.false:
5598 // br label %select.end
5599 // select.end:
5600 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5601 //
5602 // In addition, we may sink instructions that produce %c or %d from
5603 // the entry block into the destination(s) of the new branch.
5604 // If the true or false blocks do not contain a sunken instruction, that
5605 // block and its branch may be optimized away. In that case, one side of the
5606 // first branch will point directly to select.end, and the corresponding PHI
5607 // predecessor block will be the start block.
5608
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005609 // First, we split the block containing the select into 2 blocks.
5610 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005611 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005612 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005613
Sanjay Patel69a50a12015-10-19 21:59:12 +00005614 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005615 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005616
5617 // These are the new basic blocks for the conditional branch.
5618 // At least one will become an actual new basic block.
5619 BasicBlock *TrueBlock = nullptr;
5620 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005621 BranchInst *TrueBranch = nullptr;
5622 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005623
5624 // Sink expensive instructions into the conditional blocks to avoid executing
5625 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005626 for (SelectInst *SI : ASI) {
5627 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5628 if (TrueBlock == nullptr) {
5629 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5630 EndBlock->getParent(), EndBlock);
5631 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5632 }
5633 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5634 TrueInst->moveBefore(TrueBranch);
5635 }
5636 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5637 if (FalseBlock == nullptr) {
5638 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5639 EndBlock->getParent(), EndBlock);
5640 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5641 }
5642 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5643 FalseInst->moveBefore(FalseBranch);
5644 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005645 }
5646
5647 // If there was nothing to sink, then arbitrarily choose the 'false' side
5648 // for a new input value to the PHI.
5649 if (TrueBlock == FalseBlock) {
5650 assert(TrueBlock == nullptr &&
5651 "Unexpected basic block transform while optimizing select");
5652
5653 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5654 EndBlock->getParent(), EndBlock);
5655 BranchInst::Create(EndBlock, FalseBlock);
5656 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005657
5658 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005659 // If we did not create a new block for one of the 'true' or 'false' paths
5660 // of the condition, it means that side of the branch goes to the end block
5661 // directly and the path originates from the start block from the point of
5662 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005663 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005664 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005665 TT = EndBlock;
5666 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005667 TrueBlock = StartBlock;
5668 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005669 TT = TrueBlock;
5670 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005671 FalseBlock = StartBlock;
5672 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005673 TT = TrueBlock;
5674 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005675 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005676 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005677
Dehao Chen9bbb9412016-09-12 20:23:28 +00005678 SmallPtrSet<const Instruction *, 2> INS;
5679 INS.insert(ASI.begin(), ASI.end());
5680 // Use reverse iterator because later select may use the value of the
5681 // earlier select, and we need to propagate value through earlier select
5682 // to get the PHI operand.
5683 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5684 SelectInst *SI = *It;
5685 // The select itself is replaced with a PHI Node.
5686 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5687 PN->takeName(SI);
5688 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5689 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00005690
Dehao Chen9bbb9412016-09-12 20:23:28 +00005691 SI->replaceAllUsesWith(PN);
5692 SI->eraseFromParent();
5693 INS.erase(SI);
5694 ++NumSelectsExpanded;
5695 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005696
5697 // Instruct OptimizeBlock to skip to the next block.
5698 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005699 return true;
5700}
5701
Benjamin Kramer573ff362014-03-01 17:24:40 +00005702static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005703 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5704 int SplatElem = -1;
5705 for (unsigned i = 0; i < Mask.size(); ++i) {
5706 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5707 return false;
5708 SplatElem = Mask[i];
5709 }
5710
5711 return true;
5712}
5713
5714/// Some targets have expensive vector shifts if the lanes aren't all the same
5715/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5716/// it's often worth sinking a shufflevector splat down to its use so that
5717/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005718bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005719 BasicBlock *DefBB = SVI->getParent();
5720
5721 // Only do this xform if variable vector shifts are particularly expensive.
5722 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5723 return false;
5724
5725 // We only expect better codegen by sinking a shuffle if we can recognise a
5726 // constant splat.
5727 if (!isBroadcastShuffle(SVI))
5728 return false;
5729
5730 // InsertedShuffles - Only insert a shuffle in each block once.
5731 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5732
5733 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005734 for (User *U : SVI->users()) {
5735 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005736
5737 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005738 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005739 if (UserBB == DefBB) continue;
5740
5741 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005742 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005743
5744 // Everything checks out, sink the shuffle if the user's block doesn't
5745 // already have a copy.
5746 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5747
5748 if (!InsertedShuffle) {
5749 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005750 assert(InsertPt != UserBB->end());
5751 InsertedShuffle =
5752 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5753 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005754 }
5755
Chandler Carruthcdf47882014-03-09 03:16:01 +00005756 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005757 MadeChange = true;
5758 }
5759
5760 // If we removed all uses, nuke the shuffle.
5761 if (SVI->use_empty()) {
5762 SVI->eraseFromParent();
5763 MadeChange = true;
5764 }
5765
5766 return MadeChange;
5767}
5768
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005769bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5770 if (!TLI || !DL)
5771 return false;
5772
5773 Value *Cond = SI->getCondition();
5774 Type *OldType = Cond->getType();
5775 LLVMContext &Context = Cond->getContext();
5776 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5777 unsigned RegWidth = RegType.getSizeInBits();
5778
5779 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5780 return false;
5781
5782 // If the register width is greater than the type width, expand the condition
5783 // of the switch instruction and each case constant to the width of the
5784 // register. By widening the type of the switch condition, subsequent
5785 // comparisons (for case comparisons) will not need to be extended to the
5786 // preferred register width, so we will potentially eliminate N-1 extends,
5787 // where N is the number of cases in the switch.
5788 auto *NewType = Type::getIntNTy(Context, RegWidth);
5789
5790 // Zero-extend the switch condition and case constants unless the switch
5791 // condition is a function argument that is already being sign-extended.
5792 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5793 // everything instead.
5794 Instruction::CastOps ExtType = Instruction::ZExt;
5795 if (auto *Arg = dyn_cast<Argument>(Cond))
5796 if (Arg->hasSExtAttr())
5797 ExtType = Instruction::SExt;
5798
5799 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5800 ExtInst->insertBefore(SI);
5801 SI->setCondition(ExtInst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00005802 for (auto Case : SI->cases()) {
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005803 APInt NarrowConst = Case.getCaseValue()->getValue();
5804 APInt WideConst = (ExtType == Instruction::ZExt) ?
5805 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5806 Case.setValue(ConstantInt::get(Context, WideConst));
5807 }
5808
5809 return true;
5810}
5811
Zaara Syeda3a7578c2017-05-31 17:12:38 +00005812
Quentin Colombetc32615d2014-10-31 17:52:53 +00005813namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005814
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005815/// Helper class to promote a scalar operation to a vector one.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005816/// This class is used to move downward extractelement transition.
5817/// E.g.,
5818/// a = vector_op <2 x i32>
5819/// b = extractelement <2 x i32> a, i32 0
5820/// c = scalar_op b
5821/// store c
5822///
5823/// =>
5824/// a = vector_op <2 x i32>
5825/// c = vector_op a (equivalent to scalar_op on the related lane)
5826/// * d = extractelement <2 x i32> c, i32 0
5827/// * store d
5828/// Assuming both extractelement and store can be combine, we get rid of the
5829/// transition.
5830class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005831 /// DataLayout associated with the current module.
5832 const DataLayout &DL;
5833
Quentin Colombetc32615d2014-10-31 17:52:53 +00005834 /// Used to perform some checks on the legality of vector operations.
5835 const TargetLowering &TLI;
5836
5837 /// Used to estimated the cost of the promoted chain.
5838 const TargetTransformInfo &TTI;
5839
5840 /// The transition being moved downwards.
5841 Instruction *Transition;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005842
Quentin Colombetc32615d2014-10-31 17:52:53 +00005843 /// The sequence of instructions to be promoted.
5844 SmallVector<Instruction *, 4> InstsToBePromoted;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005845
Quentin Colombetc32615d2014-10-31 17:52:53 +00005846 /// Cost of combining a store and an extract.
5847 unsigned StoreExtractCombineCost;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005848
Quentin Colombetc32615d2014-10-31 17:52:53 +00005849 /// Instruction that will be combined with the transition.
Eugene Zelenko900b6332017-08-29 22:32:07 +00005850 Instruction *CombineInst = nullptr;
Quentin Colombetc32615d2014-10-31 17:52:53 +00005851
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005852 /// The instruction that represents the current end of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005853 /// Since we are faking the promotion until we reach the end of the chain
5854 /// of computation, we need a way to get the current end of the transition.
5855 Instruction *getEndOfTransition() const {
5856 if (InstsToBePromoted.empty())
5857 return Transition;
5858 return InstsToBePromoted.back();
5859 }
5860
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005861 /// Return the index of the original value in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005862 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5863 /// c, is at index 0.
5864 unsigned getTransitionOriginalValueIdx() const {
5865 assert(isa<ExtractElementInst>(Transition) &&
5866 "Other kind of transitions are not supported yet");
5867 return 0;
5868 }
5869
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005870 /// Return the index of the index in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005871 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5872 /// is at index 1.
5873 unsigned getTransitionIdx() const {
5874 assert(isa<ExtractElementInst>(Transition) &&
5875 "Other kind of transitions are not supported yet");
5876 return 1;
5877 }
5878
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005879 /// Get the type of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005880 /// This is the type of the original value.
5881 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5882 /// transition is <2 x i32>.
5883 Type *getTransitionType() const {
5884 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5885 }
5886
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005887 /// Promote \p ToBePromoted by moving \p Def downward through.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005888 /// I.e., we have the following sequence:
5889 /// Def = Transition <ty1> a to <ty2>
5890 /// b = ToBePromoted <ty2> Def, ...
5891 /// =>
5892 /// b = ToBePromoted <ty1> a, ...
5893 /// Def = Transition <ty1> ToBePromoted to <ty2>
5894 void promoteImpl(Instruction *ToBePromoted);
5895
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005896 /// Check whether or not it is profitable to promote all the
Quentin Colombetc32615d2014-10-31 17:52:53 +00005897 /// instructions enqueued to be promoted.
5898 bool isProfitableToPromote() {
5899 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5900 unsigned Index = isa<ConstantInt>(ValIdx)
5901 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5902 : -1;
5903 Type *PromotedType = getTransitionType();
5904
5905 StoreInst *ST = cast<StoreInst>(CombineInst);
5906 unsigned AS = ST->getPointerAddressSpace();
5907 unsigned Align = ST->getAlignment();
5908 // Check if this store is supported.
5909 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005910 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5911 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005912 // If this is not supported, there is no way we can combine
5913 // the extract with the store.
5914 return false;
5915 }
5916
5917 // The scalar chain of computation has to pay for the transition
5918 // scalar to vector.
5919 // The vector chain has to account for the combining cost.
5920 uint64_t ScalarCost =
5921 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5922 uint64_t VectorCost = StoreExtractCombineCost;
5923 for (const auto &Inst : InstsToBePromoted) {
5924 // Compute the cost.
5925 // By construction, all instructions being promoted are arithmetic ones.
5926 // Moreover, one argument is a constant that can be viewed as a splat
5927 // constant.
5928 Value *Arg0 = Inst->getOperand(0);
5929 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5930 isa<ConstantFP>(Arg0);
5931 TargetTransformInfo::OperandValueKind Arg0OVK =
5932 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5933 : TargetTransformInfo::OK_AnyValue;
5934 TargetTransformInfo::OperandValueKind Arg1OVK =
5935 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5936 : TargetTransformInfo::OK_AnyValue;
5937 ScalarCost += TTI.getArithmeticInstrCost(
5938 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5939 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5940 Arg0OVK, Arg1OVK);
5941 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005942 LLVM_DEBUG(
5943 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5944 << ScalarCost << "\nVector: " << VectorCost << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00005945 return ScalarCost > VectorCost;
5946 }
5947
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005948 /// Generate a constant vector with \p Val with the same
Quentin Colombetc32615d2014-10-31 17:52:53 +00005949 /// number of elements as the transition.
5950 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005951 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005952 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5953 /// otherwise we generate a vector with as many undef as possible:
5954 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5955 /// used at the index of the extract.
5956 Value *getConstantVector(Constant *Val, bool UseSplat) const {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005957 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00005958 if (!UseSplat) {
5959 // If we cannot determine where the constant must be, we have to
5960 // use a splat constant.
5961 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5962 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5963 ExtractIdx = CstVal->getSExtValue();
5964 else
5965 UseSplat = true;
5966 }
5967
5968 unsigned End = getTransitionType()->getVectorNumElements();
5969 if (UseSplat)
5970 return ConstantVector::getSplat(End, Val);
5971
5972 SmallVector<Constant *, 4> ConstVec;
5973 UndefValue *UndefVal = UndefValue::get(Val->getType());
5974 for (unsigned Idx = 0; Idx != End; ++Idx) {
5975 if (Idx == ExtractIdx)
5976 ConstVec.push_back(Val);
5977 else
5978 ConstVec.push_back(UndefVal);
5979 }
5980 return ConstantVector::get(ConstVec);
5981 }
5982
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005983 /// Check if promoting to a vector type an operand at \p OperandIdx
Quentin Colombetc32615d2014-10-31 17:52:53 +00005984 /// in \p Use can trigger undefined behavior.
5985 static bool canCauseUndefinedBehavior(const Instruction *Use,
5986 unsigned OperandIdx) {
5987 // This is not safe to introduce undef when the operand is on
5988 // the right hand side of a division-like instruction.
5989 if (OperandIdx != 1)
5990 return false;
5991 switch (Use->getOpcode()) {
5992 default:
5993 return false;
5994 case Instruction::SDiv:
5995 case Instruction::UDiv:
5996 case Instruction::SRem:
5997 case Instruction::URem:
5998 return true;
5999 case Instruction::FDiv:
6000 case Instruction::FRem:
6001 return !Use->hasNoNaNs();
6002 }
6003 llvm_unreachable(nullptr);
6004 }
6005
6006public:
Mehdi Amini44ede332015-07-09 02:09:04 +00006007 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
6008 const TargetTransformInfo &TTI, Instruction *Transition,
6009 unsigned CombineCost)
6010 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Eugene Zelenko900b6332017-08-29 22:32:07 +00006011 StoreExtractCombineCost(CombineCost) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00006012 assert(Transition && "Do not know how to promote null");
6013 }
6014
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006015 /// Check if we can promote \p ToBePromoted to \p Type.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006016 bool canPromote(const Instruction *ToBePromoted) const {
6017 // We could support CastInst too.
6018 return isa<BinaryOperator>(ToBePromoted);
6019 }
6020
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006021 /// Check if it is profitable to promote \p ToBePromoted
Quentin Colombetc32615d2014-10-31 17:52:53 +00006022 /// by moving downward the transition through.
6023 bool shouldPromote(const Instruction *ToBePromoted) const {
6024 // Promote only if all the operands can be statically expanded.
6025 // Indeed, we do not want to introduce any new kind of transitions.
6026 for (const Use &U : ToBePromoted->operands()) {
6027 const Value *Val = U.get();
6028 if (Val == getEndOfTransition()) {
6029 // If the use is a division and the transition is on the rhs,
6030 // we cannot promote the operation, otherwise we may create a
6031 // division by zero.
6032 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
6033 return false;
6034 continue;
6035 }
6036 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
6037 !isa<ConstantFP>(Val))
6038 return false;
6039 }
6040 // Check that the resulting operation is legal.
6041 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
6042 if (!ISDOpcode)
6043 return false;
6044 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00006045 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00006046 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00006047 }
6048
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006049 /// Check whether or not \p Use can be combined
Quentin Colombetc32615d2014-10-31 17:52:53 +00006050 /// with the transition.
6051 /// I.e., is it possible to do Use(Transition) => AnotherUse?
6052 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
6053
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006054 /// Record \p ToBePromoted as part of the chain to be promoted.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006055 void enqueueForPromotion(Instruction *ToBePromoted) {
6056 InstsToBePromoted.push_back(ToBePromoted);
6057 }
6058
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006059 /// Set the instruction that will be combined with the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006060 void recordCombineInstruction(Instruction *ToBeCombined) {
6061 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
6062 CombineInst = ToBeCombined;
6063 }
6064
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006065 /// Promote all the instructions enqueued for promotion if it is
Quentin Colombetc32615d2014-10-31 17:52:53 +00006066 /// is profitable.
6067 /// \return True if the promotion happened, false otherwise.
6068 bool promote() {
6069 // Check if there is something to promote.
6070 // Right now, if we do not have anything to combine with,
6071 // we assume the promotion is not profitable.
6072 if (InstsToBePromoted.empty() || !CombineInst)
6073 return false;
6074
6075 // Check cost.
6076 if (!StressStoreExtract && !isProfitableToPromote())
6077 return false;
6078
6079 // Promote.
6080 for (auto &ToBePromoted : InstsToBePromoted)
6081 promoteImpl(ToBePromoted);
6082 InstsToBePromoted.clear();
6083 return true;
6084 }
6085};
Eugene Zelenko900b6332017-08-29 22:32:07 +00006086
6087} // end anonymous namespace
Quentin Colombetc32615d2014-10-31 17:52:53 +00006088
6089void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
6090 // At this point, we know that all the operands of ToBePromoted but Def
6091 // can be statically promoted.
6092 // For Def, we need to use its parameter in ToBePromoted:
6093 // b = ToBePromoted ty1 a
6094 // Def = Transition ty1 b to ty2
6095 // Move the transition down.
6096 // 1. Replace all uses of the promoted operation by the transition.
6097 // = ... b => = ... Def.
6098 assert(ToBePromoted->getType() == Transition->getType() &&
6099 "The type of the result of the transition does not match "
6100 "the final type");
6101 ToBePromoted->replaceAllUsesWith(Transition);
6102 // 2. Update the type of the uses.
6103 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
6104 Type *TransitionTy = getTransitionType();
6105 ToBePromoted->mutateType(TransitionTy);
6106 // 3. Update all the operands of the promoted operation with promoted
6107 // operands.
6108 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
6109 for (Use &U : ToBePromoted->operands()) {
6110 Value *Val = U.get();
6111 Value *NewVal = nullptr;
6112 if (Val == Transition)
6113 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
6114 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
6115 isa<ConstantFP>(Val)) {
6116 // Use a splat constant if it is not safe to use undef.
6117 NewVal = getConstantVector(
6118 cast<Constant>(Val),
6119 isa<UndefValue>(Val) ||
6120 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
6121 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00006122 llvm_unreachable("Did you modified shouldPromote and forgot to update "
6123 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006124 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
6125 }
Sanjay Patel674d2c22017-08-29 14:07:48 +00006126 Transition->moveAfter(ToBePromoted);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006127 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6128}
6129
6130/// Some targets can do store(extractelement) with one instruction.
6131/// Try to push the extractelement towards the stores when the target
6132/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006133bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006134 unsigned CombineCost = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006135 if (DisableStoreExtract || !TLI ||
6136 (!StressStoreExtract &&
6137 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
6138 Inst->getOperand(1), CombineCost)))
6139 return false;
6140
6141 // At this point we know that Inst is a vector to scalar transition.
6142 // Try to move it down the def-use chain, until:
6143 // - We can combine the transition with its single use
6144 // => we got rid of the transition.
6145 // - We escape the current basic block
6146 // => we would need to check that we are moving it at a cheaper place and
6147 // we do not do that for now.
6148 BasicBlock *Parent = Inst->getParent();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006149 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00006150 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006151 // If the transition has more than one use, assume this is not going to be
6152 // beneficial.
6153 while (Inst->hasOneUse()) {
6154 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006155 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006156
6157 if (ToBePromoted->getParent() != Parent) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006158 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
6159 << ToBePromoted->getParent()->getName()
6160 << ") than the transition (" << Parent->getName()
6161 << ").\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006162 return false;
6163 }
6164
6165 if (VPH.canCombine(ToBePromoted)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006166 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
6167 << "will be combined with: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006168 VPH.recordCombineInstruction(ToBePromoted);
6169 bool Changed = VPH.promote();
6170 NumStoreExtractExposed += Changed;
6171 return Changed;
6172 }
6173
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006174 LLVM_DEBUG(dbgs() << "Try promoting.\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006175 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6176 return false;
6177
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006178 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006179
6180 VPH.enqueueForPromotion(ToBePromoted);
6181 Inst = ToBePromoted;
6182 }
6183 return false;
6184}
6185
Wei Mia2f0b592016-12-22 19:44:45 +00006186/// For the instruction sequence of store below, F and I values
6187/// are bundled together as an i64 value before being stored into memory.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006188/// Sometimes it is more efficient to generate separate stores for F and I,
Wei Mia2f0b592016-12-22 19:44:45 +00006189/// which can remove the bitwise instructions or sink them to colder places.
6190///
6191/// (store (or (zext (bitcast F to i32) to i64),
6192/// (shl (zext I to i64), 32)), addr) -->
6193/// (store F, addr) and (store I, addr+4)
6194///
6195/// Similarly, splitting for other merged store can also be beneficial, like:
6196/// For pair of {i32, i32}, i64 store --> two i32 stores.
6197/// For pair of {i32, i16}, i64 store --> two i32 stores.
6198/// For pair of {i16, i16}, i32 store --> two i16 stores.
6199/// For pair of {i16, i8}, i32 store --> two i16 stores.
6200/// For pair of {i8, i8}, i16 store --> two i8 stores.
6201///
6202/// We allow each target to determine specifically which kind of splitting is
6203/// supported.
6204///
6205/// The store patterns are commonly seen from the simple code snippet below
6206/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
6207/// void goo(const std::pair<int, float> &);
6208/// hoo() {
6209/// ...
6210/// goo(std::make_pair(tmp, ftmp));
6211/// ...
6212/// }
6213///
6214/// Although we already have similar splitting in DAG Combine, we duplicate
6215/// it in CodeGenPrepare to catch the case in which pattern is across
6216/// multiple BBs. The logic in DAG Combine is kept to catch case generated
6217/// during code expansion.
6218static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
6219 const TargetLowering &TLI) {
6220 // Handle simple but common cases only.
6221 Type *StoreType = SI.getValueOperand()->getType();
6222 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6223 DL.getTypeSizeInBits(StoreType) == 0)
6224 return false;
6225
6226 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6227 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6228 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6229 DL.getTypeSizeInBits(SplitStoreType))
6230 return false;
6231
6232 // Match the following patterns:
6233 // (store (or (zext LValue to i64),
6234 // (shl (zext HValue to i64), 32)), HalfValBitSize)
6235 // or
6236 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6237 // (zext LValue to i64),
6238 // Expect both operands of OR and the first operand of SHL have only
6239 // one use.
6240 Value *LValue, *HValue;
6241 if (!match(SI.getValueOperand(),
6242 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6243 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6244 m_SpecificInt(HalfValBitSize))))))
6245 return false;
6246
6247 // Check LValue and HValue are int with size less or equal than 32.
6248 if (!LValue->getType()->isIntegerTy() ||
6249 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6250 !HValue->getType()->isIntegerTy() ||
6251 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6252 return false;
6253
6254 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6255 // as the input of target query.
6256 auto *LBC = dyn_cast<BitCastInst>(LValue);
6257 auto *HBC = dyn_cast<BitCastInst>(HValue);
6258 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6259 : EVT::getEVT(LValue->getType());
6260 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6261 : EVT::getEVT(HValue->getType());
6262 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6263 return false;
6264
6265 // Start to split store.
6266 IRBuilder<> Builder(SI.getContext());
6267 Builder.SetInsertPoint(&SI);
6268
6269 // If LValue/HValue is a bitcast in another BB, create a new one in current
6270 // BB so it may be merged with the splitted stores by dag combiner.
6271 if (LBC && LBC->getParent() != SI.getParent())
6272 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6273 if (HBC && HBC->getParent() != SI.getParent())
6274 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6275
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006276 bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
Wei Mia2f0b592016-12-22 19:44:45 +00006277 auto CreateSplitStore = [&](Value *V, bool Upper) {
6278 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6279 Value *Addr = Builder.CreateBitCast(
6280 SI.getOperand(1),
6281 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006282 if ((IsLE && Upper) || (!IsLE && !Upper))
Wei Mia2f0b592016-12-22 19:44:45 +00006283 Addr = Builder.CreateGEP(
6284 SplitStoreType, Addr,
6285 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6286 Builder.CreateAlignedStore(
6287 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6288 };
6289
6290 CreateSplitStore(LValue, false);
6291 CreateSplitStore(HValue, true);
6292
6293 // Delete the old store.
6294 SI.eraseFromParent();
6295 return true;
6296}
6297
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006298// Return true if the GEP has two operands, the first operand is of a sequential
6299// type, and the second operand is a constant.
6300static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6301 gep_type_iterator I = gep_type_begin(*GEP);
6302 return GEP->getNumOperands() == 2 &&
6303 I.isSequential() &&
6304 isa<ConstantInt>(GEP->getOperand(1));
6305}
6306
6307// Try unmerging GEPs to reduce liveness interference (register pressure) across
6308// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6309// reducing liveness interference across those edges benefits global register
6310// allocation. Currently handles only certain cases.
6311//
6312// For example, unmerge %GEPI and %UGEPI as below.
6313//
6314// ---------- BEFORE ----------
6315// SrcBlock:
6316// ...
6317// %GEPIOp = ...
6318// ...
6319// %GEPI = gep %GEPIOp, Idx
6320// ...
6321// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6322// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6323// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6324// %UGEPI)
6325//
6326// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6327// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6328// ...
6329//
6330// DstBi:
6331// ...
6332// %UGEPI = gep %GEPIOp, UIdx
6333// ...
6334// ---------------------------
6335//
6336// ---------- AFTER ----------
6337// SrcBlock:
6338// ... (same as above)
6339// (* %GEPI is still alive on the indirectbr edges)
6340// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6341// unmerging)
6342// ...
6343//
6344// DstBi:
6345// ...
6346// %UGEPI = gep %GEPI, (UIdx-Idx)
6347// ...
6348// ---------------------------
6349//
6350// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6351// no longer alive on them.
6352//
6353// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6354// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6355// not to disable further simplications and optimizations as a result of GEP
6356// merging.
6357//
6358// Note this unmerging may increase the length of the data flow critical path
6359// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6360// between the register pressure and the length of data-flow critical
6361// path. Restricting this to the uncommon IndirectBr case would minimize the
6362// impact of potentially longer critical path, if any, and the impact on compile
6363// time.
6364static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6365 const TargetTransformInfo *TTI) {
6366 BasicBlock *SrcBlock = GEPI->getParent();
6367 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6368 // (non-IndirectBr) cases exit early here.
6369 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6370 return false;
6371 // Check that GEPI is a simple gep with a single constant index.
6372 if (!GEPSequentialConstIndexed(GEPI))
6373 return false;
6374 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6375 // Check that GEPI is a cheap one.
6376 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6377 > TargetTransformInfo::TCC_Basic)
6378 return false;
6379 Value *GEPIOp = GEPI->getOperand(0);
6380 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6381 if (!isa<Instruction>(GEPIOp))
6382 return false;
6383 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6384 if (GEPIOpI->getParent() != SrcBlock)
6385 return false;
6386 // Check that GEP is used outside the block, meaning it's alive on the
6387 // IndirectBr edge(s).
6388 if (find_if(GEPI->users(), [&](User *Usr) {
6389 if (auto *I = dyn_cast<Instruction>(Usr)) {
6390 if (I->getParent() != SrcBlock) {
6391 return true;
6392 }
6393 }
6394 return false;
6395 }) == GEPI->users().end())
6396 return false;
6397 // The second elements of the GEP chains to be unmerged.
6398 std::vector<GetElementPtrInst *> UGEPIs;
6399 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6400 // on IndirectBr edges.
6401 for (User *Usr : GEPIOp->users()) {
6402 if (Usr == GEPI) continue;
6403 // Check if Usr is an Instruction. If not, give up.
6404 if (!isa<Instruction>(Usr))
6405 return false;
6406 auto *UI = cast<Instruction>(Usr);
6407 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6408 if (UI->getParent() == SrcBlock)
6409 continue;
6410 // Check if Usr is a GEP. If not, give up.
6411 if (!isa<GetElementPtrInst>(Usr))
6412 return false;
6413 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6414 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6415 // the pointer operand to it. If so, record it in the vector. If not, give
6416 // up.
6417 if (!GEPSequentialConstIndexed(UGEPI))
6418 return false;
6419 if (UGEPI->getOperand(0) != GEPIOp)
6420 return false;
6421 if (GEPIIdx->getType() !=
6422 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6423 return false;
6424 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6425 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6426 > TargetTransformInfo::TCC_Basic)
6427 return false;
6428 UGEPIs.push_back(UGEPI);
6429 }
6430 if (UGEPIs.size() == 0)
6431 return false;
6432 // Check the materializing cost of (Uidx-Idx).
6433 for (GetElementPtrInst *UGEPI : UGEPIs) {
6434 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6435 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6436 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6437 if (ImmCost > TargetTransformInfo::TCC_Basic)
6438 return false;
6439 }
6440 // Now unmerge between GEPI and UGEPIs.
6441 for (GetElementPtrInst *UGEPI : UGEPIs) {
6442 UGEPI->setOperand(0, GEPI);
6443 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6444 Constant *NewUGEPIIdx =
6445 ConstantInt::get(GEPIIdx->getType(),
6446 UGEPIIdx->getValue() - GEPIIdx->getValue());
6447 UGEPI->setOperand(1, NewUGEPIIdx);
6448 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6449 // inbounds to avoid UB.
6450 if (!GEPI->isInBounds()) {
6451 UGEPI->setIsInBounds(false);
6452 }
6453 }
6454 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6455 // alive on IndirectBr edges).
6456 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6457 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6458 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6459 return true;
6460}
6461
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006462bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00006463 // Bail out if we inserted the instruction to prevent optimizations from
6464 // stepping on each other's toes.
6465 if (InsertedInsts.count(I))
6466 return false;
6467
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006468 if (PHINode *P = dyn_cast<PHINode>(I)) {
6469 // It is possible for very late stage optimizations (such as SimplifyCFG)
6470 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6471 // trivial PHI, go ahead and zap it here.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00006472 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006473 P->replaceAllUsesWith(V);
6474 P->eraseFromParent();
6475 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00006476 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006477 }
Chris Lattneree588de2011-01-15 07:29:01 +00006478 return false;
6479 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006480
Chris Lattneree588de2011-01-15 07:29:01 +00006481 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006482 // If the source of the cast is a constant, then this should have
6483 // already been constant folded. The only reason NOT to constant fold
6484 // it is if something (e.g. LSR) was careful to place the constant
6485 // evaluation in a block other than then one that uses it (e.g. to hoist
6486 // the address of globals out of a loop). If this is the case, we don't
6487 // want to forward-subst the cast.
6488 if (isa<Constant>(CI->getOperand(0)))
6489 return false;
6490
Mehdi Amini44ede332015-07-09 02:09:04 +00006491 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00006492 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006493
Chris Lattneree588de2011-01-15 07:29:01 +00006494 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006495 /// Sink a zext or sext into its user blocks if the target type doesn't
6496 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00006497 if (TLI &&
6498 TLI->getTypeAction(CI->getContext(),
6499 TLI->getValueType(*DL, CI->getType())) ==
6500 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006501 return SinkCast(CI);
6502 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00006503 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00006504 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006505 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006506 }
Chris Lattneree588de2011-01-15 07:29:01 +00006507 return false;
6508 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006509
Chris Lattneree588de2011-01-15 07:29:01 +00006510 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00006511 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00006512 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00006513
Chris Lattneree588de2011-01-15 07:29:01 +00006514 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006515 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006516 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006517 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006518 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006519 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6520 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006521 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006522 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006523 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006524
Chris Lattneree588de2011-01-15 07:29:01 +00006525 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006526 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6527 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006528 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006529 if (TLI) {
6530 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006531 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006532 SI->getOperand(0)->getType(), AS);
6533 }
Chris Lattneree588de2011-01-15 07:29:01 +00006534 return false;
6535 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006536
Matt Arsenault02d915b2017-03-15 22:35:20 +00006537 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6538 unsigned AS = RMW->getPointerAddressSpace();
6539 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6540 RMW->getType(), AS);
6541 }
6542
6543 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6544 unsigned AS = CmpX->getPointerAddressSpace();
6545 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6546 CmpX->getCompareOperand()->getType(), AS);
6547 }
6548
Yi Jiangd069f632014-04-21 19:34:27 +00006549 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6550
Geoff Berry5d534b62017-02-21 18:53:14 +00006551 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6552 EnableAndCmpSinking && TLI)
6553 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6554
Yi Jiangd069f632014-04-21 19:34:27 +00006555 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6556 BinOp->getOpcode() == Instruction::LShr)) {
6557 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6558 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006559 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006560
6561 return false;
6562 }
6563
Chris Lattneree588de2011-01-15 07:29:01 +00006564 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006565 if (GEPI->hasAllZeroIndices()) {
6566 /// The GEP operand must be a pointer, so must its result -> BitCast
6567 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6568 GEPI->getName(), GEPI);
Vedant Kumar40399a22018-05-24 23:00:21 +00006569 NC->setDebugLoc(GEPI->getDebugLoc());
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006570 GEPI->replaceAllUsesWith(NC);
6571 GEPI->eraseFromParent();
6572 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00006573 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00006574 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006575 }
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006576 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
6577 return true;
6578 }
Chris Lattneree588de2011-01-15 07:29:01 +00006579 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006580 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006581
Chris Lattneree588de2011-01-15 07:29:01 +00006582 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006583 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006584
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006585 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006586 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006587
Tim Northoveraeb8e062014-02-19 10:02:43 +00006588 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006589 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006590
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006591 if (auto *Switch = dyn_cast<SwitchInst>(I))
6592 return optimizeSwitchInst(Switch);
6593
Quentin Colombetc32615d2014-10-31 17:52:53 +00006594 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006595 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006596
Chris Lattneree588de2011-01-15 07:29:01 +00006597 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006598}
6599
James Molloyf01488e2016-01-15 09:20:19 +00006600/// Given an OR instruction, check to see if this is a bitreverse
6601/// idiom. If so, insert the new intrinsic and return true.
6602static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6603 const TargetLowering &TLI) {
6604 if (!I.getType()->isIntegerTy() ||
6605 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6606 TLI.getValueType(DL, I.getType(), true)))
6607 return false;
6608
6609 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00006610 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00006611 return false;
6612 Instruction *LastInst = Insts.back();
6613 I.replaceAllUsesWith(LastInst);
6614 RecursivelyDeleteTriviallyDeadInstructions(&I);
6615 return true;
6616}
6617
Chris Lattnerf2836d12007-03-31 04:06:36 +00006618// In this pass we look for GEP and cast instructions that are used
6619// across basic blocks and rewrite them to improve basic-block-at-a-time
6620// selection.
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006621bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00006622 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00006623 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00006624
Chris Lattner7a277142011-01-15 07:14:54 +00006625 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006626 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006627 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006628 if (ModifiedDT)
6629 return true;
6630 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00006631
James Molloyf01488e2016-01-15 09:20:19 +00006632 bool MadeBitReverse = true;
6633 while (TLI && MadeBitReverse) {
6634 MadeBitReverse = false;
6635 for (auto &I : reverse(BB)) {
6636 if (makeBitReverse(I, *DL, *TLI)) {
6637 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00006638 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00006639 break;
6640 }
6641 }
6642 }
James Molloy3ef84c42016-01-15 10:36:01 +00006643 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00006644
Chris Lattnerf2836d12007-03-31 04:06:36 +00006645 return MadeChange;
6646}
Devang Patel53771ba2011-08-18 00:50:51 +00006647
6648// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00006649// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00006650// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006651bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00006652 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006653 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00006654 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006655 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006656 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00006657 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00006658 // Leave dbg.values that refer to an alloca alone. These
Craig Topper87e715f2017-11-07 20:56:17 +00006659 // intrinsics describe the address of a variable (= the alloca)
Adrian Prantl32da8892014-04-25 20:49:25 +00006660 // being taken. They should not be moved next to the alloca
6661 // (and to the beginning of the scope), but rather stay close to
6662 // where said address is used.
6663 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00006664 PrevNonDbgInst = Insn;
6665 continue;
6666 }
6667
6668 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6669 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00006670 // If VI is a phi in a block with an EHPad terminator, we can't insert
6671 // after it.
6672 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6673 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006674 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
6675 << *DVI << ' ' << *VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006676 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00006677 if (isa<PHINode>(VI))
6678 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6679 else
6680 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006681 MadeChange = true;
6682 ++NumDbgValueMoved;
6683 }
6684 }
6685 }
6686 return MadeChange;
6687}
Tim Northovercea0abb2014-03-29 08:22:29 +00006688
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006689/// Scale down both weights to fit into uint32_t.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006690static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6691 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006692 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006693 NewTrue = NewTrue / Scale;
6694 NewFalse = NewFalse / Scale;
6695}
6696
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006697/// Some targets prefer to split a conditional branch like:
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006698/// \code
6699/// %0 = icmp ne i32 %a, 0
6700/// %1 = icmp ne i32 %b, 0
6701/// %or.cond = or i1 %0, %1
6702/// br i1 %or.cond, label %TrueBB, label %FalseBB
6703/// \endcode
6704/// into multiple branch instructions like:
6705/// \code
6706/// bb1:
6707/// %0 = icmp ne i32 %a, 0
6708/// br i1 %0, label %TrueBB, label %bb2
6709/// bb2:
6710/// %1 = icmp ne i32 %b, 0
6711/// br i1 %1, label %TrueBB, label %FalseBB
6712/// \endcode
6713/// This usually allows instruction selection to do even further optimizations
6714/// and combine the compare with the branch instruction. Currently this is
6715/// applied for targets which have "cheap" jump instructions.
6716///
6717/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6718///
6719bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006720 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006721 return false;
6722
6723 bool MadeChange = false;
6724 for (auto &BB : F) {
6725 // Does this BB end with the following?
6726 // %cond1 = icmp|fcmp|binary instruction ...
6727 // %cond2 = icmp|fcmp|binary instruction ...
6728 // %cond.or = or|and i1 %cond1, cond2
6729 // br i1 %cond.or label %dest1, label %dest2"
6730 BinaryOperator *LogicOp;
6731 BasicBlock *TBB, *FBB;
6732 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6733 continue;
6734
Sanjay Patel42574202015-09-02 19:23:23 +00006735 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6736 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6737 continue;
6738
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006739 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006740 Value *Cond1, *Cond2;
6741 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6742 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006743 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006744 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6745 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006746 Opc = Instruction::Or;
6747 else
6748 continue;
6749
6750 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6751 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6752 continue;
6753
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006754 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006755
6756 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00006757 auto TmpBB =
6758 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6759 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006760
6761 // Update original basic block by using the first condition directly by the
6762 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006763 Br1->setCondition(Cond1);
6764 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006765
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006766 // Depending on the condition we have to either replace the true or the
6767 // false successor of the original branch instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006768 if (Opc == Instruction::And)
6769 Br1->setSuccessor(0, TmpBB);
6770 else
6771 Br1->setSuccessor(1, TmpBB);
6772
6773 // Fill in the new basic block.
6774 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006775 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6776 I->removeFromParent();
6777 I->insertBefore(Br2);
6778 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006779
6780 // Update PHI nodes in both successors. The original BB needs to be
Hiroshi Inoue6a391bb2017-06-27 10:35:37 +00006781 // replaced in one successor's PHI nodes, because the branch comes now from
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006782 // the newly generated BB (NewBB). In the other successor we need to add one
6783 // incoming edge to the PHI nodes, because both branch instructions target
6784 // now the same successor. Depending on the original branch condition
6785 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006786 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006787 // This doesn't change the successor order of the just created branch
6788 // instruction (or any other instruction).
6789 if (Opc == Instruction::Or)
6790 std::swap(TBB, FBB);
6791
6792 // Replace the old BB with the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006793 for (PHINode &PN : TBB->phis()) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006794 int i;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006795 while ((i = PN.getBasicBlockIndex(&BB)) >= 0)
6796 PN.setIncomingBlock(i, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006797 }
6798
6799 // Add another incoming edge form the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006800 for (PHINode &PN : FBB->phis()) {
6801 auto *Val = PN.getIncomingValueForBlock(&BB);
6802 PN.addIncoming(Val, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006803 }
6804
6805 // Update the branch weights (from SelectionDAGBuilder::
6806 // FindMergedConditions).
6807 if (Opc == Instruction::Or) {
6808 // Codegen X | Y as:
6809 // BB1:
6810 // jmp_if_X TBB
6811 // jmp TmpBB
6812 // TmpBB:
6813 // jmp_if_Y TBB
6814 // jmp FBB
6815 //
6816
6817 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6818 // The requirement is that
6819 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006820 // = TrueProb for original BB.
6821 // Assuming the original weights are A and B, one choice is to set BB1's
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006822 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6823 // assumes that
6824 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6825 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6826 // TmpBB, but the math is more complicated.
6827 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006828 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006829 uint64_t NewTrueWeight = TrueWeight;
6830 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6831 scaleWeights(NewTrueWeight, NewFalseWeight);
6832 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6833 .createBranchWeights(TrueWeight, FalseWeight));
6834
6835 NewTrueWeight = TrueWeight;
6836 NewFalseWeight = 2 * FalseWeight;
6837 scaleWeights(NewTrueWeight, NewFalseWeight);
6838 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6839 .createBranchWeights(TrueWeight, FalseWeight));
6840 }
6841 } else {
6842 // Codegen X & Y as:
6843 // BB1:
6844 // jmp_if_X TmpBB
6845 // jmp FBB
6846 // TmpBB:
6847 // jmp_if_Y TBB
6848 // jmp FBB
6849 //
6850 // This requires creation of TmpBB after CurBB.
6851
6852 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6853 // The requirement is that
6854 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006855 // = FalseProb for original BB.
6856 // Assuming the original weights are A and B, one choice is to set BB1's
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006857 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6858 // assumes that
6859 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6860 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006861 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006862 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6863 uint64_t NewFalseWeight = FalseWeight;
6864 scaleWeights(NewTrueWeight, NewFalseWeight);
6865 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6866 .createBranchWeights(TrueWeight, FalseWeight));
6867
6868 NewTrueWeight = 2 * TrueWeight;
6869 NewFalseWeight = FalseWeight;
6870 scaleWeights(NewTrueWeight, NewFalseWeight);
6871 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6872 .createBranchWeights(TrueWeight, FalseWeight));
6873 }
6874 }
6875
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006876 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00006877 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006878 ModifiedDT = true;
6879
6880 MadeChange = true;
6881
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006882 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6883 TmpBB->dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006884 }
6885 return MadeChange;
6886}