blob: 2d7d0be8f190654afc5d84e1dd5539e89c238181 [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerf2836d12007-03-31 04:06:36 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000010// SelectionDAG-based code generation. This works around limitations in it's
11// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000012//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenko900b6332017-08-29 22:32:07 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000018#include "llvm/ADT/PointerIntPair.h"
19#include "llvm/ADT/STLExtras.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000020#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/ADT/Statistic.h"
Jun Bum Lim90b6b502016-12-16 20:38:39 +000023#include "llvm/Analysis/BlockFrequencyInfo.h"
24#include "llvm/Analysis/BranchProbabilityInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000025#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000027#include "llvm/Analysis/LoopInfo.h"
Zaara Syeda3a7578c2017-05-31 17:12:38 +000028#include "llvm/Analysis/MemoryBuiltins.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000029#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000030#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000031#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000032#include "llvm/Transforms/Utils/Local.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000033#include "llvm/Analysis/ValueTracking.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000034#include "llvm/CodeGen/Analysis.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000035#include "llvm/CodeGen/ISDOpcodes.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000036#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000037#include "llvm/CodeGen/TargetLowering.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000038#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000039#include "llvm/CodeGen/TargetSubtargetInfo.h"
Craig Topper2fa14362018-03-29 17:21:10 +000040#include "llvm/CodeGen/ValueTypes.h"
Nico Weber432a3882018-04-30 14:59:11 +000041#include "llvm/Config/llvm-config.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000042#include "llvm/IR/Argument.h"
43#include "llvm/IR/Attributes.h"
44#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000045#include "llvm/IR/CallSite.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000046#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Constants.h"
48#include "llvm/IR/DataLayout.h"
49#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000050#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000052#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000053#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/IRBuilder.h"
56#include "llvm/IR/InlineAsm.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000057#include "llvm/IR/InstrTypes.h"
58#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000059#include "llvm/IR/Instructions.h"
60#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000061#include "llvm/IR/Intrinsics.h"
62#include "llvm/IR/LLVMContext.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000063#include "llvm/IR/MDBuilder.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000064#include "llvm/IR/Module.h"
65#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000066#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000067#include "llvm/IR/Statepoint.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000068#include "llvm/IR/Type.h"
69#include "llvm/IR/Use.h"
70#include "llvm/IR/User.h"
71#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000072#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000073#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000074#include "llvm/Pass.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000075#include "llvm/Support/BlockFrequency.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000076#include "llvm/Support/BranchProbability.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000077#include "llvm/Support/Casting.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000078#include "llvm/Support/CommandLine.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000079#include "llvm/Support/Compiler.h"
Evan Chengd3d80172007-12-05 23:58:20 +000080#include "llvm/Support/Debug.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000081#include "llvm/Support/ErrorHandling.h"
David Blaikie13e77db2018-03-23 23:58:25 +000082#include "llvm/Support/MachineValueType.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000083#include "llvm/Support/MathExtras.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000084#include "llvm/Support/raw_ostream.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000085#include "llvm/Target/TargetMachine.h"
86#include "llvm/Target/TargetOptions.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000087#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000088#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000089#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000090#include <algorithm>
91#include <cassert>
92#include <cstdint>
93#include <iterator>
94#include <limits>
95#include <memory>
96#include <utility>
97#include <vector>
Zaara Syeda3a7578c2017-05-31 17:12:38 +000098
Chris Lattnerf2836d12007-03-31 04:06:36 +000099using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +0000100using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000101
Chandler Carruth1b9dde02014-04-22 02:02:50 +0000102#define DEBUG_TYPE "codegenprepare"
103
Cameron Zwarichced753f2011-01-05 17:27:27 +0000104STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +0000105STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
106STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +0000107STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
108 "sunken Cmps");
109STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
110 "of sunken Casts");
111STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
112 "computations were sunk");
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000113STATISTIC(NumMemoryInstsPhiCreated,
114 "Number of phis created when address "
115 "computations were sunk to memory instructions");
116STATISTIC(NumMemoryInstsSelectCreated,
117 "Number of select created when address "
118 "computations were sunk to memory instructions");
Evan Cheng0663f232011-03-21 01:19:09 +0000119STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
120STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +0000121STATISTIC(NumAndsAdded,
122 "Number of and mask instructions added to form ext loads");
123STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +0000124STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +0000125STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000126STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +0000127STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +0000128
Cameron Zwarich338d3622011-03-11 21:52:04 +0000129static cl::opt<bool> DisableBranchOpts(
130 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
131 cl::desc("Disable branch optimizations in CodeGenPrepare"));
132
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000133static cl::opt<bool>
134 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
135 cl::desc("Disable GC optimizations in CodeGenPrepare"));
136
Benjamin Kramer3d38c172012-05-06 14:25:16 +0000137static cl::opt<bool> DisableSelectToBranch(
138 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
139 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000140
Hal Finkelc3998302014-04-12 00:59:48 +0000141static cl::opt<bool> AddrSinkUsingGEPs(
Eli Friedman5fba1e52017-04-06 22:42:18 +0000142 "addr-sink-using-gep", cl::Hidden, cl::init(true),
Hal Finkelc3998302014-04-12 00:59:48 +0000143 cl::desc("Address sinking in CGP using GEPs."));
144
Tim Northovercea0abb2014-03-29 08:22:29 +0000145static cl::opt<bool> EnableAndCmpSinking(
146 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
147 cl::desc("Enable sinkinig and/cmp into branches."));
148
Quentin Colombetc32615d2014-10-31 17:52:53 +0000149static cl::opt<bool> DisableStoreExtract(
150 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
151 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
152
153static cl::opt<bool> StressStoreExtract(
154 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
155 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
156
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000157static cl::opt<bool> DisableExtLdPromotion(
158 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
159 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
160 "CodeGenPrepare"));
161
162static cl::opt<bool> StressExtLdPromotion(
163 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
164 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
165 "optimization in CodeGenPrepare"));
166
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000167static cl::opt<bool> DisablePreheaderProtect(
168 "disable-preheader-prot", cl::Hidden, cl::init(false),
169 cl::desc("Disable protection against removing loop preheaders"));
170
Dehao Chen302b69c2016-10-18 20:42:47 +0000171static cl::opt<bool> ProfileGuidedSectionPrefix(
David Callahan5960d9b12017-06-14 20:35:33 +0000172 "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
Dehao Chen302b69c2016-10-18 20:42:47 +0000173 cl::desc("Use profile info to add section prefix for hot/cold functions"));
174
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000175static cl::opt<unsigned> FreqRatioToSkipMerge(
176 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
177 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
178 "(frequency of destination block) is greater than this ratio"));
179
Wei Mia2f0b592016-12-22 19:44:45 +0000180static cl::opt<bool> ForceSplitStore(
181 "force-split-store", cl::Hidden, cl::init(false),
182 cl::desc("Force store splitting no matter what the target query says."));
183
Jun Bum Limdee55652017-04-03 19:20:07 +0000184static cl::opt<bool>
185EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
186 cl::desc("Enable merging of redundant sexts when one is dominating"
187 " the other."), cl::init(true));
188
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000189static cl::opt<bool> DisableComplexAddrModes(
Serguei Katkovd4df7442017-11-29 09:48:50 +0000190 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000191 cl::desc("Disables combining addressing modes with different parts "
192 "in optimizeMemoryInst."));
193
194static cl::opt<bool>
195AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
196 cl::desc("Allow creation of Phis in Address sinking."));
197
198static cl::opt<bool>
Serguei Katkov9fe05242018-01-26 06:26:56 +0000199AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000200 cl::desc("Allow creation of selects in Address sinking."));
201
John Brawn70cdb5b2017-11-24 14:10:45 +0000202static cl::opt<bool> AddrSinkCombineBaseReg(
203 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
204 cl::desc("Allow combining of BaseReg field in Address sinking."));
205
206static cl::opt<bool> AddrSinkCombineBaseGV(
207 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
208 cl::desc("Allow combining of BaseGV field in Address sinking."));
209
210static cl::opt<bool> AddrSinkCombineBaseOffs(
211 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
212 cl::desc("Allow combining of BaseOffs field in Address sinking."));
213
214static cl::opt<bool> AddrSinkCombineScaledReg(
215 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
216 cl::desc("Allow combining of ScaledReg field in Address sinking."));
217
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000218static cl::opt<bool>
219 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
220 cl::init(true),
221 cl::desc("Enable splitting large offset of GEP."));
222
Eric Christopherc1ea1492008-09-24 05:32:41 +0000223namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000224
Guozhi Wei8c17f9a2018-08-15 22:08:26 +0000225enum ExtType {
226 ZeroExtension, // Zero extension has been seen.
227 SignExtension, // Sign extension has been seen.
228 BothExtension // This extension type is used if we saw sext after
229 // ZeroExtension had been set, or if we saw zext after
230 // SignExtension had been set. It makes the type
231 // information of a promoted instruction invalid.
232};
233
Eugene Zelenko900b6332017-08-29 22:32:07 +0000234using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
Guozhi Wei8c17f9a2018-08-15 22:08:26 +0000235using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000236using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
237using SExts = SmallVector<Instruction *, 16>;
238using ValueToSExts = DenseMap<Value *, SExts>;
239
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000240class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000241
Chris Lattner2dd09db2009-09-02 06:11:42 +0000242 class CodeGenPrepare : public FunctionPass {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000243 const TargetMachine *TM = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000244 const TargetSubtargetInfo *SubtargetInfo;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000245 const TargetLowering *TLI = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000246 const TargetRegisterInfo *TRI;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000247 const TargetTransformInfo *TTI = nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000248 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000249 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000250 std::unique_ptr<BlockFrequencyInfo> BFI;
251 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000252
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000253 /// As we scan instructions optimizing them, this is the next instruction
254 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000255 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000256
Evan Cheng0663f232011-03-21 01:19:09 +0000257 /// Keeps track of non-local addresses that have been sunk into a block.
258 /// This allows us to avoid inserting duplicate code for blocks with
Simon Dardis230f4532017-11-24 16:45:28 +0000259 /// multiple load/stores of the same address. The usage of WeakTrackingVH
260 /// enables SunkAddrs to be treated as a cache whose entries can be
261 /// invalidated if a sunken address computation has been erased.
262 ValueMap<Value*, WeakTrackingVH> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000263
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000264 /// Keeps track of all instructions inserted for the current function.
265 SetOfInstrs InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000266
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000267 /// Keeps track of the type of the related instruction before their
268 /// promotion for the current function.
269 InstrToOrigTy PromotedInsts;
270
Jun Bum Limdee55652017-04-03 19:20:07 +0000271 /// Keep track of instructions removed during promotion.
272 SetOfInstrs RemovedInsts;
273
274 /// Keep track of sext chains based on their initial value.
275 DenseMap<Value *, Instruction *> SeenChainsForSExt;
276
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000277 /// Keep track of GEPs accessing the same data structures such as structs or
278 /// arrays that are candidates to be split later because of their large
279 /// size.
David Greene27e87c2018-09-12 10:19:10 +0000280 MapVector<
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000281 AssertingVH<Value>,
282 SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
283 LargeOffsetGEPMap;
284
285 /// Keep track of new GEP base after splitting the GEPs having large offset.
286 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
287
288 /// Map serial numbers to Large offset GEPs.
289 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
290
Jun Bum Limdee55652017-04-03 19:20:07 +0000291 /// Keep track of SExt promoted.
292 ValueToSExts ValToSExtendedUses;
293
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000294 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000295 bool OptSize;
296
Mehdi Amini4fe37982015-07-07 18:45:17 +0000297 /// DataLayout for the Function being processed.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000298 const DataLayout *DL = nullptr;
Mehdi Amini4fe37982015-07-07 18:45:17 +0000299
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +0000300 /// Building the dominator tree can be expensive, so we only build it
301 /// lazily and update it when required.
302 std::unique_ptr<DominatorTree> DT;
303
Chris Lattnerf2836d12007-03-31 04:06:36 +0000304 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000305 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000306
307 CodeGenPrepare() : FunctionPass(ID) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000308 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
309 }
Eugene Zelenko900b6332017-08-29 22:32:07 +0000310
Craig Topper4584cd52014-03-07 09:26:03 +0000311 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000312
Mehdi Amini117296c2016-10-01 02:56:57 +0000313 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000314
Craig Topper4584cd52014-03-07 09:26:03 +0000315 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000316 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000317 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000318 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000319 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000320 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000321 }
322
Chris Lattnerf2836d12007-03-31 04:06:36 +0000323 private:
James Y Knight72f76bf2018-11-07 15:24:12 +0000324 template <typename F>
325 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
326 // Substituting can cause recursive simplifications, which can invalidate
327 // our iterator. Use a WeakTrackingVH to hold onto it in case this
328 // happens.
329 Value *CurValue = &*CurInstIterator;
330 WeakTrackingVH IterHandle(CurValue);
331
332 f();
333
334 // If the iterator instruction was recursively deleted, start over at the
335 // start of the block.
336 if (IterHandle != CurValue) {
337 CurInstIterator = BB->begin();
338 SunkAddrs.clear();
339 }
340 }
341
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +0000342 // Get the DominatorTree, building if necessary.
343 DominatorTree &getDT(Function &F) {
344 if (!DT)
345 DT = llvm::make_unique<DominatorTree>(F);
346 return *DT;
347 }
348
Sanjay Patelfc580a62015-09-21 23:03:16 +0000349 bool eliminateFallThrough(Function &F);
350 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000351 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000352 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
353 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000354 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
355 bool isPreheader);
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +0000356 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
357 bool optimizeInst(Instruction *I, bool &ModifiedDT);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000358 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
359 Type *AccessTy, unsigned AddrSpace);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000360 bool optimizeInlineAsmInst(CallInst *CS);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000361 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000362 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000363 bool optimizeExtUses(Instruction *I);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000364 bool optimizeLoadExt(LoadInst *Load);
Teresa Johnsonb7e21382019-03-27 18:44:25 +0000365 bool optimizeSelectInst(SelectInst *SI);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000366 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
367 bool optimizeSwitchInst(SwitchInst *SI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000368 bool optimizeExtractElementInst(Instruction *Inst);
Rong Xuce3be452019-03-08 22:46:18 +0000369 bool dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000370 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000371 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
372 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
373 bool tryToPromoteExts(TypePromotionTransaction &TPT,
374 const SmallVectorImpl<Instruction *> &Exts,
375 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
376 unsigned CreatedInstsCost = 0);
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +0000377 bool mergeSExts(Function &F);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000378 bool splitLargeGEPOffsets();
Jun Bum Limdee55652017-04-03 19:20:07 +0000379 bool performAddressTypePromotion(
380 Instruction *&Inst,
381 bool AllowPromotionWithoutCommonHeader,
382 bool HasPromoted, TypePromotionTransaction &TPT,
383 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Rong Xuce3be452019-03-08 22:46:18 +0000384 bool splitBranchCondition(Function &F, bool &ModifiedDT);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000385 bool simplifyOffsetableRelocate(Instruction &I);
Florian Hahn3b251962019-02-05 10:27:40 +0000386
387 bool tryToSinkFreeOperands(Instruction *I);
Teresa Johnson4dc85192019-03-24 15:18:50 +0000388 bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, CmpInst *Cmp,
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +0000389 Intrinsic::ID IID);
390 bool optimizeCmp(CmpInst *Cmp, bool &ModifiedDT);
391 bool combineToUSubWithOverflow(CmpInst *Cmp, bool &ModifiedDT);
392 bool combineToUAddWithOverflow(CmpInst *Cmp, bool &ModifiedDT);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000393 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000394
395} // end anonymous namespace
Devang Patel09f162c2007-05-01 21:15:47 +0000396
Devang Patel8c78a0b2007-05-03 01:11:54 +0000397char CodeGenPrepare::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000398
Matthias Braun1527baa2017-05-25 21:26:32 +0000399INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000400 "Optimize for code generation", false, false)
Dehao Chen302b69c2016-10-18 20:42:47 +0000401INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000402INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000403 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000404
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000405FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000406
Chris Lattnerf2836d12007-03-31 04:06:36 +0000407bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000408 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000409 return false;
410
Mehdi Amini4fe37982015-07-07 18:45:17 +0000411 DL = &F.getParent()->getDataLayout();
412
Chris Lattnerf2836d12007-03-31 04:06:36 +0000413 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000414 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000415 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000416 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000417
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000418 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
419 TM = &TPC->getTM<TargetMachine>();
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000420 SubtargetInfo = TM->getSubtargetImpl(F);
421 TLI = SubtargetInfo->getTargetLowering();
422 TRI = SubtargetInfo->getRegisterInfo();
423 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000424 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000425 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000426 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000427 BPI.reset(new BranchProbabilityInfo(F, *LI));
428 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
Evandro Menezes85bd3972019-04-04 22:40:06 +0000429 OptSize = F.hasOptSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000430
Easwaran Raman0d55b552017-11-14 19:31:51 +0000431 ProfileSummaryInfo *PSI =
Vedant Kumare7b789b2018-11-19 05:23:16 +0000432 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen302b69c2016-10-18 20:42:47 +0000433 if (ProfileGuidedSectionPrefix) {
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000434 if (PSI->isFunctionHotInCallGraph(&F, *BFI))
Dehao Chen302b69c2016-10-18 20:42:47 +0000435 F.setSectionPrefix(".hot");
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000436 else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
Teresa Johnson720d9b42017-05-09 01:43:24 +0000437 F.setSectionPrefix(".unlikely");
Dehao Chen302b69c2016-10-18 20:42:47 +0000438 }
439
Preston Gurdcdf540d2012-09-04 18:22:17 +0000440 /// This optimization identifies DIV instructions that can be
441 /// profitably bypassed and carried out with a shorter, faster divide.
Easwaran Raman0d55b552017-11-14 19:31:51 +0000442 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
443 TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000444 const DenseMap<unsigned int, unsigned int> &BypassWidths =
445 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000446 BasicBlock* BB = &*F.begin();
447 while (BB != nullptr) {
448 // bypassSlowDivision may create new BBs, but we don't want to reapply the
449 // optimization to those blocks.
450 BasicBlock* Next = BB->getNextNode();
451 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
452 BB = Next;
453 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000454 }
455
456 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000457 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000458 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000459
Rong Xuce3be452019-03-08 22:46:18 +0000460 bool ModifiedDT = false;
Geoff Berry5d534b62017-02-21 18:53:14 +0000461 if (!DisableBranchOpts)
Rong Xuce3be452019-03-08 22:46:18 +0000462 EverMadeChange |= splitBranchCondition(F, ModifiedDT);
Tim Northovercea0abb2014-03-29 08:22:29 +0000463
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000464 // Split some critical edges where one of the sources is an indirect branch,
465 // to help generate sane code for PHIs involving such edges.
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000466 EverMadeChange |= SplitIndirectBrCriticalEdges(F);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000467
Chris Lattnerc3748562007-04-02 01:35:34 +0000468 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000469 while (MadeChange) {
470 MadeChange = false;
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +0000471 DT.reset();
Hans Wennborg02fbc712012-09-19 07:48:16 +0000472 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000473 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000474 bool ModifiedDTOnIteration = false;
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +0000475 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000476
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000477 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000478 if (ModifiedDTOnIteration)
479 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000480 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000481 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +0000482 MadeChange |= mergeSExts(F);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000483 if (!LargeOffsetGEPMap.empty())
484 MadeChange |= splitLargeGEPOffsets();
Jun Bum Limdee55652017-04-03 19:20:07 +0000485
486 // Really free removed instructions during promotion.
487 for (Instruction *I : RemovedInsts)
Reid Kleckner96ab8722017-05-18 17:24:10 +0000488 I->deleteValue();
Jun Bum Limdee55652017-04-03 19:20:07 +0000489
Chris Lattnerf2836d12007-03-31 04:06:36 +0000490 EverMadeChange |= MadeChange;
Peter Collingbourneabd820a2018-10-23 21:23:18 +0000491 SeenChainsForSExt.clear();
492 ValToSExtendedUses.clear();
493 RemovedInsts.clear();
494 LargeOffsetGEPMap.clear();
495 LargeOffsetGEPID.clear();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000496 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000497
498 SunkAddrs.clear();
499
Cameron Zwarich338d3622011-03-11 21:52:04 +0000500 if (!DisableBranchOpts) {
501 MadeChange = false;
David Stenberg23bba562018-07-02 14:23:48 +0000502 // Use a set vector to get deterministic iteration order. The order the
503 // blocks are removed may affect whether or not PHI nodes in successors
504 // are removed.
505 SmallSetVector<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000506 for (BasicBlock &BB : F) {
507 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
508 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000509 if (!MadeChange) continue;
510
511 for (SmallVectorImpl<BasicBlock*>::iterator
512 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
513 if (pred_begin(*II) == pred_end(*II))
514 WorkList.insert(*II);
515 }
516
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000517 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000518 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000519 while (!WorkList.empty()) {
David Stenberg23bba562018-07-02 14:23:48 +0000520 BasicBlock *BB = WorkList.pop_back_val();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000521 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
522
523 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000524
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000525 for (SmallVectorImpl<BasicBlock*>::iterator
526 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
527 if (pred_begin(*II) == pred_end(*II))
528 WorkList.insert(*II);
529 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000530
Nadav Rotem70409992012-08-14 05:19:07 +0000531 // Merge pairs of basic blocks with unconditional branches, connected by
532 // a single edge.
533 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000534 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000535
Cameron Zwarich338d3622011-03-11 21:52:04 +0000536 EverMadeChange |= MadeChange;
537 }
538
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000539 if (!DisableGCOpts) {
540 SmallVector<Instruction *, 2> Statepoints;
541 for (BasicBlock &BB : F)
542 for (Instruction &I : BB)
543 if (isStatepoint(I))
544 Statepoints.push_back(&I);
545 for (auto &I : Statepoints)
546 EverMadeChange |= simplifyOffsetableRelocate(*I);
547 }
548
Vedant Kumar30406fd2018-08-21 23:43:08 +0000549 // Do this last to clean up use-before-def scenarios introduced by other
550 // preparatory transforms.
551 EverMadeChange |= placeDbgValues(F);
552
Chris Lattnerf2836d12007-03-31 04:06:36 +0000553 return EverMadeChange;
554}
555
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000556/// Merge basic blocks which are connected by a single edge, where one of the
557/// basic blocks has a single successor pointing to the other basic block,
558/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000559bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000560 bool Changed = false;
561 // Scan all of the blocks in the function, except for the entry block.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000562 // Use a temporary array to avoid iterator being invalidated when
563 // deleting blocks.
564 SmallVector<WeakTrackingVH, 16> Blocks;
565 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
566 Blocks.push_back(&Block);
567
568 for (auto &Block : Blocks) {
569 auto *BB = cast_or_null<BasicBlock>(Block);
570 if (!BB)
571 continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000572 // If the destination block has a single pred, then this is a trivial
573 // edge, just collapse it.
574 BasicBlock *SinglePred = BB->getSinglePredecessor();
575
Evan Cheng64a223a2012-09-28 23:58:57 +0000576 // Don't merge if BB's address is taken.
577 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000578
579 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
580 if (Term && !Term->isConditional()) {
581 Changed = true;
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000582 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000583
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000584 // Merge BB into SinglePred and delete it.
585 MergeBlockIntoPredecessor(BB);
Nadav Rotem70409992012-08-14 05:19:07 +0000586 }
587 }
588 return Changed;
589}
590
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000591/// Find a destination block from BB if BB is mergeable empty block.
592BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
593 // If this block doesn't end with an uncond branch, ignore it.
594 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
595 if (!BI || !BI->isUnconditional())
596 return nullptr;
597
598 // If the instruction before the branch (skipping debug info) isn't a phi
599 // node, then other stuff is happening here.
600 BasicBlock::iterator BBI = BI->getIterator();
601 if (BBI != BB->begin()) {
602 --BBI;
603 while (isa<DbgInfoIntrinsic>(BBI)) {
604 if (BBI == BB->begin())
605 break;
606 --BBI;
607 }
608 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
609 return nullptr;
610 }
611
612 // Do not break infinite loops.
613 BasicBlock *DestBB = BI->getSuccessor(0);
614 if (DestBB == BB)
615 return nullptr;
616
617 if (!canMergeBlocks(BB, DestBB))
618 DestBB = nullptr;
619
620 return DestBB;
621}
622
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000623/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
624/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
625/// edges in ways that are non-optimal for isel. Start by eliminating these
626/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000627bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000628 SmallPtrSet<BasicBlock *, 16> Preheaders;
629 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
630 while (!LoopList.empty()) {
631 Loop *L = LoopList.pop_back_val();
632 LoopList.insert(LoopList.end(), L->begin(), L->end());
633 if (BasicBlock *Preheader = L->getLoopPreheader())
634 Preheaders.insert(Preheader);
635 }
636
Chris Lattnerc3748562007-04-02 01:35:34 +0000637 bool MadeChange = false;
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000638 // Copy blocks into a temporary array to avoid iterator invalidation issues
639 // as we remove them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000640 // Note that this intentionally skips the entry block.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000641 SmallVector<WeakTrackingVH, 16> Blocks;
642 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
643 Blocks.push_back(&Block);
644
645 for (auto &Block : Blocks) {
646 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
647 if (!BB)
648 continue;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000649 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
650 if (!DestBB ||
651 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000652 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000653
Sanjay Patelfc580a62015-09-21 23:03:16 +0000654 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000655 MadeChange = true;
656 }
657 return MadeChange;
658}
659
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000660bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
661 BasicBlock *DestBB,
662 bool isPreheader) {
663 // Do not delete loop preheaders if doing so would create a critical edge.
664 // Loop preheaders can be good locations to spill registers. If the
665 // preheader is deleted and we create a critical edge, registers may be
666 // spilled in the loop body instead.
667 if (!DisablePreheaderProtect && isPreheader &&
668 !(BB->getSinglePredecessor() &&
669 BB->getSinglePredecessor()->getSingleSuccessor()))
670 return false;
671
Craig Topper784929d2019-02-08 20:48:56 +0000672 // Skip merging if the block's successor is also a successor to any callbr
673 // that leads to this block.
674 // FIXME: Is this really needed? Is this a correctness issue?
675 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
676 if (auto *CBI = dyn_cast<CallBrInst>((*PI)->getTerminator()))
677 for (unsigned i = 0, e = CBI->getNumSuccessors(); i != e; ++i)
678 if (DestBB == CBI->getSuccessor(i))
679 return false;
680 }
681
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000682 // Try to skip merging if the unique predecessor of BB is terminated by a
683 // switch or indirect branch instruction, and BB is used as an incoming block
684 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
685 // add COPY instructions in the predecessor of BB instead of BB (if it is not
686 // merged). Note that the critical edge created by merging such blocks wont be
687 // split in MachineSink because the jump table is not analyzable. By keeping
688 // such empty block (BB), ISel will place COPY instructions in BB, not in the
689 // predecessor of BB.
690 BasicBlock *Pred = BB->getUniquePredecessor();
691 if (!Pred ||
692 !(isa<SwitchInst>(Pred->getTerminator()) ||
693 isa<IndirectBrInst>(Pred->getTerminator())))
694 return true;
695
Jonas Devlieghere42243df2018-08-07 12:14:01 +0000696 if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000697 return true;
698
699 // We use a simple cost heuristic which determine skipping merging is
700 // profitable if the cost of skipping merging is less than the cost of
701 // merging : Cost(skipping merging) < Cost(merging BB), where the
702 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
703 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
704 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
705 // Freq(Pred) / Freq(BB) > 2.
706 // Note that if there are multiple empty blocks sharing the same incoming
707 // value for the PHIs in the DestBB, we consider them together. In such
708 // case, Cost(merging BB) will be the sum of their frequencies.
709
710 if (!isa<PHINode>(DestBB->begin()))
711 return true;
712
713 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
714
715 // Find all other incoming blocks from which incoming values of all PHIs in
716 // DestBB are the same as the ones from BB.
717 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
718 ++PI) {
719 BasicBlock *DestBBPred = *PI;
720 if (DestBBPred == BB)
721 continue;
722
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000723 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
724 return DestPN.getIncomingValueForBlock(BB) ==
725 DestPN.getIncomingValueForBlock(DestBBPred);
726 }))
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000727 SameIncomingValueBBs.insert(DestBBPred);
728 }
729
730 // See if all BB's incoming values are same as the value from Pred. In this
731 // case, no reason to skip merging because COPYs are expected to be place in
732 // Pred already.
733 if (SameIncomingValueBBs.count(Pred))
734 return true;
735
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000736 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
737 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
738
739 for (auto SameValueBB : SameIncomingValueBBs)
740 if (SameValueBB->getUniquePredecessor() == Pred &&
741 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
742 BBFreq += BFI->getBlockFreq(SameValueBB);
743
744 return PredFreq.getFrequency() <=
745 BBFreq.getFrequency() * FreqRatioToSkipMerge;
746}
747
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000748/// Return true if we can merge BB into DestBB if there is a single
749/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000750/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000751bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000752 const BasicBlock *DestBB) const {
753 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
754 // the successor. If there are more complex condition (e.g. preheaders),
755 // don't mess around with them.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000756 for (const PHINode &PN : BB->phis()) {
757 for (const User *U : PN.users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000758 const Instruction *UI = cast<Instruction>(U);
759 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000760 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000761 // If User is inside DestBB block and it is a PHINode then check
762 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000763 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000764 if (UI->getParent() == DestBB) {
765 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000766 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
767 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
768 if (Insn && Insn->getParent() == BB &&
769 Insn->getParent() != UPN->getIncomingBlock(I))
770 return false;
771 }
772 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000773 }
774 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000775
Chris Lattnerc3748562007-04-02 01:35:34 +0000776 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
777 // and DestBB may have conflicting incoming values for the block. If so, we
778 // can't merge the block.
779 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
780 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000781
Chris Lattnerc3748562007-04-02 01:35:34 +0000782 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000783 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000784 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
785 // It is faster to get preds from a PHI than with pred_iterator.
786 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
787 BBPreds.insert(BBPN->getIncomingBlock(i));
788 } else {
789 BBPreds.insert(pred_begin(BB), pred_end(BB));
790 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000791
Chris Lattnerc3748562007-04-02 01:35:34 +0000792 // Walk the preds of DestBB.
793 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
794 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
795 if (BBPreds.count(Pred)) { // Common predecessor?
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000796 for (const PHINode &PN : DestBB->phis()) {
797 const Value *V1 = PN.getIncomingValueForBlock(Pred);
798 const Value *V2 = PN.getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000799
Chris Lattnerc3748562007-04-02 01:35:34 +0000800 // If V2 is a phi node in BB, look up what the mapped value will be.
801 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
802 if (V2PN->getParent() == BB)
803 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000804
Chris Lattnerc3748562007-04-02 01:35:34 +0000805 // If there is a conflict, bail out.
806 if (V1 != V2) return false;
807 }
808 }
809 }
810
811 return true;
812}
813
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000814/// Eliminate a basic block that has only phi's and an unconditional branch in
815/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000816void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000817 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
818 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000819
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000820 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
821 << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000822
Chris Lattnerc3748562007-04-02 01:35:34 +0000823 // If the destination block has a single pred, then this is a trivial edge,
824 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000825 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000826 if (SinglePred != DestBB) {
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000827 assert(SinglePred == BB &&
828 "Single predecessor not the same as predecessor");
829 // Merge DestBB into SinglePred/BB and delete it.
830 MergeBlockIntoPredecessor(DestBB);
831 // Note: BB(=SinglePred) will not be deleted on this path.
832 // DestBB(=its single successor) is the one that was deleted.
833 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000834 return;
835 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000836 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000837
Chris Lattnerc3748562007-04-02 01:35:34 +0000838 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
839 // to handle the new incoming edges it is about to have.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000840 for (PHINode &PN : DestBB->phis()) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000841 // Remove the incoming value for BB, and remember it.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000842 Value *InVal = PN.removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000843
Chris Lattnerc3748562007-04-02 01:35:34 +0000844 // Two options: either the InVal is a phi node defined in BB or it is some
845 // value that dominates BB.
846 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
847 if (InValPhi && InValPhi->getParent() == BB) {
848 // Add all of the input values of the input PHI as inputs of this phi.
849 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000850 PN.addIncoming(InValPhi->getIncomingValue(i),
851 InValPhi->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000852 } else {
853 // Otherwise, add one instance of the dominating value for each edge that
854 // we will be adding.
855 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
856 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000857 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000858 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000859 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000860 PN.addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000861 }
862 }
863 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000864
Chris Lattnerc3748562007-04-02 01:35:34 +0000865 // The PHIs are now updated, change everything that refers to BB to use
866 // DestBB and remove BB.
867 BB->replaceAllUsesWith(DestBB);
868 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000869 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000870
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000871 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000872}
873
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000874// Computes a map of base pointer relocation instructions to corresponding
875// derived pointer relocation instructions given a vector of all relocate calls
876static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000877 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
878 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
879 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000880 // Collect information in two maps: one primarily for locating the base object
881 // while filling the second map; the second map is the final structure holding
882 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000883 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
884 for (auto *ThisRelocate : AllRelocateCalls) {
885 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
886 ThisRelocate->getDerivedPtrIndex());
887 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000888 }
889 for (auto &Item : RelocateIdxMap) {
890 std::pair<unsigned, unsigned> Key = Item.first;
891 if (Key.first == Key.second)
892 // Base relocation: nothing to insert
893 continue;
894
Manuel Jacob83eefa62016-01-05 04:03:00 +0000895 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000896 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000897
898 // We're iterating over RelocateIdxMap so we cannot modify it.
899 auto MaybeBase = RelocateIdxMap.find(BaseKey);
900 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000901 // TODO: We might want to insert a new base object relocate and gep off
902 // that, if there are enough derived object relocates.
903 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000904
905 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000906 }
907}
908
909// Accepts a GEP and extracts the operands into a vector provided they're all
910// small integer constants
911static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
912 SmallVectorImpl<Value *> &OffsetV) {
913 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
914 // Only accept small constant integer operands
915 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
916 if (!Op || Op->getZExtValue() > 20)
917 return false;
918 }
919
920 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
921 OffsetV.push_back(GEP->getOperand(i));
922 return true;
923}
924
925// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
926// replace, computes a replacement, and affects it.
927static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000928simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
929 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000930 bool MadeChange = false;
Serguei Katkov9e5604d2017-08-17 05:48:30 +0000931 // We must ensure the relocation of derived pointer is defined after
932 // relocation of base pointer. If we find a relocation corresponding to base
933 // defined earlier than relocation of base then we move relocation of base
934 // right before found relocation. We consider only relocation in the same
935 // basic block as relocation of base. Relocations from other basic block will
936 // be skipped by optimization and we do not care about them.
937 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
938 &*R != RelocatedBase; ++R)
939 if (auto RI = dyn_cast<GCRelocateInst>(R))
940 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
941 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
942 RelocatedBase->moveBefore(RI);
943 break;
944 }
945
Manuel Jacob83eefa62016-01-05 04:03:00 +0000946 for (GCRelocateInst *ToReplace : Targets) {
947 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000948 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000949 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000950 // A duplicate relocate call. TODO: coalesce duplicates.
951 continue;
952 }
953
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000954 if (RelocatedBase->getParent() != ToReplace->getParent()) {
955 // Base and derived relocates are in different basic blocks.
956 // In this case transform is only valid when base dominates derived
957 // relocate. However it would be too expensive to check dominance
958 // for each such relocate, so we skip the whole transformation.
959 continue;
960 }
961
Manuel Jacob83eefa62016-01-05 04:03:00 +0000962 Value *Base = ToReplace->getBasePtr();
963 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000964 if (!Derived || Derived->getPointerOperand() != Base)
965 continue;
966
967 SmallVector<Value *, 2> OffsetV;
968 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
969 continue;
970
971 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000972 assert(RelocatedBase->getNextNode() &&
973 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000974
975 // Insert after RelocatedBase
976 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000977 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000978
979 // If gc_relocate does not match the actual type, cast it to the right type.
980 // In theory, there must be a bitcast after gc_relocate if the type does not
981 // match, and we should reuse it to get the derived pointer. But it could be
982 // cases like this:
983 // bb1:
984 // ...
985 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
986 // br label %merge
987 //
988 // bb2:
989 // ...
990 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
991 // br label %merge
992 //
993 // merge:
994 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
995 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
996 //
997 // In this case, we can not find the bitcast any more. So we insert a new bitcast
998 // no matter there is already one or not. In this way, we can handle all cases, and
999 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +00001000 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +00001001 if (RelocatedBase->getType() != Base->getType()) {
1002 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +00001003 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +00001004 }
David Blaikie68d535c2015-03-24 22:38:16 +00001005 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +00001006 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001007 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +00001008 // If the newly generated derived pointer's type does not match the original derived
1009 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +00001010 Value *ActualReplacement = Replacement;
1011 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +00001012 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +00001013 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +00001014 }
1015 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001016 ToReplace->eraseFromParent();
1017
1018 MadeChange = true;
1019 }
1020 return MadeChange;
1021}
1022
1023// Turns this:
1024//
1025// %base = ...
1026// %ptr = gep %base + 15
1027// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1028// %base' = relocate(%tok, i32 4, i32 4)
1029// %ptr' = relocate(%tok, i32 4, i32 5)
1030// %val = load %ptr'
1031//
1032// into this:
1033//
1034// %base = ...
1035// %ptr = gep %base + 15
1036// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1037// %base' = gc.relocate(%tok, i32 4, i32 4)
1038// %ptr' = gep %base' + 15
1039// %val = load %ptr'
1040bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1041 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +00001042 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001043
1044 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +00001045 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001046 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +00001047 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001048
1049 // We need atleast one base pointer relocation + one derived pointer
1050 // relocation to mangle
1051 if (AllRelocateCalls.size() < 2)
1052 return false;
1053
1054 // RelocateInstMap is a mapping from the base relocate instruction to the
1055 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +00001056 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001057 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1058 if (RelocateInstMap.empty())
1059 return false;
1060
1061 for (auto &Item : RelocateInstMap)
1062 // Item.first is the RelocatedBase to offset against
1063 // Item.second is the vector of Targets to replace
1064 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1065 return MadeChange;
1066}
1067
Sanjay Patel7d8260f2019-03-10 18:42:30 +00001068/// Sink the specified cast instruction into its user blocks.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001069static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001070 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001071
Chris Lattnerf2836d12007-03-31 04:06:36 +00001072 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001073 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001074
Chris Lattnerf2836d12007-03-31 04:06:36 +00001075 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001076 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001077 UI != E; ) {
1078 Use &TheUse = UI.getUse();
1079 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001080
Chris Lattnerf2836d12007-03-31 04:06:36 +00001081 // Figure out which BB this cast is used in. For PHI's this is the
1082 // appropriate predecessor block.
1083 BasicBlock *UserBB = User->getParent();
1084 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001085 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001086 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001087
Chris Lattnerf2836d12007-03-31 04:06:36 +00001088 // Preincrement use iterator so we don't invalidate it.
1089 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001090
David Majnemer0c80e2e2016-04-27 19:36:38 +00001091 // The first insertion point of a block containing an EH pad is after the
1092 // pad. If the pad is the user, we cannot sink the cast past the pad.
1093 if (User->isEHPad())
1094 continue;
1095
Andrew Kaylord0430e82015-11-23 19:16:15 +00001096 // If the block selected to receive the cast is an EH pad that does not
1097 // allow non-PHI instructions before the terminator, we can't sink the
1098 // cast.
1099 if (UserBB->getTerminator()->isEHPad())
1100 continue;
1101
Chris Lattnerf2836d12007-03-31 04:06:36 +00001102 // If this user is in the same block as the cast, don't change the cast.
1103 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001104
Chris Lattnerf2836d12007-03-31 04:06:36 +00001105 // If we have already inserted a cast into this block, use it.
1106 CastInst *&InsertedCast = InsertedCasts[UserBB];
1107
1108 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001109 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001110 assert(InsertPt != UserBB->end());
1111 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1112 CI->getType(), "", &*InsertPt);
Vedant Kumar9374c042018-05-23 22:03:48 +00001113 InsertedCast->setDebugLoc(CI->getDebugLoc());
Chris Lattnerf2836d12007-03-31 04:06:36 +00001114 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001115
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001116 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001117 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001118 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001119 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001120 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001121
Chris Lattnerf2836d12007-03-31 04:06:36 +00001122 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001123 if (CI->use_empty()) {
Adrian Prantl261ac8b2017-11-03 21:55:03 +00001124 salvageDebugInfo(*CI);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001125 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001126 MadeChange = true;
1127 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001128
Chris Lattnerf2836d12007-03-31 04:06:36 +00001129 return MadeChange;
1130}
1131
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001132/// If the specified cast instruction is a noop copy (e.g. it's casting from
1133/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1134/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001135///
1136/// Return true if any changes are made.
Mehdi Amini44ede332015-07-09 02:09:04 +00001137static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1138 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001139 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1140 // than sinking only nop casts, but is helpful on some platforms.
1141 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1142 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1143 ASC->getDestAddressSpace()))
1144 return false;
1145 }
1146
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001147 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001148 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1149 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001150
1151 // This is an fp<->int conversion?
1152 if (SrcVT.isInteger() != DstVT.isInteger())
1153 return false;
1154
1155 // If this is an extension, it will be a zero or sign extension, which
1156 // isn't a noop.
1157 if (SrcVT.bitsLT(DstVT)) return false;
1158
1159 // If these values will be promoted, find out what they will be promoted
1160 // to. This helps us consider truncates on PPC as noop copies when they
1161 // are.
1162 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1163 TargetLowering::TypePromoteInteger)
1164 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1165 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1166 TargetLowering::TypePromoteInteger)
1167 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1168
1169 // If, after promotion, these are the same types, this is a noop copy.
1170 if (SrcVT != DstVT)
1171 return false;
1172
1173 return SinkCast(CI);
1174}
1175
Teresa Johnson4dc85192019-03-24 15:18:50 +00001176bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
1177 CmpInst *Cmp,
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001178 Intrinsic::ID IID) {
Sanjay Patelffe1cf52019-02-22 20:20:24 +00001179 // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001180 Value *Arg0 = BO->getOperand(0);
1181 Value *Arg1 = BO->getOperand(1);
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001182 if (BO->getOpcode() == Instruction::Add &&
1183 IID == Intrinsic::usub_with_overflow) {
1184 assert(isa<Constant>(Arg1) && "Unexpected input for usubo");
1185 Arg1 = ConstantExpr::getNeg(cast<Constant>(Arg1));
1186 }
1187
Sanjay Patelffe1cf52019-02-22 20:20:24 +00001188 Instruction *InsertPt;
1189 if (BO->hasOneUse() && BO->user_back() == Cmp) {
1190 // If the math is only used by the compare, insert at the compare to keep
1191 // the condition in the same block as its users. (CGP aggressively sinks
1192 // compares to help out SDAG.)
1193 InsertPt = Cmp;
1194 } else {
1195 // The math and compare may be independent instructions. Check dominance to
1196 // determine the insertion point for the intrinsic.
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001197 bool MathDominates = getDT(*BO->getFunction()).dominates(BO, Cmp);
1198 if (!MathDominates && !getDT(*BO->getFunction()).dominates(Cmp, BO))
Sanjay Patelffe1cf52019-02-22 20:20:24 +00001199 return false;
Sam Parker52760bf2019-03-11 13:19:46 +00001200
Sanjay Patela2250e92019-03-20 16:47:53 +00001201 BasicBlock *MathBB = BO->getParent(), *CmpBB = Cmp->getParent();
1202 if (MathBB != CmpBB) {
Sanjay Pateld47eac52019-03-21 13:57:07 +00001203 // Avoid hoisting an extra op into a dominating block and creating a
1204 // potentially longer critical path.
1205 if (!MathDominates)
1206 return false;
1207 // Check that the insertion doesn't create a value that is live across
1208 // more than two blocks, so to minimise the increase in register pressure.
Sanjay Patela2250e92019-03-20 16:47:53 +00001209 BasicBlock *Dominator = MathDominates ? MathBB : CmpBB;
1210 BasicBlock *Dominated = MathDominates ? CmpBB : MathBB;
Sam Parker52760bf2019-03-11 13:19:46 +00001211 auto Successors = successors(Dominator);
1212 if (llvm::find(Successors, Dominated) == Successors.end())
1213 return false;
1214 }
1215
Sanjay Patelffe1cf52019-02-22 20:20:24 +00001216 InsertPt = MathDominates ? cast<Instruction>(BO) : cast<Instruction>(Cmp);
1217 }
1218
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001219 IRBuilder<> Builder(InsertPt);
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001220 Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1);
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001221 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
1222 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
1223 BO->replaceAllUsesWith(Math);
1224 Cmp->replaceAllUsesWith(OV);
1225 BO->eraseFromParent();
1226 Cmp->eraseFromParent();
Sanjay Patelffe1cf52019-02-22 20:20:24 +00001227 return true;
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001228}
1229
Sanjay Patelcb04ba02019-02-24 15:31:27 +00001230/// Match special-case patterns that check for unsigned add overflow.
1231static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp,
1232 BinaryOperator *&Add) {
1233 // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
1234 // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
1235 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
Sanjay Patel3b2d0bc2019-03-04 22:47:13 +00001236
1237 // We are not expecting non-canonical/degenerate code. Just bail out.
1238 if (isa<Constant>(A))
1239 return false;
1240
Sanjay Patelcb04ba02019-02-24 15:31:27 +00001241 ICmpInst::Predicate Pred = Cmp->getPredicate();
1242 if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
1243 B = ConstantInt::get(B->getType(), 1);
1244 else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
1245 B = ConstantInt::get(B->getType(), -1);
1246 else
1247 return false;
1248
1249 // Check the users of the variable operand of the compare looking for an add
1250 // with the adjusted constant.
1251 for (User *U : A->users()) {
1252 if (match(U, m_Add(m_Specific(A), m_Specific(B)))) {
1253 Add = cast<BinaryOperator>(U);
1254 return true;
1255 }
1256 }
1257 return false;
1258}
1259
Sanjay Patel00fcc742019-02-03 13:48:03 +00001260/// Try to combine the compare into a call to the llvm.uadd.with.overflow
1261/// intrinsic. Return true if any changes were made.
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001262bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
Teresa Johnson4dc85192019-03-24 15:18:50 +00001263 bool &ModifiedDT) {
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001264 Value *A, *B;
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001265 BinaryOperator *Add;
1266 if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add))))
Sanjay Patelcb04ba02019-02-24 15:31:27 +00001267 if (!matchUAddWithOverflowConstantEdgeCases(Cmp, Add))
1268 return false;
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001269
Teresa Johnson4dc85192019-03-24 15:18:50 +00001270 if (!TLI->shouldFormOverflowOp(ISD::UADDO,
1271 TLI->getValueType(*DL, Add->getType())))
Sanjay Patel84ceae62019-02-03 17:53:09 +00001272 return false;
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001273
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001274 // We don't want to move around uses of condition values this late, so we
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001275 // check if it is legal to create the call to the intrinsic in the basic
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001276 // block containing the icmp.
1277 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001278 return false;
1279
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001280 if (!replaceMathCmpWithIntrinsic(Add, Cmp, Intrinsic::uadd_with_overflow))
Sanjay Patelffe1cf52019-02-22 20:20:24 +00001281 return false;
1282
1283 // Reset callers - do not crash by iterating over a dead instruction.
1284 ModifiedDT = true;
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001285 return true;
1286}
1287
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001288bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
Teresa Johnson4dc85192019-03-24 15:18:50 +00001289 bool &ModifiedDT) {
Sanjay Patel2c9275a2019-03-14 23:14:31 +00001290 // We are not expecting non-canonical/degenerate code. Just bail out.
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001291 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
Sanjay Patel2c9275a2019-03-14 23:14:31 +00001292 if (isa<Constant>(A) && isa<Constant>(B))
1293 return false;
1294
1295 // Convert (A u> B) to (A u< B) to simplify pattern matching.
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001296 ICmpInst::Predicate Pred = Cmp->getPredicate();
1297 if (Pred == ICmpInst::ICMP_UGT) {
1298 std::swap(A, B);
1299 Pred = ICmpInst::ICMP_ULT;
1300 }
1301 // Convert special-case: (A == 0) is the same as (A u< 1).
1302 if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) {
1303 B = ConstantInt::get(B->getType(), 1);
1304 Pred = ICmpInst::ICMP_ULT;
1305 }
Sanjay Patel198cc302019-02-20 21:23:04 +00001306 // Convert special-case: (A != 0) is the same as (0 u< A).
1307 if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) {
1308 std::swap(A, B);
1309 Pred = ICmpInst::ICMP_ULT;
1310 }
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001311 if (Pred != ICmpInst::ICMP_ULT)
1312 return false;
1313
1314 // Walk the users of a variable operand of a compare looking for a subtract or
1315 // add with that same operand. Also match the 2nd operand of the compare to
1316 // the add/sub, but that may be a negated constant operand of an add.
1317 Value *CmpVariableOperand = isa<Constant>(A) ? B : A;
1318 BinaryOperator *Sub = nullptr;
1319 for (User *U : CmpVariableOperand->users()) {
1320 // A - B, A u< B --> usubo(A, B)
1321 if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) {
1322 Sub = cast<BinaryOperator>(U);
1323 break;
1324 }
1325
1326 // A + (-C), A u< C (canonicalized form of (sub A, C))
1327 const APInt *CmpC, *AddC;
1328 if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
1329 match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
1330 Sub = cast<BinaryOperator>(U);
1331 break;
1332 }
1333 }
1334 if (!Sub)
1335 return false;
1336
Teresa Johnson4dc85192019-03-24 15:18:50 +00001337 if (!TLI->shouldFormOverflowOp(ISD::USUBO,
1338 TLI->getValueType(*DL, Sub->getType())))
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001339 return false;
1340
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001341 if (!replaceMathCmpWithIntrinsic(Sub, Cmp, Intrinsic::usub_with_overflow))
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001342 return false;
Sanjay Patelffe1cf52019-02-22 20:20:24 +00001343
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001344 // Reset callers - do not crash by iterating over a dead instruction.
1345 ModifiedDT = true;
1346 return true;
1347}
1348
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001349/// Sink the given CmpInst into user blocks to reduce the number of virtual
1350/// registers that must be created and coalesced. This is a clear win except on
1351/// targets with multiple condition code registers (PowerPC), where it might
1352/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001353///
1354/// Return true if any changes are made.
Sanjay Patel00fcc742019-02-03 13:48:03 +00001355static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI) {
1356 if (TLI.hasMultipleConditionRegisters())
1357 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001358
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001359 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Sanjay Patel00fcc742019-02-03 13:48:03 +00001360 if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001361 return false;
1362
1363 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001364 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001365
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001366 bool MadeChange = false;
Sanjay Patel00fcc742019-02-03 13:48:03 +00001367 for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001368 UI != E; ) {
1369 Use &TheUse = UI.getUse();
1370 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001371
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001372 // Preincrement use iterator so we don't invalidate it.
1373 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001374
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001375 // Don't bother for PHI nodes.
1376 if (isa<PHINode>(User))
1377 continue;
1378
1379 // Figure out which BB this cmp is used in.
1380 BasicBlock *UserBB = User->getParent();
Sanjay Patel00fcc742019-02-03 13:48:03 +00001381 BasicBlock *DefBB = Cmp->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001382
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001383 // If this user is in the same block as the cmp, don't change the cmp.
1384 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001385
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001386 // If we have already inserted a cmp into this block, use it.
1387 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1388
1389 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001390 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001391 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001392 InsertedCmp =
Sanjay Patel00fcc742019-02-03 13:48:03 +00001393 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(),
1394 Cmp->getOperand(0), Cmp->getOperand(1), "",
1395 &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001396 // Propagate the debug info.
Sanjay Patel00fcc742019-02-03 13:48:03 +00001397 InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001398 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001399
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001400 // Replace a use of the cmp with a use of the new cmp.
1401 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001402 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001403 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001404 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001405
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001406 // If we removed all uses, nuke the cmp.
Sanjay Patel00fcc742019-02-03 13:48:03 +00001407 if (Cmp->use_empty()) {
1408 Cmp->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001409 MadeChange = true;
1410 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001411
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001412 return MadeChange;
1413}
1414
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001415bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, bool &ModifiedDT) {
Teresa Johnson4dc85192019-03-24 15:18:50 +00001416 if (sinkCmpExpression(Cmp, *TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001417 return true;
1418
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001419 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001420 return true;
1421
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00001422 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00001423 return true;
1424
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001425 return false;
1426}
1427
Geoff Berry5d534b62017-02-21 18:53:14 +00001428/// Duplicate and sink the given 'and' instruction into user blocks where it is
1429/// used in a compare to allow isel to generate better code for targets where
1430/// this operation can be combined.
1431///
1432/// Return true if any changes are made.
1433static bool sinkAndCmp0Expression(Instruction *AndI,
1434 const TargetLowering &TLI,
1435 SetOfInstrs &InsertedInsts) {
1436 // Double-check that we're not trying to optimize an instruction that was
1437 // already optimized by some other part of this pass.
1438 assert(!InsertedInsts.count(AndI) &&
1439 "Attempting to optimize already optimized and instruction");
1440 (void) InsertedInsts;
1441
1442 // Nothing to do for single use in same basic block.
1443 if (AndI->hasOneUse() &&
1444 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1445 return false;
1446
1447 // Try to avoid cases where sinking/duplicating is likely to increase register
1448 // pressure.
1449 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1450 !isa<ConstantInt>(AndI->getOperand(1)) &&
1451 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1452 return false;
1453
1454 for (auto *U : AndI->users()) {
1455 Instruction *User = cast<Instruction>(U);
1456
Sanjay Patel7d8260f2019-03-10 18:42:30 +00001457 // Only sink 'and' feeding icmp with 0.
Geoff Berry5d534b62017-02-21 18:53:14 +00001458 if (!isa<ICmpInst>(User))
1459 return false;
1460
1461 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1462 if (!CmpC || !CmpC->isZero())
1463 return false;
1464 }
1465
1466 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1467 return false;
1468
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001469 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1470 LLVM_DEBUG(AndI->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001471
1472 // Push the 'and' into the same block as the icmp 0. There should only be
1473 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1474 // others, so we don't need to keep track of which BBs we insert into.
1475 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1476 UI != E; ) {
1477 Use &TheUse = UI.getUse();
1478 Instruction *User = cast<Instruction>(*UI);
1479
1480 // Preincrement use iterator so we don't invalidate it.
1481 ++UI;
1482
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001483 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
Geoff Berry5d534b62017-02-21 18:53:14 +00001484
1485 // Keep the 'and' in the same place if the use is already in the same block.
1486 Instruction *InsertPt =
1487 User->getParent() == AndI->getParent() ? AndI : User;
1488 Instruction *InsertedAnd =
1489 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1490 AndI->getOperand(1), "", InsertPt);
1491 // Propagate the debug info.
1492 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1493
1494 // Replace a use of the 'and' with a use of the new 'and'.
1495 TheUse = InsertedAnd;
1496 ++NumAndUses;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001497 LLVM_DEBUG(User->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001498 }
1499
1500 // We removed all uses, nuke the and.
1501 AndI->eraseFromParent();
1502 return true;
1503}
1504
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001505/// Check if the candidates could be combined with a shift instruction, which
1506/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001507/// 1. Truncate instruction
1508/// 2. And instruction and the imm is a mask of the low bits:
1509/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001510static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001511 if (!isa<TruncInst>(User)) {
1512 if (User->getOpcode() != Instruction::And ||
1513 !isa<ConstantInt>(User->getOperand(1)))
1514 return false;
1515
Quentin Colombetd4f44692014-04-22 01:20:34 +00001516 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001517
Quentin Colombetd4f44692014-04-22 01:20:34 +00001518 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001519 return false;
1520 }
1521 return true;
1522}
1523
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001524/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001525static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001526SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1527 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001528 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001529 BasicBlock *UserBB = User->getParent();
1530 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1531 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1532 bool MadeChange = false;
1533
1534 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1535 TruncE = TruncI->user_end();
1536 TruncUI != TruncE;) {
1537
1538 Use &TruncTheUse = TruncUI.getUse();
1539 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1540 // Preincrement use iterator so we don't invalidate it.
1541
1542 ++TruncUI;
1543
1544 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1545 if (!ISDOpcode)
1546 continue;
1547
Tim Northovere2239ff2014-07-29 10:20:22 +00001548 // If the use is actually a legal node, there will not be an
1549 // implicit truncate.
1550 // FIXME: always querying the result type is just an
1551 // approximation; some nodes' legality is determined by the
1552 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001553 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001554 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001555 continue;
1556
1557 // Don't bother for PHI nodes.
1558 if (isa<PHINode>(TruncUser))
1559 continue;
1560
1561 BasicBlock *TruncUserBB = TruncUser->getParent();
1562
1563 if (UserBB == TruncUserBB)
1564 continue;
1565
1566 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1567 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1568
1569 if (!InsertedShift && !InsertedTrunc) {
1570 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001571 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001572 // Sink the shift
1573 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001574 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1575 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001576 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001577 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1578 "", &*InsertPt);
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001579 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
Yi Jiangd069f632014-04-21 19:34:27 +00001580
1581 // Sink the trunc
1582 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1583 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001584 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001585
1586 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001587 TruncI->getType(), "", &*TruncInsertPt);
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001588 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
Yi Jiangd069f632014-04-21 19:34:27 +00001589
1590 MadeChange = true;
1591
1592 TruncTheUse = InsertedTrunc;
1593 }
1594 }
1595 return MadeChange;
1596}
1597
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001598/// Sink the shift *right* instruction into user blocks if the uses could
1599/// potentially be combined with this shift instruction and generate BitExtract
1600/// instruction. It will only be applied if the architecture supports BitExtract
1601/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001602/// BB1:
1603/// %x.extract.shift = lshr i64 %arg1, 32
1604/// BB2:
1605/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1606/// ==>
1607///
1608/// BB2:
1609/// %x.extract.shift.1 = lshr i64 %arg1, 32
1610/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1611///
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001612/// CodeGen will recognize the pattern in BB2 and generate BitExtract
Yi Jiangd069f632014-04-21 19:34:27 +00001613/// instruction.
1614/// Return true if any changes are made.
1615static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001616 const TargetLowering &TLI,
1617 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001618 BasicBlock *DefBB = ShiftI->getParent();
1619
1620 /// Only insert instructions in each block once.
1621 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1622
Mehdi Amini44ede332015-07-09 02:09:04 +00001623 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001624
1625 bool MadeChange = false;
1626 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1627 UI != E;) {
1628 Use &TheUse = UI.getUse();
1629 Instruction *User = cast<Instruction>(*UI);
1630 // Preincrement use iterator so we don't invalidate it.
1631 ++UI;
1632
1633 // Don't bother for PHI nodes.
1634 if (isa<PHINode>(User))
1635 continue;
1636
1637 if (!isExtractBitsCandidateUse(User))
1638 continue;
1639
1640 BasicBlock *UserBB = User->getParent();
1641
1642 if (UserBB == DefBB) {
1643 // If the shift and truncate instruction are in the same BB. The use of
1644 // the truncate(TruncUse) may still introduce another truncate if not
1645 // legal. In this case, we would like to sink both shift and truncate
1646 // instruction to the BB of TruncUse.
1647 // for example:
1648 // BB1:
1649 // i64 shift.result = lshr i64 opnd, imm
1650 // trunc.result = trunc shift.result to i16
1651 //
1652 // BB2:
1653 // ----> We will have an implicit truncate here if the architecture does
1654 // not have i16 compare.
1655 // cmp i16 trunc.result, opnd2
1656 //
1657 if (isa<TruncInst>(User) && shiftIsLegal
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001658 // If the type of the truncate is legal, no truncate will be
Yi Jiangd069f632014-04-21 19:34:27 +00001659 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001660 &&
1661 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001662 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001663 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001664
1665 continue;
1666 }
1667 // If we have already inserted a shift into this block, use it.
1668 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1669
1670 if (!InsertedShift) {
1671 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001672 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001673
1674 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001675 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1676 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001677 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001678 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1679 "", &*InsertPt);
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001680 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
Yi Jiangd069f632014-04-21 19:34:27 +00001681
1682 MadeChange = true;
1683 }
1684
1685 // Replace a use of the shift with a use of the new shift.
1686 TheUse = InsertedShift;
1687 }
1688
1689 // If we removed all uses, nuke the shift.
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001690 if (ShiftI->use_empty()) {
1691 salvageDebugInfo(*ShiftI);
Yi Jiangd069f632014-04-21 19:34:27 +00001692 ShiftI->eraseFromParent();
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001693 }
Yi Jiangd069f632014-04-21 19:34:27 +00001694
1695 return MadeChange;
1696}
1697
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001698/// If counting leading or trailing zeros is an expensive operation and a zero
1699/// input is defined, add a check for zero to avoid calling the intrinsic.
1700///
1701/// We want to transform:
1702/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1703///
1704/// into:
1705/// entry:
1706/// %cmpz = icmp eq i64 %A, 0
1707/// br i1 %cmpz, label %cond.end, label %cond.false
1708/// cond.false:
1709/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1710/// br label %cond.end
1711/// cond.end:
1712/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1713///
1714/// If the transform is performed, return true and set ModifiedDT to true.
1715static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1716 const TargetLowering *TLI,
1717 const DataLayout *DL,
1718 bool &ModifiedDT) {
1719 if (!TLI || !DL)
1720 return false;
1721
1722 // If a zero input is undefined, it doesn't make sense to despeculate that.
1723 if (match(CountZeros->getOperand(1), m_One()))
1724 return false;
1725
1726 // If it's cheap to speculate, there's nothing to do.
1727 auto IntrinsicID = CountZeros->getIntrinsicID();
1728 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1729 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1730 return false;
1731
1732 // Only handle legal scalar cases. Anything else requires too much work.
1733 Type *Ty = CountZeros->getType();
1734 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001735 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001736 return false;
1737
1738 // The intrinsic will be sunk behind a compare against zero and branch.
1739 BasicBlock *StartBlock = CountZeros->getParent();
1740 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1741
1742 // Create another block after the count zero intrinsic. A PHI will be added
1743 // in this block to select the result of the intrinsic or the bit-width
1744 // constant if the input to the intrinsic is zero.
1745 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1746 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1747
1748 // Set up a builder to create a compare, conditional branch, and PHI.
1749 IRBuilder<> Builder(CountZeros->getContext());
1750 Builder.SetInsertPoint(StartBlock->getTerminator());
1751 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1752
1753 // Replace the unconditional branch that was created by the first split with
1754 // a compare against zero and a conditional branch.
1755 Value *Zero = Constant::getNullValue(Ty);
1756 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1757 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1758 StartBlock->getTerminator()->eraseFromParent();
1759
1760 // Create a PHI in the end block to select either the output of the intrinsic
1761 // or the bit width of the operand.
1762 Builder.SetInsertPoint(&EndBlock->front());
1763 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1764 CountZeros->replaceAllUsesWith(PN);
1765 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1766 PN->addIncoming(BitWidth, StartBlock);
1767 PN->addIncoming(CountZeros, CallBlock);
1768
1769 // We are explicitly handling the zero case, so we can set the intrinsic's
1770 // undefined zero argument to 'true'. This will also prevent reprocessing the
1771 // intrinsic; we only despeculate when a zero input is defined.
1772 CountZeros->setArgOperand(1, Builder.getTrue());
1773 ModifiedDT = true;
1774 return true;
1775}
1776
Sanjay Patel3b8974b2017-06-08 20:00:09 +00001777bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001778 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001779
Chris Lattner7a277142011-01-15 07:14:54 +00001780 // Lower inline assembly if we can.
1781 // If we found an inline asm expession, and if the target knows how to
1782 // lower it to normal LLVM code, do so now.
1783 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1784 if (TLI->ExpandInlineAsm(CI)) {
1785 // Avoid invalidating the iterator.
1786 CurInstIterator = BB->begin();
1787 // Avoid processing instructions out of order, which could cause
1788 // reuse before a value is defined.
1789 SunkAddrs.clear();
1790 return true;
1791 }
1792 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001793 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001794 return true;
1795 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001796
John Brawn0dbcd652015-03-18 12:01:59 +00001797 // Align the pointer arguments to this call if the target thinks it's a good
1798 // idea
1799 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001800 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001801 for (auto &Arg : CI->arg_operands()) {
1802 // We want to align both objects whose address is used directly and
1803 // objects whose address is used in casts and GEPs, though it only makes
1804 // sense for GEPs if the offset is a multiple of the desired alignment and
1805 // if size - offset meets the size threshold.
1806 if (!Arg->getType()->isPointerTy())
1807 continue;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001808 APInt Offset(DL->getIndexSizeInBits(
Mehdi Amini4fe37982015-07-07 18:45:17 +00001809 cast<PointerType>(Arg->getType())->getAddressSpace()),
1810 0);
1811 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001812 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001813 if ((Offset2 & (PrefAlign-1)) != 0)
1814 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001815 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001816 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1817 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001818 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001819 // Global variables can only be aligned if they are defined in this
1820 // object (i.e. they are uniquely initialized in this object), and
1821 // over-aligning global variables that have an explicit section is
1822 // forbidden.
1823 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001824 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001825 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001826 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001827 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001828 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001829 }
1830 // If this is a memcpy (or similar) then we may be able to improve the
1831 // alignment
1832 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Daniel Neilsonbe58a222018-01-31 17:24:53 +00001833 unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
1834 if (DestAlign > MI->getDestAlignment())
1835 MI->setDestAlignment(DestAlign);
1836 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1837 unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
1838 if (SrcAlign > MTI->getSourceAlignment())
1839 MTI->setSourceAlignment(SrcAlign);
1840 }
John Brawn0dbcd652015-03-18 12:01:59 +00001841 }
1842 }
1843
Philip Reamesac115ed2016-03-09 23:13:12 +00001844 // If we have a cold call site, try to sink addressing computation into the
1845 // cold block. This interacts with our handling for loads and stores to
1846 // ensure that we can fold all uses of a potential addressing computation
1847 // into their uses. TODO: generalize this to work over profiling data
1848 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1849 for (auto &Arg : CI->arg_operands()) {
1850 if (!Arg->getType()->isPointerTy())
1851 continue;
1852 unsigned AS = Arg->getType()->getPointerAddressSpace();
1853 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1854 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001855
Eric Christopher4b7948e2010-03-11 02:41:03 +00001856 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001857 if (II) {
1858 switch (II->getIntrinsicID()) {
1859 default: break;
Philip Reamesede49dd2019-01-31 18:45:46 +00001860 case Intrinsic::experimental_widenable_condition: {
1861 // Give up on future widening oppurtunties so that we can fold away dead
1862 // paths and merge blocks before going into block-local instruction
1863 // selection.
1864 if (II->use_empty()) {
1865 II->eraseFromParent();
1866 return true;
1867 }
1868 Constant *RetVal = ConstantInt::getTrue(II->getContext());
1869 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1870 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1871 });
1872 return true;
1873 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001874 case Intrinsic::objectsize: {
1875 // Lower all uses of llvm.objectsize.*
Erik Pilkington600e9de2019-01-30 20:34:35 +00001876 Value *RetVal =
George Burgess IV3f089142016-12-20 23:46:36 +00001877 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Nadav Rotem465834c2012-07-24 10:51:42 +00001878
James Y Knight72f76bf2018-11-07 15:24:12 +00001879 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1880 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1881 });
1882 return true;
1883 }
1884 case Intrinsic::is_constant: {
1885 // If is_constant hasn't folded away yet, lower it to false now.
1886 Constant *RetVal = ConstantInt::get(II->getType(), 0);
1887 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1888 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1889 });
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001890 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001891 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001892 case Intrinsic::aarch64_stlxr:
1893 case Intrinsic::aarch64_stxr: {
1894 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1895 if (!ExtVal || !ExtVal->hasOneUse() ||
1896 ExtVal->getParent() == CI->getParent())
1897 return false;
1898 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1899 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001900 // Mark this instruction as "inserted by CGP", so that other
1901 // optimizations don't touch it.
1902 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001903 return true;
1904 }
Florian Hahn3b251962019-02-05 10:27:40 +00001905
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001906 case Intrinsic::launder_invariant_group:
Krzysztof Pszeniczny2bfe7592018-10-19 19:02:16 +00001907 case Intrinsic::strip_invariant_group: {
1908 Value *ArgVal = II->getArgOperand(0);
1909 auto it = LargeOffsetGEPMap.find(II);
1910 if (it != LargeOffsetGEPMap.end()) {
1911 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
1912 // Make sure not to have to deal with iterator invalidation
1913 // after possibly adding ArgVal to LargeOffsetGEPMap.
1914 auto GEPs = std::move(it->second);
1915 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
1916 LargeOffsetGEPMap.erase(II);
1917 }
1918
1919 II->replaceAllUsesWith(ArgVal);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001920 II->eraseFromParent();
1921 return true;
Krzysztof Pszeniczny2bfe7592018-10-19 19:02:16 +00001922 }
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001923 case Intrinsic::cttz:
1924 case Intrinsic::ctlz:
1925 // If counting zeros is expensive, try to avoid it.
1926 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001927 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001928
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001929 if (TLI) {
1930 SmallVector<Value*, 2> PtrOps;
1931 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001932 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1933 while (!PtrOps.empty()) {
1934 Value *PtrVal = PtrOps.pop_back_val();
1935 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1936 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001937 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001938 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001939 }
Pete Cooper615fd892012-03-13 20:59:56 +00001940 }
1941
Eric Christopher4b7948e2010-03-11 02:41:03 +00001942 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001943 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001944
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001945 // Lower all default uses of _chk calls. This is very similar
1946 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001947 // to fortified library functions (e.g. __memcpy_chk) that have the default
1948 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001949 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001950 if (Value *V = Simplifier.optimizeCall(CI)) {
1951 CI->replaceAllUsesWith(V);
1952 CI->eraseFromParent();
1953 return true;
1954 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001955
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001956 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001957}
Chris Lattner1b93be52011-01-15 07:25:29 +00001958
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001959/// Look for opportunities to duplicate return instructions to the predecessor
1960/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001961/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001962/// bb0:
1963/// %tmp0 = tail call i32 @f0()
1964/// br label %return
1965/// bb1:
1966/// %tmp1 = tail call i32 @f1()
1967/// br label %return
1968/// bb2:
1969/// %tmp2 = tail call i32 @f2()
1970/// br label %return
1971/// return:
1972/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1973/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001974/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001975///
1976/// =>
1977///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001978/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001979/// bb0:
1980/// %tmp0 = tail call i32 @f0()
1981/// ret i32 %tmp0
1982/// bb1:
1983/// %tmp1 = tail call i32 @f1()
1984/// ret i32 %tmp1
1985/// bb2:
1986/// %tmp2 = tail call i32 @f2()
1987/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001988/// @endcode
Rong Xuce3be452019-03-08 22:46:18 +00001989bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001990 if (!TLI)
1991 return false;
1992
Michael Kuperstein71321562016-09-07 20:29:49 +00001993 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1994 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001995 return false;
1996
Craig Topperc0196b12014-04-14 00:51:57 +00001997 PHINode *PN = nullptr;
1998 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001999 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00002000 if (V) {
2001 BCI = dyn_cast<BitCastInst>(V);
2002 if (BCI)
2003 V = BCI->getOperand(0);
2004
2005 PN = dyn_cast<PHINode>(V);
2006 if (!PN)
2007 return false;
2008 }
Evan Cheng0663f232011-03-21 01:19:09 +00002009
Cameron Zwarich4649f172011-03-24 04:52:10 +00002010 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002011 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00002012
Cameron Zwarich4649f172011-03-24 04:52:10 +00002013 // Make sure there are no instructions between the PHI and return, or that the
2014 // return is the first instruction in the block.
2015 if (PN) {
2016 BasicBlock::iterator BI = BB->begin();
Jonas Paulsson5ed4d462019-01-29 09:03:35 +00002017 // Skip over debug and the bitcast.
2018 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI) || &*BI == BCI);
Michael Kuperstein71321562016-09-07 20:29:49 +00002019 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002020 return false;
2021 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002022 BasicBlock::iterator BI = BB->begin();
2023 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002024 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002025 return false;
2026 }
Evan Cheng0663f232011-03-21 01:19:09 +00002027
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002028 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2029 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002030 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002031 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00002032 if (PN) {
2033 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2034 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2035 // Make sure the phi value is indeed produced by the tail call.
2036 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002037 TLI->mayBeEmittedAsTailCall(CI) &&
2038 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002039 TailCalls.push_back(CI);
2040 }
2041 } else {
2042 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002043 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002044 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002045 continue;
2046
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002047 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002048 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2049 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002050 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2051 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002052 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002053
Cameron Zwarich4649f172011-03-24 04:52:10 +00002054 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002055 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2056 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002057 TailCalls.push_back(CI);
2058 }
Evan Cheng0663f232011-03-21 01:19:09 +00002059 }
2060
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002061 bool Changed = false;
2062 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2063 CallInst *CI = TailCalls[i];
2064 CallSite CS(CI);
2065
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002066 // Make sure the call instruction is followed by an unconditional branch to
2067 // the return block.
2068 BasicBlock *CallBB = CI->getParent();
2069 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2070 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2071 continue;
2072
2073 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002074 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002075 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002076 ++NumRetsDup;
2077 }
2078
2079 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002080 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002081 BB->eraseFromParent();
2082
2083 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002084}
2085
Chris Lattner728f9022008-11-25 07:09:13 +00002086//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002087// Memory Optimization
2088//===----------------------------------------------------------------------===//
2089
Chandler Carruthc8925912013-01-05 02:09:22 +00002090namespace {
2091
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002092/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002093/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002094struct ExtAddrMode : public TargetLowering::AddrMode {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002095 Value *BaseReg = nullptr;
2096 Value *ScaledReg = nullptr;
John Brawn736bf002017-10-03 13:08:22 +00002097 Value *OriginalValue = nullptr;
Tim Northover8935aca2019-03-12 15:22:23 +00002098 bool InBounds = true;
John Brawn736bf002017-10-03 13:08:22 +00002099
2100 enum FieldName {
2101 NoField = 0x00,
2102 BaseRegField = 0x01,
2103 BaseGVField = 0x02,
2104 BaseOffsField = 0x04,
2105 ScaledRegField = 0x08,
2106 ScaleField = 0x10,
2107 MultipleFields = 0xff
2108 };
Eugene Zelenko900b6332017-08-29 22:32:07 +00002109
Tim Northover8935aca2019-03-12 15:22:23 +00002110
Eugene Zelenko900b6332017-08-29 22:32:07 +00002111 ExtAddrMode() = default;
2112
Chandler Carruthc8925912013-01-05 02:09:22 +00002113 void print(raw_ostream &OS) const;
2114 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002115
John Brawn736bf002017-10-03 13:08:22 +00002116 FieldName compare(const ExtAddrMode &other) {
2117 // First check that the types are the same on each field, as differing types
2118 // is something we can't cope with later on.
2119 if (BaseReg && other.BaseReg &&
2120 BaseReg->getType() != other.BaseReg->getType())
2121 return MultipleFields;
2122 if (BaseGV && other.BaseGV &&
2123 BaseGV->getType() != other.BaseGV->getType())
2124 return MultipleFields;
2125 if (ScaledReg && other.ScaledReg &&
2126 ScaledReg->getType() != other.ScaledReg->getType())
2127 return MultipleFields;
2128
Tim Northover8935aca2019-03-12 15:22:23 +00002129 // Conservatively reject 'inbounds' mismatches.
2130 if (InBounds != other.InBounds)
2131 return MultipleFields;
2132
John Brawn736bf002017-10-03 13:08:22 +00002133 // Check each field to see if it differs.
2134 unsigned Result = NoField;
2135 if (BaseReg != other.BaseReg)
2136 Result |= BaseRegField;
2137 if (BaseGV != other.BaseGV)
2138 Result |= BaseGVField;
2139 if (BaseOffs != other.BaseOffs)
2140 Result |= BaseOffsField;
2141 if (ScaledReg != other.ScaledReg)
2142 Result |= ScaledRegField;
2143 // Don't count 0 as being a different scale, because that actually means
2144 // unscaled (which will already be counted by having no ScaledReg).
2145 if (Scale && other.Scale && Scale != other.Scale)
2146 Result |= ScaleField;
2147
2148 if (countPopulation(Result) > 1)
2149 return MultipleFields;
2150 else
2151 return static_cast<FieldName>(Result);
2152 }
2153
John Brawn4b476482017-11-27 11:29:15 +00002154 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
2155 // with no offset.
John Brawn736bf002017-10-03 13:08:22 +00002156 bool isTrivial() {
John Brawn4b476482017-11-27 11:29:15 +00002157 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
2158 // trivial if at most one of these terms is nonzero, except that BaseGV and
2159 // BaseReg both being zero actually means a null pointer value, which we
2160 // consider to be 'non-zero' here.
2161 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
Chandler Carruthc8925912013-01-05 02:09:22 +00002162 }
John Brawn70cdb5b2017-11-24 14:10:45 +00002163
2164 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
2165 switch (Field) {
2166 default:
2167 return nullptr;
2168 case BaseRegField:
2169 return BaseReg;
2170 case BaseGVField:
2171 return BaseGV;
2172 case ScaledRegField:
2173 return ScaledReg;
2174 case BaseOffsField:
2175 return ConstantInt::get(IntPtrTy, BaseOffs);
2176 }
2177 }
2178
2179 void SetCombinedField(FieldName Field, Value *V,
2180 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
2181 switch (Field) {
2182 default:
2183 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
2184 break;
2185 case ExtAddrMode::BaseRegField:
2186 BaseReg = V;
2187 break;
2188 case ExtAddrMode::BaseGVField:
2189 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
2190 // in the BaseReg field.
2191 assert(BaseReg == nullptr);
2192 BaseReg = V;
2193 BaseGV = nullptr;
2194 break;
2195 case ExtAddrMode::ScaledRegField:
2196 ScaledReg = V;
2197 // If we have a mix of scaled and unscaled addrmodes then we want scale
2198 // to be the scale and not zero.
2199 if (!Scale)
2200 for (const ExtAddrMode &AM : AddrModes)
2201 if (AM.Scale) {
2202 Scale = AM.Scale;
2203 break;
2204 }
2205 break;
2206 case ExtAddrMode::BaseOffsField:
2207 // The offset is no longer a constant, so it goes in ScaledReg with a
2208 // scale of 1.
2209 assert(ScaledReg == nullptr);
2210 ScaledReg = V;
2211 Scale = 1;
2212 BaseOffs = 0;
2213 break;
2214 }
2215 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002216};
2217
Eugene Zelenko900b6332017-08-29 22:32:07 +00002218} // end anonymous namespace
2219
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002220#ifndef NDEBUG
2221static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2222 AM.print(OS);
2223 return OS;
2224}
2225#endif
2226
Aaron Ballman615eb472017-10-15 14:32:27 +00002227#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthc8925912013-01-05 02:09:22 +00002228void ExtAddrMode::print(raw_ostream &OS) const {
2229 bool NeedPlus = false;
2230 OS << "[";
Tim Northover8935aca2019-03-12 15:22:23 +00002231 if (InBounds)
2232 OS << "inbounds ";
Chandler Carruthc8925912013-01-05 02:09:22 +00002233 if (BaseGV) {
2234 OS << (NeedPlus ? " + " : "")
2235 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002236 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002237 NeedPlus = true;
2238 }
2239
Richard Trieuc0f91212014-05-30 03:15:17 +00002240 if (BaseOffs) {
2241 OS << (NeedPlus ? " + " : "")
2242 << BaseOffs;
2243 NeedPlus = true;
2244 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002245
2246 if (BaseReg) {
2247 OS << (NeedPlus ? " + " : "")
2248 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002249 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002250 NeedPlus = true;
2251 }
2252 if (Scale) {
2253 OS << (NeedPlus ? " + " : "")
2254 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002255 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002256 }
2257
2258 OS << ']';
2259}
2260
Yaron Kereneb2a2542016-01-29 20:50:44 +00002261LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002262 print(dbgs());
2263 dbgs() << '\n';
2264}
2265#endif
2266
Eugene Zelenko900b6332017-08-29 22:32:07 +00002267namespace {
2268
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002269/// This class provides transaction based operation on the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002270/// Every change made through this class is recorded in the internal state and
2271/// can be undone (rollback) until commit is called.
2272class TypePromotionTransaction {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002273 /// This represents the common interface of the individual transaction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002274 /// Each class implements the logic for doing one specific modification on
2275 /// the IR via the TypePromotionTransaction.
2276 class TypePromotionAction {
2277 protected:
2278 /// The Instruction modified.
2279 Instruction *Inst;
2280
2281 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002282 /// Constructor of the action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002283 /// The constructor performs the related action on the IR.
2284 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2285
Eugene Zelenko900b6332017-08-29 22:32:07 +00002286 virtual ~TypePromotionAction() = default;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002287
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002288 /// Undo the modification done by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002289 /// When this method is called, the IR must be in the same state as it was
2290 /// before this action was applied.
2291 /// \pre Undoing the action works if and only if the IR is in the exact same
2292 /// state as it was directly after this action was applied.
2293 virtual void undo() = 0;
2294
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002295 /// Advocate every change made by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002296 /// When the results on the IR of the action are to be kept, it is important
2297 /// to call this function, otherwise hidden information may be kept forever.
2298 virtual void commit() {
2299 // Nothing to be done, this action is not doing anything.
2300 }
2301 };
2302
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002303 /// Utility to remember the position of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002304 class InsertionHandler {
2305 /// Position of an instruction.
2306 /// Either an instruction:
2307 /// - Is the first in a basic block: BB is used.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002308 /// - Has a previous instruction: PrevInst is used.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002309 union {
2310 Instruction *PrevInst;
2311 BasicBlock *BB;
2312 } Point;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002313
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002314 /// Remember whether or not the instruction had a previous instruction.
2315 bool HasPrevInstruction;
2316
2317 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002318 /// Record the position of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002319 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002320 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002321 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2322 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002323 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002324 else
2325 Point.BB = Inst->getParent();
2326 }
2327
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002328 /// Insert \p Inst at the recorded position.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002329 void insert(Instruction *Inst) {
2330 if (HasPrevInstruction) {
2331 if (Inst->getParent())
2332 Inst->removeFromParent();
2333 Inst->insertAfter(Point.PrevInst);
2334 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002335 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002336 if (Inst->getParent())
2337 Inst->moveBefore(Position);
2338 else
2339 Inst->insertBefore(Position);
2340 }
2341 }
2342 };
2343
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002344 /// Move an instruction before another.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002345 class InstructionMoveBefore : public TypePromotionAction {
2346 /// Original position of the instruction.
2347 InsertionHandler Position;
2348
2349 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002350 /// Move \p Inst before \p Before.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002351 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2352 : TypePromotionAction(Inst), Position(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002353 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
2354 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002355 Inst->moveBefore(Before);
2356 }
2357
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002358 /// Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002359 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002360 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002361 Position.insert(Inst);
2362 }
2363 };
2364
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002365 /// Set the operand of an instruction with a new value.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002366 class OperandSetter : public TypePromotionAction {
2367 /// Original operand of the instruction.
2368 Value *Origin;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002369
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002370 /// Index of the modified instruction.
2371 unsigned Idx;
2372
2373 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002374 /// Set \p Idx operand of \p Inst with \p NewVal.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002375 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2376 : TypePromotionAction(Inst), Idx(Idx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002377 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2378 << "for:" << *Inst << "\n"
2379 << "with:" << *NewVal << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002380 Origin = Inst->getOperand(Idx);
2381 Inst->setOperand(Idx, NewVal);
2382 }
2383
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002384 /// Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002385 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002386 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2387 << "for: " << *Inst << "\n"
2388 << "with: " << *Origin << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002389 Inst->setOperand(Idx, Origin);
2390 }
2391 };
2392
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002393 /// Hide the operands of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002394 /// Do as if this instruction was not using any of its operands.
2395 class OperandsHider : public TypePromotionAction {
2396 /// The list of original operands.
2397 SmallVector<Value *, 4> OriginalValues;
2398
2399 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002400 /// Remove \p Inst from the uses of the operands of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002401 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002402 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002403 unsigned NumOpnds = Inst->getNumOperands();
2404 OriginalValues.reserve(NumOpnds);
2405 for (unsigned It = 0; It < NumOpnds; ++It) {
2406 // Save the current operand.
2407 Value *Val = Inst->getOperand(It);
2408 OriginalValues.push_back(Val);
2409 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002410 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002411 // that we are not willing to pay.
2412 Inst->setOperand(It, UndefValue::get(Val->getType()));
2413 }
2414 }
2415
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002416 /// Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002417 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002418 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002419 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2420 Inst->setOperand(It, OriginalValues[It]);
2421 }
2422 };
2423
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002424 /// Build a truncate instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002425 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002426 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002427
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002428 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002429 /// Build a truncate instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002430 /// result.
2431 /// trunc Opnd to Ty.
2432 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2433 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002434 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002435 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002436 }
2437
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002438 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002439 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002440
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002441 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002442 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002443 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002444 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2445 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002446 }
2447 };
2448
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002449 /// Build a sign extension instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002450 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002451 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002452
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002453 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002454 /// Build a sign extension instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002455 /// result.
2456 /// sext Opnd to Ty.
2457 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002458 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002459 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002460 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002461 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002462 }
2463
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002464 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002465 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002466
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002467 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002468 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002469 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002470 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2471 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002472 }
2473 };
2474
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002475 /// Build a zero extension instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002476 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002477 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002478
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002479 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002480 /// Build a zero extension instruction of \p Opnd producing a \p Ty
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002481 /// result.
2482 /// zext Opnd to Ty.
2483 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002484 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002485 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002486 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002487 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002488 }
2489
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002490 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002491 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002492
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002493 /// Remove the built instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002494 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002495 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002496 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2497 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002498 }
2499 };
2500
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002501 /// Mutate an instruction to another type.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002502 class TypeMutator : public TypePromotionAction {
2503 /// Record the original type.
2504 Type *OrigTy;
2505
2506 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002507 /// Mutate the type of \p Inst into \p NewTy.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002508 TypeMutator(Instruction *Inst, Type *NewTy)
2509 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002510 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2511 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002512 Inst->mutateType(NewTy);
2513 }
2514
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002515 /// Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002516 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002517 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2518 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002519 Inst->mutateType(OrigTy);
2520 }
2521 };
2522
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002523 /// Replace the uses of an instruction by another instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002524 class UsesReplacer : public TypePromotionAction {
2525 /// Helper structure to keep track of the replaced uses.
2526 struct InstructionAndIdx {
2527 /// The instruction using the instruction.
2528 Instruction *Inst;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002529
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002530 /// The index where this instruction is used for Inst.
2531 unsigned Idx;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002532
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002533 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2534 : Inst(Inst), Idx(Idx) {}
2535 };
2536
2537 /// Keep track of the original uses (pair Instruction, Index).
2538 SmallVector<InstructionAndIdx, 4> OriginalUses;
Wolfgang Piebac874c42018-12-11 21:13:53 +00002539 /// Keep track of the debug users.
2540 SmallVector<DbgValueInst *, 1> DbgValues;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002541
2542 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002543
2544 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002545 /// Replace all the use of \p Inst by \p New.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002546 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002547 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2548 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002549 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002550 for (Use &U : Inst->uses()) {
2551 Instruction *UserI = cast<Instruction>(U.getUser());
2552 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002553 }
Wolfgang Piebac874c42018-12-11 21:13:53 +00002554 // Record the debug uses separately. They are not in the instruction's
2555 // use list, but they are replaced by RAUW.
2556 findDbgValues(DbgValues, Inst);
2557
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002558 // Now, we can replace the uses.
2559 Inst->replaceAllUsesWith(New);
2560 }
2561
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002562 /// Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002563 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002564 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002565 for (use_iterator UseIt = OriginalUses.begin(),
2566 EndIt = OriginalUses.end();
2567 UseIt != EndIt; ++UseIt) {
2568 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2569 }
Wolfgang Piebac874c42018-12-11 21:13:53 +00002570 // RAUW has replaced all original uses with references to the new value,
2571 // including the debug uses. Since we are undoing the replacements,
2572 // the original debug uses must also be reinstated to maintain the
2573 // correctness and utility of debug value instructions.
2574 for (auto *DVI: DbgValues) {
2575 LLVMContext &Ctx = Inst->getType()->getContext();
2576 auto *MV = MetadataAsValue::get(Ctx, ValueAsMetadata::get(Inst));
2577 DVI->setOperand(0, MV);
2578 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002579 }
2580 };
2581
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002582 /// Remove an instruction from the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002583 class InstructionRemover : public TypePromotionAction {
2584 /// Original position of the instruction.
2585 InsertionHandler Inserter;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002586
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002587 /// Helper structure to hide all the link to the instruction. In other
2588 /// words, this helps to do as if the instruction was removed.
2589 OperandsHider Hider;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002590
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002591 /// Keep track of the uses replaced, if any.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002592 UsesReplacer *Replacer = nullptr;
2593
Jun Bum Limdee55652017-04-03 19:20:07 +00002594 /// Keep track of instructions removed.
2595 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002596
2597 public:
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002598 /// Remove all reference of \p Inst and optionally replace all its
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002599 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002600 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002601 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002602 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2603 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002604 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Eugene Zelenko900b6332017-08-29 22:32:07 +00002605 RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002606 if (New)
2607 Replacer = new UsesReplacer(Inst, New);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002608 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002609 RemovedInsts.insert(Inst);
2610 /// The instructions removed here will be freed after completing
2611 /// optimizeBlock() for all blocks as we need to keep track of the
2612 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002613 Inst->removeFromParent();
2614 }
2615
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002616 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002617
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002618 /// Resurrect the instruction and reassign it to the proper uses if
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002619 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002620 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002621 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002622 Inserter.insert(Inst);
2623 if (Replacer)
2624 Replacer->undo();
2625 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002626 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002627 }
2628 };
2629
2630public:
2631 /// Restoration point.
2632 /// The restoration point is a pointer to an action instead of an iterator
2633 /// because the iterator may be invalidated but not the pointer.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002634 using ConstRestorationPt = const TypePromotionAction *;
Jun Bum Limdee55652017-04-03 19:20:07 +00002635
2636 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2637 : RemovedInsts(RemovedInsts) {}
2638
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002639 /// Advocate every changes made in that transaction.
2640 void commit();
Eugene Zelenko900b6332017-08-29 22:32:07 +00002641
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002642 /// Undo all the changes made after the given point.
2643 void rollback(ConstRestorationPt Point);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002644
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002645 /// Get the current restoration point.
2646 ConstRestorationPt getRestorationPoint() const;
2647
2648 /// \name API for IR modification with state keeping to support rollback.
2649 /// @{
2650 /// Same as Instruction::setOperand.
2651 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002652
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002653 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002654 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002655
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002656 /// Same as Value::replaceAllUsesWith.
2657 void replaceAllUsesWith(Instruction *Inst, Value *New);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002658
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002659 /// Same as Value::mutateType.
2660 void mutateType(Instruction *Inst, Type *NewTy);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002661
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002662 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002663 Value *createTrunc(Instruction *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002664
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002665 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002666 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002667
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002668 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002669 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002670
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002671 /// Same as Instruction::moveBefore.
2672 void moveBefore(Instruction *Inst, Instruction *Before);
2673 /// @}
2674
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002675private:
2676 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002677 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002678
2679 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2680
Jun Bum Limdee55652017-04-03 19:20:07 +00002681 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002682};
2683
Eugene Zelenko900b6332017-08-29 22:32:07 +00002684} // end anonymous namespace
2685
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002686void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2687 Value *NewVal) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002688 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2689 Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002690}
2691
2692void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2693 Value *NewVal) {
2694 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002695 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2696 Inst, RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002697}
2698
2699void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2700 Value *New) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002701 Actions.push_back(
2702 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002703}
2704
2705void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002706 Actions.push_back(
2707 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002708}
2709
Quentin Colombetac55b152014-09-16 22:36:07 +00002710Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2711 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002712 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002713 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002714 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002715 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002716}
2717
Quentin Colombetac55b152014-09-16 22:36:07 +00002718Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2719 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002720 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002721 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002722 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002723 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002724}
2725
Quentin Colombetac55b152014-09-16 22:36:07 +00002726Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2727 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002728 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002729 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002730 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002731 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002732}
2733
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002734void TypePromotionTransaction::moveBefore(Instruction *Inst,
2735 Instruction *Before) {
2736 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002737 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2738 Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002739}
2740
2741TypePromotionTransaction::ConstRestorationPt
2742TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002743 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002744}
2745
2746void TypePromotionTransaction::commit() {
2747 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002748 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002749 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002750 Actions.clear();
2751}
2752
2753void TypePromotionTransaction::rollback(
2754 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002755 while (!Actions.empty() && Point != Actions.back().get()) {
2756 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002757 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002758 }
2759}
2760
Eugene Zelenko900b6332017-08-29 22:32:07 +00002761namespace {
2762
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002763/// A helper class for matching addressing modes.
Chandler Carruthc8925912013-01-05 02:09:22 +00002764///
2765/// This encapsulates the logic for matching the target-legal addressing modes.
2766class AddressingModeMatcher {
2767 SmallVectorImpl<Instruction*> &AddrModeInsts;
2768 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002769 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002770 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002771
2772 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2773 /// the memory instruction that we're computing this address for.
2774 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002775 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002776 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002777
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002778 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002779 /// part of the return value of this addressing mode matching stuff.
2780 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002781
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002782 /// The instructions inserted by other CodeGenPrepare optimizations.
2783 const SetOfInstrs &InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002784
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002785 /// A map from the instructions to their type before promotion.
2786 InstrToOrigTy &PromotedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002787
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002788 /// The ongoing transaction where every action should be registered.
2789 TypePromotionTransaction &TPT;
2790
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002791 // A GEP which has too large offset to be folded into the addressing mode.
2792 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
2793
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002794 /// This is set to true when we should not do profitability checks.
2795 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002796 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002797
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002798 AddressingModeMatcher(
2799 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
2800 const TargetRegisterInfo &TRI, Type *AT, unsigned AS, Instruction *MI,
2801 ExtAddrMode &AM, const SetOfInstrs &InsertedInsts,
2802 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
2803 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002804 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002805 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2806 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002807 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002808 IgnoreProfitability = false;
2809 }
Stephen Lin837bba12013-07-15 17:55:02 +00002810
Eugene Zelenko900b6332017-08-29 22:32:07 +00002811public:
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002812 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002813 /// give an access type of AccessTy. This returns a list of involved
2814 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002815 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002816 /// optimizations.
2817 /// \p PromotedInsts maps the instructions to their type before promotion.
2818 /// \p The ongoing transaction where every action should be registered.
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002819 static ExtAddrMode
2820 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
2821 SmallVectorImpl<Instruction *> &AddrModeInsts,
2822 const TargetLowering &TLI, const TargetRegisterInfo &TRI,
2823 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
2824 TypePromotionTransaction &TPT,
2825 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002826 ExtAddrMode Result;
2827
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002828 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002829 MemoryInst, Result, InsertedInsts,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002830 PromotedInsts, TPT, LargeOffsetGEP)
2831 .matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002832 (void)Success; assert(Success && "Couldn't select *anything*?");
2833 return Result;
2834 }
Eugene Zelenko900b6332017-08-29 22:32:07 +00002835
Chandler Carruthc8925912013-01-05 02:09:22 +00002836private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002837 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
Fangrui Songcb0bab82018-07-16 18:51:40 +00002838 bool matchAddr(Value *Addr, unsigned Depth);
2839 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002840 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002841 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002842 ExtAddrMode &AMBefore,
2843 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002844 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2845 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002846 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002847};
2848
Ali Tamurd482b012018-11-12 21:43:43 +00002849class PhiNodeSet;
2850
2851/// An iterator for PhiNodeSet.
2852class PhiNodeSetIterator {
2853 PhiNodeSet * const Set;
2854 size_t CurrentIndex = 0;
2855
2856public:
2857 /// The constructor. Start should point to either a valid element, or be equal
2858 /// to the size of the underlying SmallVector of the PhiNodeSet.
2859 PhiNodeSetIterator(PhiNodeSet * const Set, size_t Start);
2860 PHINode * operator*() const;
2861 PhiNodeSetIterator& operator++();
2862 bool operator==(const PhiNodeSetIterator &RHS) const;
2863 bool operator!=(const PhiNodeSetIterator &RHS) const;
2864};
2865
2866/// Keeps a set of PHINodes.
2867///
2868/// This is a minimal set implementation for a specific use case:
2869/// It is very fast when there are very few elements, but also provides good
2870/// performance when there are many. It is similar to SmallPtrSet, but also
2871/// provides iteration by insertion order, which is deterministic and stable
2872/// across runs. It is also similar to SmallSetVector, but provides removing
2873/// elements in O(1) time. This is achieved by not actually removing the element
2874/// from the underlying vector, so comes at the cost of using more memory, but
2875/// that is fine, since PhiNodeSets are used as short lived objects.
2876class PhiNodeSet {
2877 friend class PhiNodeSetIterator;
2878
2879 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
2880 using iterator = PhiNodeSetIterator;
2881
2882 /// Keeps the elements in the order of their insertion in the underlying
2883 /// vector. To achieve constant time removal, it never deletes any element.
2884 SmallVector<PHINode *, 32> NodeList;
2885
2886 /// Keeps the elements in the underlying set implementation. This (and not the
2887 /// NodeList defined above) is the source of truth on whether an element
2888 /// is actually in the collection.
2889 MapType NodeMap;
2890
2891 /// Points to the first valid (not deleted) element when the set is not empty
2892 /// and the value is not zero. Equals to the size of the underlying vector
2893 /// when the set is empty. When the value is 0, as in the beginning, the
2894 /// first element may or may not be valid.
2895 size_t FirstValidElement = 0;
2896
2897public:
2898 /// Inserts a new element to the collection.
2899 /// \returns true if the element is actually added, i.e. was not in the
2900 /// collection before the operation.
2901 bool insert(PHINode *Ptr) {
2902 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
2903 NodeList.push_back(Ptr);
2904 return true;
2905 }
2906 return false;
2907 }
2908
2909 /// Removes the element from the collection.
2910 /// \returns whether the element is actually removed, i.e. was in the
2911 /// collection before the operation.
2912 bool erase(PHINode *Ptr) {
2913 auto it = NodeMap.find(Ptr);
2914 if (it != NodeMap.end()) {
2915 NodeMap.erase(Ptr);
2916 SkipRemovedElements(FirstValidElement);
2917 return true;
2918 }
2919 return false;
2920 }
2921
2922 /// Removes all elements and clears the collection.
2923 void clear() {
2924 NodeMap.clear();
2925 NodeList.clear();
2926 FirstValidElement = 0;
2927 }
2928
2929 /// \returns an iterator that will iterate the elements in the order of
2930 /// insertion.
2931 iterator begin() {
2932 if (FirstValidElement == 0)
2933 SkipRemovedElements(FirstValidElement);
2934 return PhiNodeSetIterator(this, FirstValidElement);
2935 }
2936
2937 /// \returns an iterator that points to the end of the collection.
2938 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
2939
2940 /// Returns the number of elements in the collection.
2941 size_t size() const {
2942 return NodeMap.size();
2943 }
2944
2945 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
2946 size_t count(PHINode *Ptr) const {
2947 return NodeMap.count(Ptr);
2948 }
2949
2950private:
2951 /// Updates the CurrentIndex so that it will point to a valid element.
2952 ///
2953 /// If the element of NodeList at CurrentIndex is valid, it does not
2954 /// change it. If there are no more valid elements, it updates CurrentIndex
2955 /// to point to the end of the NodeList.
2956 void SkipRemovedElements(size_t &CurrentIndex) {
2957 while (CurrentIndex < NodeList.size()) {
2958 auto it = NodeMap.find(NodeList[CurrentIndex]);
2959 // If the element has been deleted and added again later, NodeMap will
2960 // point to a different index, so CurrentIndex will still be invalid.
2961 if (it != NodeMap.end() && it->second == CurrentIndex)
2962 break;
2963 ++CurrentIndex;
2964 }
2965 }
2966};
2967
2968PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
2969 : Set(Set), CurrentIndex(Start) {}
2970
2971PHINode * PhiNodeSetIterator::operator*() const {
2972 assert(CurrentIndex < Set->NodeList.size() &&
2973 "PhiNodeSet access out of range");
2974 return Set->NodeList[CurrentIndex];
2975}
2976
2977PhiNodeSetIterator& PhiNodeSetIterator::operator++() {
2978 assert(CurrentIndex < Set->NodeList.size() &&
2979 "PhiNodeSet access out of range");
2980 ++CurrentIndex;
2981 Set->SkipRemovedElements(CurrentIndex);
2982 return *this;
2983}
2984
2985bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
2986 return CurrentIndex == RHS.CurrentIndex;
2987}
2988
2989bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
Serge Guelton12c7a962018-11-19 10:05:28 +00002990 return !((*this) == RHS);
Ali Tamurd482b012018-11-12 21:43:43 +00002991}
2992
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002993/// Keep track of simplification of Phi nodes.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002994/// Accept the set of all phi nodes and erase phi node from this set
2995/// if it is simplified.
2996class SimplificationTracker {
2997 DenseMap<Value *, Value *> Storage;
2998 const SimplifyQuery &SQ;
Ali Tamurd482b012018-11-12 21:43:43 +00002999 // Tracks newly created Phi nodes. The elements are iterated by insertion
3000 // order.
3001 PhiNodeSet AllPhiNodes;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003002 // Tracks newly created Select nodes.
3003 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003004
3005public:
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003006 SimplificationTracker(const SimplifyQuery &sq)
3007 : SQ(sq) {}
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003008
3009 Value *Get(Value *V) {
3010 do {
3011 auto SV = Storage.find(V);
3012 if (SV == Storage.end())
3013 return V;
3014 V = SV->second;
3015 } while (true);
3016 }
3017
3018 Value *Simplify(Value *Val) {
3019 SmallVector<Value *, 32> WorkList;
3020 SmallPtrSet<Value *, 32> Visited;
3021 WorkList.push_back(Val);
3022 while (!WorkList.empty()) {
3023 auto P = WorkList.pop_back_val();
3024 if (!Visited.insert(P).second)
3025 continue;
3026 if (auto *PI = dyn_cast<Instruction>(P))
3027 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
3028 for (auto *U : PI->users())
3029 WorkList.push_back(cast<Value>(U));
3030 Put(PI, V);
3031 PI->replaceAllUsesWith(V);
3032 if (auto *PHI = dyn_cast<PHINode>(PI))
Ali Tamurd482b012018-11-12 21:43:43 +00003033 AllPhiNodes.erase(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003034 if (auto *Select = dyn_cast<SelectInst>(PI))
3035 AllSelectNodes.erase(Select);
3036 PI->eraseFromParent();
3037 }
3038 }
3039 return Get(Val);
3040 }
3041
3042 void Put(Value *From, Value *To) {
3043 Storage.insert({ From, To });
3044 }
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003045
3046 void ReplacePhi(PHINode *From, PHINode *To) {
3047 Value* OldReplacement = Get(From);
3048 while (OldReplacement != From) {
3049 From = To;
3050 To = dyn_cast<PHINode>(OldReplacement);
3051 OldReplacement = Get(From);
3052 }
3053 assert(Get(To) == To && "Replacement PHI node is already replaced.");
3054 Put(From, To);
3055 From->replaceAllUsesWith(To);
Ali Tamurd482b012018-11-12 21:43:43 +00003056 AllPhiNodes.erase(From);
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003057 From->eraseFromParent();
3058 }
3059
Ali Tamurd482b012018-11-12 21:43:43 +00003060 PhiNodeSet& newPhiNodes() { return AllPhiNodes; }
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003061
3062 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
3063
3064 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
3065
3066 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
3067
3068 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
3069
3070 void destroyNewNodes(Type *CommonType) {
3071 // For safe erasing, replace the uses with dummy value first.
3072 auto Dummy = UndefValue::get(CommonType);
3073 for (auto I : AllPhiNodes) {
3074 I->replaceAllUsesWith(Dummy);
3075 I->eraseFromParent();
3076 }
3077 AllPhiNodes.clear();
3078 for (auto I : AllSelectNodes) {
3079 I->replaceAllUsesWith(Dummy);
3080 I->eraseFromParent();
3081 }
3082 AllSelectNodes.clear();
3083 }
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003084};
3085
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003086/// A helper class for combining addressing modes.
John Brawn736bf002017-10-03 13:08:22 +00003087class AddressingModeCombiner {
Serguei Katkov2673f172018-11-29 06:45:18 +00003088 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003089 typedef std::pair<PHINode *, PHINode *> PHIPair;
3090
John Brawn736bf002017-10-03 13:08:22 +00003091private:
3092 /// The addressing modes we've collected.
3093 SmallVector<ExtAddrMode, 16> AddrModes;
3094
3095 /// The field in which the AddrModes differ, when we have more than one.
3096 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
3097
3098 /// Are the AddrModes that we have all just equal to their original values?
3099 bool AllAddrModesTrivial = true;
3100
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003101 /// Common Type for all different fields in addressing modes.
3102 Type *CommonType;
3103
3104 /// SimplifyQuery for simplifyInstruction utility.
3105 const SimplifyQuery &SQ;
3106
3107 /// Original Address.
Serguei Katkov2673f172018-11-29 06:45:18 +00003108 Value *Original;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003109
John Brawn736bf002017-10-03 13:08:22 +00003110public:
Serguei Katkov2673f172018-11-29 06:45:18 +00003111 AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue)
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003112 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
3113
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003114 /// Get the combined AddrMode
John Brawn736bf002017-10-03 13:08:22 +00003115 const ExtAddrMode &getAddrMode() const {
3116 return AddrModes[0];
3117 }
3118
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003119 /// Add a new AddrMode if it's compatible with the AddrModes we already
John Brawn736bf002017-10-03 13:08:22 +00003120 /// have.
3121 /// \return True iff we succeeded in doing so.
3122 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
3123 // Take note of if we have any non-trivial AddrModes, as we need to detect
3124 // when all AddrModes are trivial as then we would introduce a phi or select
3125 // which just duplicates what's already there.
3126 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
3127
3128 // If this is the first addrmode then everything is fine.
3129 if (AddrModes.empty()) {
3130 AddrModes.emplace_back(NewAddrMode);
3131 return true;
3132 }
3133
3134 // Figure out how different this is from the other address modes, which we
3135 // can do just by comparing against the first one given that we only care
3136 // about the cumulative difference.
3137 ExtAddrMode::FieldName ThisDifferentField =
3138 AddrModes[0].compare(NewAddrMode);
3139 if (DifferentField == ExtAddrMode::NoField)
3140 DifferentField = ThisDifferentField;
3141 else if (DifferentField != ThisDifferentField)
3142 DifferentField = ExtAddrMode::MultipleFields;
3143
Serguei Katkov17e57942018-01-23 12:07:49 +00003144 // If NewAddrMode differs in more than one dimension we cannot handle it.
3145 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
3146
3147 // If Scale Field is different then we reject.
3148 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
3149
Serguei Katkov4d1dd6b2018-01-09 04:37:06 +00003150 // We also must reject the case when base offset is different and
3151 // scale reg is not null, we cannot handle this case due to merge of
3152 // different offsets will be used as ScaleReg.
Serguei Katkov17e57942018-01-23 12:07:49 +00003153 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
3154 !NewAddrMode.ScaledReg);
John Brawn736bf002017-10-03 13:08:22 +00003155
Serguei Katkov17e57942018-01-23 12:07:49 +00003156 // We also must reject the case when GV is different and BaseReg installed
3157 // due to we want to use base reg as a merge of GV values.
3158 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
3159 !NewAddrMode.HasBaseReg);
3160
3161 // Even if NewAddMode is the same we still need to collect it due to
3162 // original value is different. And later we will need all original values
3163 // as anchors during finding the common Phi node.
3164 if (CanHandle)
3165 AddrModes.emplace_back(NewAddrMode);
3166 else
3167 AddrModes.clear();
3168
3169 return CanHandle;
John Brawn736bf002017-10-03 13:08:22 +00003170 }
3171
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003172 /// Combine the addressing modes we've collected into a single
John Brawn736bf002017-10-03 13:08:22 +00003173 /// addressing mode.
3174 /// \return True iff we successfully combined them or we only had one so
3175 /// didn't need to combine them anyway.
3176 bool combineAddrModes() {
3177 // If we have no AddrModes then they can't be combined.
3178 if (AddrModes.size() == 0)
3179 return false;
3180
3181 // A single AddrMode can trivially be combined.
Serguei Katkov505359f2017-11-20 05:42:36 +00003182 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
John Brawn736bf002017-10-03 13:08:22 +00003183 return true;
3184
3185 // If the AddrModes we collected are all just equal to the value they are
3186 // derived from then combining them wouldn't do anything useful.
3187 if (AllAddrModesTrivial)
3188 return false;
3189
John Brawn70cdb5b2017-11-24 14:10:45 +00003190 if (!addrModeCombiningAllowed())
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003191 return false;
3192
3193 // Build a map between <original value, basic block where we saw it> to
3194 // value of base register.
Serguei Katkov50364592017-11-29 05:51:26 +00003195 // Bail out if there is no common type.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003196 FoldAddrToValueMapping Map;
Serguei Katkov50364592017-11-29 05:51:26 +00003197 if (!initializeMap(Map))
3198 return false;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003199
3200 Value *CommonValue = findCommon(Map);
3201 if (CommonValue)
John Brawn70cdb5b2017-11-24 14:10:45 +00003202 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003203 return CommonValue != nullptr;
3204 }
3205
3206private:
Serguei Katkov2673f172018-11-29 06:45:18 +00003207 /// Initialize Map with anchor values. For address seen
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003208 /// we set the value of different field saw in this address.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003209 /// At the same time we find a common type for different field we will
3210 /// use to create new Phi/Select nodes. Keep it in CommonType field.
Serguei Katkov50364592017-11-29 05:51:26 +00003211 /// Return false if there is no common type found.
3212 bool initializeMap(FoldAddrToValueMapping &Map) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003213 // Keep track of keys where the value is null. We will need to replace it
3214 // with constant null when we know the common type.
Serguei Katkov2673f172018-11-29 06:45:18 +00003215 SmallVector<Value *, 2> NullValue;
John Brawn70cdb5b2017-11-24 14:10:45 +00003216 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003217 for (auto &AM : AddrModes) {
John Brawn70cdb5b2017-11-24 14:10:45 +00003218 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003219 if (DV) {
Serguei Katkov50364592017-11-29 05:51:26 +00003220 auto *Type = DV->getType();
3221 if (CommonType && CommonType != Type)
3222 return false;
3223 CommonType = Type;
Serguei Katkov2673f172018-11-29 06:45:18 +00003224 Map[AM.OriginalValue] = DV;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003225 } else {
Serguei Katkov2673f172018-11-29 06:45:18 +00003226 NullValue.push_back(AM.OriginalValue);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003227 }
3228 }
3229 assert(CommonType && "At least one non-null value must be!");
Serguei Katkov2673f172018-11-29 06:45:18 +00003230 for (auto *V : NullValue)
3231 Map[V] = Constant::getNullValue(CommonType);
Serguei Katkov50364592017-11-29 05:51:26 +00003232 return true;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003233 }
3234
Serguei Katkov2673f172018-11-29 06:45:18 +00003235 /// We have mapping between value A and other value B where B was a field in
3236 /// addressing mode represented by A. Also we have an original value C
3237 /// representing an address we start with. Traversing from C through phi and
3238 /// selects we ended up with A's in a map. This utility function tries to find
3239 /// a value V which is a field in addressing mode C and traversing through phi
3240 /// nodes and selects we will end up in corresponded values B in a map.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003241 /// The utility will create a new Phi/Selects if needed.
3242 // The simple example looks as follows:
3243 // BB1:
3244 // p1 = b1 + 40
3245 // br cond BB2, BB3
3246 // BB2:
3247 // p2 = b2 + 40
3248 // br BB3
3249 // BB3:
3250 // p = phi [p1, BB1], [p2, BB2]
3251 // v = load p
3252 // Map is
Serguei Katkov2673f172018-11-29 06:45:18 +00003253 // p1 -> b1
3254 // p2 -> b2
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003255 // Request is
Serguei Katkov2673f172018-11-29 06:45:18 +00003256 // p -> ?
3257 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003258 Value *findCommon(FoldAddrToValueMapping &Map) {
Eric Christopherd72f78e2018-01-09 23:25:38 +00003259 // Tracks the simplification of newly created phi nodes. The reason we use
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003260 // this mapping is because we will add new created Phi nodes in AddrToBase.
3261 // Simplification of Phi nodes is recursive, so some Phi node may
Serguei Katkov2673f172018-11-29 06:45:18 +00003262 // be simplified after we added it to AddrToBase. In reality this
3263 // simplification is possible only if original phi/selects were not
3264 // simplified yet.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003265 // Using this mapping we can find the current value in AddrToBase.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003266 SimplificationTracker ST(SQ);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003267
3268 // First step, DFS to create PHI nodes for all intermediate blocks.
3269 // Also fill traverse order for the second step.
Serguei Katkov2673f172018-11-29 06:45:18 +00003270 SmallVector<Value *, 32> TraverseOrder;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003271 InsertPlaceholders(Map, TraverseOrder, ST);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003272
3273 // Second Step, fill new nodes by merged values and simplify if possible.
3274 FillPlaceholders(Map, TraverseOrder, ST);
3275
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003276 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
3277 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003278 return nullptr;
3279 }
3280
3281 // Now we'd like to match New Phi nodes to existed ones.
3282 unsigned PhiNotMatchedCount = 0;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003283 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
3284 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003285 return nullptr;
3286 }
3287
3288 auto *Result = ST.Get(Map.find(Original)->second);
3289 if (Result) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003290 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
3291 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003292 }
3293 return Result;
3294 }
3295
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003296 /// Try to match PHI node to Candidate.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003297 /// Matcher tracks the matched Phi nodes.
3298 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003299 SmallSetVector<PHIPair, 8> &Matcher,
Ali Tamurd482b012018-11-12 21:43:43 +00003300 PhiNodeSet &PhiNodesToMatch) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003301 SmallVector<PHIPair, 8> WorkList;
3302 Matcher.insert({ PHI, Candidate });
Mikael Holmen339daae2019-03-15 13:51:05 +00003303 SmallSet<PHINode *, 8> MatchedPHIs;
3304 MatchedPHIs.insert(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003305 WorkList.push_back({ PHI, Candidate });
3306 SmallSet<PHIPair, 8> Visited;
3307 while (!WorkList.empty()) {
3308 auto Item = WorkList.pop_back_val();
3309 if (!Visited.insert(Item).second)
3310 continue;
3311 // We iterate over all incoming values to Phi to compare them.
3312 // If values are different and both of them Phi and the first one is a
3313 // Phi we added (subject to match) and both of them is in the same basic
3314 // block then we can match our pair if values match. So we state that
3315 // these values match and add it to work list to verify that.
3316 for (auto B : Item.first->blocks()) {
3317 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
3318 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
3319 if (FirstValue == SecondValue)
3320 continue;
3321
3322 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
3323 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
3324
3325 // One of them is not Phi or
3326 // The first one is not Phi node from the set we'd like to match or
3327 // Phi nodes from different basic blocks then
3328 // we will not be able to match.
3329 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
3330 FirstPhi->getParent() != SecondPhi->getParent())
3331 return false;
3332
3333 // If we already matched them then continue.
3334 if (Matcher.count({ FirstPhi, SecondPhi }))
3335 continue;
3336 // So the values are different and does not match. So we need them to
Mikael Holmen339daae2019-03-15 13:51:05 +00003337 // match. (But we register no more than one match per PHI node, so that
3338 // we won't later try to replace them twice.)
3339 if (!MatchedPHIs.insert(FirstPhi).second)
3340 Matcher.insert({ FirstPhi, SecondPhi });
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003341 // But me must check it.
3342 WorkList.push_back({ FirstPhi, SecondPhi });
3343 }
3344 }
3345 return true;
3346 }
3347
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003348 /// For the given set of PHI nodes (in the SimplificationTracker) try
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003349 /// to find their equivalents.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003350 /// Returns false if this matching fails and creation of new Phi is disabled.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003351 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003352 unsigned &PhiNotMatchedCount) {
Ali Tamurd482b012018-11-12 21:43:43 +00003353 // Matched and PhiNodesToMatch iterate their elements in a deterministic
3354 // order, so the replacements (ReplacePhi) are also done in a deterministic
3355 // order.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003356 SmallSetVector<PHIPair, 8> Matched;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003357 SmallPtrSet<PHINode *, 8> WillNotMatch;
Ali Tamurd482b012018-11-12 21:43:43 +00003358 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003359 while (PhiNodesToMatch.size()) {
3360 PHINode *PHI = *PhiNodesToMatch.begin();
3361
3362 // Add us, if no Phi nodes in the basic block we do not match.
3363 WillNotMatch.clear();
3364 WillNotMatch.insert(PHI);
3365
3366 // Traverse all Phis until we found equivalent or fail to do that.
3367 bool IsMatched = false;
3368 for (auto &P : PHI->getParent()->phis()) {
3369 if (&P == PHI)
3370 continue;
3371 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3372 break;
3373 // If it does not match, collect all Phi nodes from matcher.
3374 // if we end up with no match, them all these Phi nodes will not match
3375 // later.
3376 for (auto M : Matched)
3377 WillNotMatch.insert(M.first);
3378 Matched.clear();
3379 }
3380 if (IsMatched) {
Serguei Katkova20e05b2018-03-12 03:50:07 +00003381 // Replace all matched values and erase them.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003382 for (auto MV : Matched)
3383 ST.ReplacePhi(MV.first, MV.second);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003384 Matched.clear();
3385 continue;
3386 }
3387 // If we are not allowed to create new nodes then bail out.
3388 if (!AllowNewPhiNodes)
3389 return false;
3390 // Just remove all seen values in matcher. They will not match anything.
3391 PhiNotMatchedCount += WillNotMatch.size();
3392 for (auto *P : WillNotMatch)
Ali Tamurd482b012018-11-12 21:43:43 +00003393 PhiNodesToMatch.erase(P);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003394 }
3395 return true;
3396 }
Serguei Katkov2673f172018-11-29 06:45:18 +00003397 /// Fill the placeholders with values from predecessors and simplify them.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003398 void FillPlaceholders(FoldAddrToValueMapping &Map,
Serguei Katkov2673f172018-11-29 06:45:18 +00003399 SmallVectorImpl<Value *> &TraverseOrder,
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003400 SimplificationTracker &ST) {
3401 while (!TraverseOrder.empty()) {
Serguei Katkov2673f172018-11-29 06:45:18 +00003402 Value *Current = TraverseOrder.pop_back_val();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003403 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003404 Value *V = Map[Current];
3405
3406 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3407 // CurrentValue also must be Select.
Serguei Katkov2673f172018-11-29 06:45:18 +00003408 auto *CurrentSelect = cast<SelectInst>(Current);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003409 auto *TrueValue = CurrentSelect->getTrueValue();
Serguei Katkov2673f172018-11-29 06:45:18 +00003410 assert(Map.find(TrueValue) != Map.end() && "No True Value!");
3411 Select->setTrueValue(ST.Get(Map[TrueValue]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003412 auto *FalseValue = CurrentSelect->getFalseValue();
Serguei Katkov2673f172018-11-29 06:45:18 +00003413 assert(Map.find(FalseValue) != Map.end() && "No False Value!");
3414 Select->setFalseValue(ST.Get(Map[FalseValue]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003415 } else {
3416 // Must be a Phi node then.
3417 PHINode *PHI = cast<PHINode>(V);
Serguei Katkov2673f172018-11-29 06:45:18 +00003418 auto *CurrentPhi = dyn_cast<PHINode>(Current);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003419 // Fill the Phi node with values from predecessors.
Serguei Katkov2673f172018-11-29 06:45:18 +00003420 for (auto B : predecessors(PHI->getParent())) {
3421 Value *PV = CurrentPhi->getIncomingValueForBlock(B);
3422 assert(Map.find(PV) != Map.end() && "No predecessor Value!");
3423 PHI->addIncoming(ST.Get(Map[PV]), B);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003424 }
3425 }
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003426 Map[Current] = ST.Simplify(V);
3427 }
3428 }
3429
Serguei Katkov2673f172018-11-29 06:45:18 +00003430 /// Starting from original value recursively iterates over def-use chain up to
3431 /// known ending values represented in a map. For each traversed phi/select
3432 /// inserts a placeholder Phi or Select.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003433 /// Reports all new created Phi/Select nodes by adding them to set.
Serguei Katkov2673f172018-11-29 06:45:18 +00003434 /// Also reports and order in what values have been traversed.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003435 void InsertPlaceholders(FoldAddrToValueMapping &Map,
Serguei Katkov2673f172018-11-29 06:45:18 +00003436 SmallVectorImpl<Value *> &TraverseOrder,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003437 SimplificationTracker &ST) {
Serguei Katkov2673f172018-11-29 06:45:18 +00003438 SmallVector<Value *, 32> Worklist;
3439 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003440 "Address must be a Phi or Select node");
3441 auto *Dummy = UndefValue::get(CommonType);
3442 Worklist.push_back(Original);
3443 while (!Worklist.empty()) {
Serguei Katkov2673f172018-11-29 06:45:18 +00003444 Value *Current = Worklist.pop_back_val();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003445 // if it is already visited or it is an ending value then skip it.
3446 if (Map.find(Current) != Map.end())
3447 continue;
3448 TraverseOrder.push_back(Current);
3449
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003450 // CurrentValue must be a Phi node or select. All others must be covered
3451 // by anchors.
Serguei Katkov2673f172018-11-29 06:45:18 +00003452 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003453 // Is it OK to get metadata from OrigSelect?!
3454 // Create a Select placeholder with dummy value.
Serguei Katkov2673f172018-11-29 06:45:18 +00003455 SelectInst *Select = SelectInst::Create(
3456 CurrentSelect->getCondition(), Dummy, Dummy,
3457 CurrentSelect->getName(), CurrentSelect, CurrentSelect);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003458 Map[Current] = Select;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003459 ST.insertNewSelect(Select);
Serguei Katkov2673f172018-11-29 06:45:18 +00003460 // We are interested in True and False values.
3461 Worklist.push_back(CurrentSelect->getTrueValue());
3462 Worklist.push_back(CurrentSelect->getFalseValue());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003463 } else {
3464 // It must be a Phi node then.
Serguei Katkov2673f172018-11-29 06:45:18 +00003465 PHINode *CurrentPhi = cast<PHINode>(Current);
3466 unsigned PredCount = CurrentPhi->getNumIncomingValues();
3467 PHINode *PHI =
3468 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003469 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003470 ST.insertNewPhi(PHI);
Serguei Katkov2673f172018-11-29 06:45:18 +00003471 for (Value *P : CurrentPhi->incoming_values())
3472 Worklist.push_back(P);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003473 }
3474 }
John Brawn736bf002017-10-03 13:08:22 +00003475 }
John Brawn70cdb5b2017-11-24 14:10:45 +00003476
3477 bool addrModeCombiningAllowed() {
3478 if (DisableComplexAddrModes)
3479 return false;
3480 switch (DifferentField) {
3481 default:
3482 return false;
3483 case ExtAddrMode::BaseRegField:
3484 return AddrSinkCombineBaseReg;
3485 case ExtAddrMode::BaseGVField:
3486 return AddrSinkCombineBaseGV;
3487 case ExtAddrMode::BaseOffsField:
3488 return AddrSinkCombineBaseOffs;
3489 case ExtAddrMode::ScaledRegField:
3490 return AddrSinkCombineScaledReg;
3491 }
3492 }
John Brawn736bf002017-10-03 13:08:22 +00003493};
Eugene Zelenko900b6332017-08-29 22:32:07 +00003494} // end anonymous namespace
3495
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003496/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003497/// Return true and update AddrMode if this addr mode is legal for the target,
3498/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003499bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003500 unsigned Depth) {
3501 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3502 // mode. Just process that directly.
3503 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003504 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003505
Chandler Carruthc8925912013-01-05 02:09:22 +00003506 // If the scale is 0, it takes nothing to add this.
3507 if (Scale == 0)
3508 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003509
Chandler Carruthc8925912013-01-05 02:09:22 +00003510 // If we already have a scale of this value, we can add to it, otherwise, we
3511 // need an available scale field.
3512 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3513 return false;
3514
3515 ExtAddrMode TestAddrMode = AddrMode;
3516
3517 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3518 // [A+B + A*7] -> [B+A*8].
3519 TestAddrMode.Scale += Scale;
3520 TestAddrMode.ScaledReg = ScaleReg;
3521
3522 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003523 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003524 return false;
3525
3526 // It was legal, so commit it.
3527 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003528
Chandler Carruthc8925912013-01-05 02:09:22 +00003529 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3530 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3531 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003532 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003533 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3534 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
Tim Northover8935aca2019-03-12 15:22:23 +00003535 TestAddrMode.InBounds = false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003536 TestAddrMode.ScaledReg = AddLHS;
3537 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003538
Chandler Carruthc8925912013-01-05 02:09:22 +00003539 // If this addressing mode is legal, commit it and remember that we folded
3540 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003541 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003542 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3543 AddrMode = TestAddrMode;
3544 return true;
3545 }
3546 }
3547
3548 // Otherwise, not (x+c)*scale, just return what we have.
3549 return true;
3550}
3551
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003552/// This is a little filter, which returns true if an addressing computation
3553/// involving I might be folded into a load/store accessing it.
3554/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003555/// the set of instructions that MatchOperationAddr can.
3556static bool MightBeFoldableInst(Instruction *I) {
3557 switch (I->getOpcode()) {
3558 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003559 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003560 // Don't touch identity bitcasts.
3561 if (I->getType() == I->getOperand(0)->getType())
3562 return false;
Vedant Kumarb3091da2018-07-06 20:17:42 +00003563 return I->getType()->isIntOrPtrTy();
Chandler Carruthc8925912013-01-05 02:09:22 +00003564 case Instruction::PtrToInt:
3565 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3566 return true;
3567 case Instruction::IntToPtr:
3568 // We know the input is intptr_t, so this is foldable.
3569 return true;
3570 case Instruction::Add:
3571 return true;
3572 case Instruction::Mul:
3573 case Instruction::Shl:
3574 // Can only handle X*C and X << C.
3575 return isa<ConstantInt>(I->getOperand(1));
3576 case Instruction::GetElementPtr:
3577 return true;
3578 default:
3579 return false;
3580 }
3581}
3582
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003583/// Check whether or not \p Val is a legal instruction for \p TLI.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003584/// \note \p Val is assumed to be the product of some type promotion.
3585/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3586/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003587static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3588 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003589 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3590 if (!PromotedInst)
3591 return false;
3592 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3593 // If the ISDOpcode is undefined, it was undefined before the promotion.
3594 if (!ISDOpcode)
3595 return true;
3596 // Otherwise, check if the promoted instruction is legal or not.
3597 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003598 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003599}
3600
Eugene Zelenko900b6332017-08-29 22:32:07 +00003601namespace {
3602
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003603/// Hepler class to perform type promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003604class TypePromotionHelper {
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003605 /// Utility function to add a promoted instruction \p ExtOpnd to
3606 /// \p PromotedInsts and record the type of extension we have seen.
3607 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
3608 Instruction *ExtOpnd,
3609 bool IsSExt) {
3610 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3611 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
3612 if (It != PromotedInsts.end()) {
3613 // If the new extension is same as original, the information in
3614 // PromotedInsts[ExtOpnd] is still correct.
3615 if (It->second.getInt() == ExtTy)
3616 return;
3617
3618 // Now the new extension is different from old extension, we make
3619 // the type information invalid by setting extension type to
3620 // BothExtension.
3621 ExtTy = BothExtension;
3622 }
3623 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
3624 }
3625
3626 /// Utility function to query the original type of instruction \p Opnd
3627 /// with a matched extension type. If the extension doesn't match, we
3628 /// cannot use the information we had on the original type.
3629 /// BothExtension doesn't match any extension type.
3630 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
3631 Instruction *Opnd,
3632 bool IsSExt) {
3633 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3634 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3635 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
3636 return It->second.getPointer();
3637 return nullptr;
3638 }
3639
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003640 /// Utility function to check whether or not a sign or zero extension
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003641 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3642 /// either using the operands of \p Inst or promoting \p Inst.
3643 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003644 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003645 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003646 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003647 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003648 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003649 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003650 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003651 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3652 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003653
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003654 /// Utility function to determine if \p OpIdx should be promoted when
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003655 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003656 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003657 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003658 }
3659
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003660 /// Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003661 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003662 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003663 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003664 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003665 /// Newly added extensions are inserted in \p Exts.
3666 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003667 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003668 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003669 static Value *promoteOperandForTruncAndAnyExt(
3670 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003671 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003672 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003673 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003674
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003675 /// Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003676 /// operand is promotable and is not a supported trunc or sext.
3677 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003678 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003679 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003680 /// Newly added extensions are inserted in \p Exts.
3681 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003682 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003683 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003684 static Value *promoteOperandForOther(Instruction *Ext,
3685 TypePromotionTransaction &TPT,
3686 InstrToOrigTy &PromotedInsts,
3687 unsigned &CreatedInstsCost,
3688 SmallVectorImpl<Instruction *> *Exts,
3689 SmallVectorImpl<Instruction *> *Truncs,
3690 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003691
3692 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003693 static Value *signExtendOperandForOther(
3694 Instruction *Ext, TypePromotionTransaction &TPT,
3695 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3696 SmallVectorImpl<Instruction *> *Exts,
3697 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3698 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3699 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003700 }
3701
3702 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003703 static Value *zeroExtendOperandForOther(
3704 Instruction *Ext, TypePromotionTransaction &TPT,
3705 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3706 SmallVectorImpl<Instruction *> *Exts,
3707 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3708 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3709 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003710 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003711
3712public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003713 /// Type for the utility function that promotes the operand of Ext.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003714 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3715 InstrToOrigTy &PromotedInsts,
3716 unsigned &CreatedInstsCost,
3717 SmallVectorImpl<Instruction *> *Exts,
3718 SmallVectorImpl<Instruction *> *Truncs,
3719 const TargetLowering &TLI);
3720
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003721 /// Given a sign/zero extend instruction \p Ext, return the appropriate
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003722 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003723 /// \return NULL if no promotable action is possible with the current
3724 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003725 /// \p InsertedInsts keeps track of all the instructions inserted by the
3726 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003727 /// because we do not want to promote these instructions as CodeGenPrepare
3728 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3729 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003730 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003731 const TargetLowering &TLI,
3732 const InstrToOrigTy &PromotedInsts);
3733};
3734
Eugene Zelenko900b6332017-08-29 22:32:07 +00003735} // end anonymous namespace
3736
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003737bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003738 Type *ConsideredExtType,
3739 const InstrToOrigTy &PromotedInsts,
3740 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003741 // The promotion helper does not know how to deal with vector types yet.
3742 // To be able to fix that, we would need to fix the places where we
3743 // statically extend, e.g., constants and such.
3744 if (Inst->getType()->isVectorTy())
3745 return false;
3746
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003747 // We can always get through zext.
3748 if (isa<ZExtInst>(Inst))
3749 return true;
3750
3751 // sext(sext) is ok too.
3752 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003753 return true;
3754
3755 // We can get through binary operator, if it is legal. In other words, the
3756 // binary operator must have a nuw or nsw flag.
3757 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3758 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003759 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3760 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003761 return true;
3762
Guozhi Weic4c6b542018-06-05 21:03:52 +00003763 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
3764 if ((Inst->getOpcode() == Instruction::And ||
3765 Inst->getOpcode() == Instruction::Or))
3766 return true;
3767
3768 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
3769 if (Inst->getOpcode() == Instruction::Xor) {
3770 const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1));
3771 // Make sure it is not a NOT.
3772 if (Cst && !Cst->getValue().isAllOnesValue())
3773 return true;
3774 }
3775
3776 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
3777 // It may change a poisoned value into a regular value, like
3778 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
3779 // poisoned value regular value
3780 // It should be OK since undef covers valid value.
3781 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
3782 return true;
3783
3784 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
3785 // It may change a poisoned value into a regular value, like
3786 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
3787 // poisoned value regular value
3788 // It should be OK since undef covers valid value.
3789 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
3790 const Instruction *ExtInst =
3791 dyn_cast<const Instruction>(*Inst->user_begin());
3792 if (ExtInst->hasOneUse()) {
3793 const Instruction *AndInst =
3794 dyn_cast<const Instruction>(*ExtInst->user_begin());
3795 if (AndInst && AndInst->getOpcode() == Instruction::And) {
3796 const ConstantInt *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
3797 if (Cst &&
3798 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
3799 return true;
3800 }
3801 }
3802 }
3803
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003804 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003805 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003806 if (!isa<TruncInst>(Inst))
3807 return false;
3808
3809 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003810 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003811 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003812 if (!OpndVal->getType()->isIntegerTy() ||
3813 OpndVal->getType()->getIntegerBitWidth() >
3814 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003815 return false;
3816
3817 // If the operand of the truncate is not an instruction, we will not have
3818 // any information on the dropped bits.
3819 // (Actually we could for constant but it is not worth the extra logic).
3820 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3821 if (!Opnd)
3822 return false;
3823
3824 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003825 // I.e., check that trunc just drops extended bits of the same kind of
3826 // the extension.
3827 // #1 get the type of the operand and check the kind of the extended bits.
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003828 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
3829 if (OpndType)
3830 ;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003831 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3832 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003833 else
3834 return false;
3835
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003836 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003837 return Inst->getType()->getIntegerBitWidth() >=
3838 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003839}
3840
3841TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003842 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003843 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003844 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3845 "Unexpected instruction type");
3846 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3847 Type *ExtTy = Ext->getType();
3848 bool IsSExt = isa<SExtInst>(Ext);
3849 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003850 // get through.
3851 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003852 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003853 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003854
3855 // Do not promote if the operand has been added by codegenprepare.
3856 // Otherwise, it means we are undoing an optimization that is likely to be
3857 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003858 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003859 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003860
3861 // SExt or Trunc instructions.
3862 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003863 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3864 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003865 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003866
3867 // Regular instruction.
3868 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003869 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003870 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003871 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003872}
3873
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003874Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003875 Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003876 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003877 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003878 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003879 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3880 // get through it and this method should not be called.
3881 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003882 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003883 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003884 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003885 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003886 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003887 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003888 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003889 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3890 TPT.replaceAllUsesWith(SExt, ZExt);
3891 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003892 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003893 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003894 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3895 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003896 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3897 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003898 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003899
3900 // Remove dead code.
3901 if (SExtOpnd->use_empty())
3902 TPT.eraseInstruction(SExtOpnd);
3903
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003904 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003905 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003906 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003907 if (ExtInst) {
3908 if (Exts)
3909 Exts->push_back(ExtInst);
3910 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3911 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003912 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003913 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003914
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003915 // At this point we have: ext ty opnd to ty.
3916 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3917 Value *NextVal = ExtInst->getOperand(0);
3918 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003919 return NextVal;
3920}
3921
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003922Value *TypePromotionHelper::promoteOperandForOther(
3923 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003924 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003925 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003926 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3927 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003928 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003929 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003930 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003931 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003932 if (!ExtOpnd->hasOneUse()) {
3933 // ExtOpnd will be promoted.
3934 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003935 // promoted version.
3936 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003937 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003938 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
Quentin Colombetac55b152014-09-16 22:36:07 +00003939 // Insert it just after the definition.
Sanjay Patel674d2c22017-08-29 14:07:48 +00003940 ITrunc->moveAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003941 if (Truncs)
3942 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003943 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003944
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003945 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003946 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003947 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003948 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003949 }
3950
3951 // Get through the Instruction:
3952 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003953 // 2. Replace the uses of Ext by Inst.
3954 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003955
3956 // Remember the original type of the instruction before promotion.
3957 // This is useful to know that the high bits are sign extended bits.
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003958 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003959 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003960 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003961 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003962 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003963 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003964 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003965
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003966 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003967 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003968 ++OpIdx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003969 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003970 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3971 !shouldExtOperand(ExtOpnd, OpIdx)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003972 LLVM_DEBUG(dbgs() << "No need to propagate\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003973 continue;
3974 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003975 // Check if we can statically extend the operand.
3976 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003977 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003978 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003979 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3980 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3981 : Cst->getValue().zext(BitWidth);
3982 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003983 continue;
3984 }
3985 // UndefValue are typed, so we have to statically sign extend them.
3986 if (isa<UndefValue>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003987 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003988 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003989 continue;
3990 }
3991
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003992 // Otherwise we have to explicitly sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003993 // Check if Ext was reused to extend an operand.
3994 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003995 // If yes, create a new one.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003996 LLVM_DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003997 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3998 : TPT.createZExt(Ext, Opnd, Ext->getType());
3999 if (!isa<Instruction>(ValForExtOpnd)) {
4000 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
4001 continue;
4002 }
4003 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004004 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004005 if (Exts)
4006 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004007 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004008
4009 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004010 TPT.moveBefore(ExtForOpnd, ExtOpnd);
4011 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004012 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004013 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004014 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004015 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004016 if (ExtForOpnd == Ext) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004017 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004018 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004019 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004020 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004021}
4022
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004023/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004024/// \p NewCost gives the cost of extension instructions created by the
4025/// promotion.
4026/// \p OldCost gives the cost of extension instructions before the promotion
4027/// plus the number of instructions that have been
4028/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00004029/// \p PromotedOperand is the value that has been promoted.
4030/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004031bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00004032 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004033 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
4034 << '\n');
Quentin Colombet1b274f92015-03-10 21:48:15 +00004035 // The cost of the new extensions is greater than the cost of the
4036 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00004037 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004038 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00004039 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004040 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00004041 return true;
4042 // The promotion is neutral but it may help folding the sign extension in
4043 // loads for instance.
4044 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00004045 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00004046}
4047
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004048/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004049/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004050/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004051/// If \p MovedAway is not NULL, it contains the information of whether or
4052/// not AddrInst has to be folded into the addressing mode on success.
4053/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
4054/// because it has been moved away.
4055/// Thus AddrInst must not be added in the matched instructions.
4056/// This state can happen when AddrInst is a sext, since it may be moved away.
4057/// Therefore, AddrInst may not be valid when MovedAway is true and it must
4058/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004059bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004060 unsigned Depth,
4061 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004062 // Avoid exponential behavior on extremely deep expression trees.
4063 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004064
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004065 // By default, all matched instructions stay in place.
4066 if (MovedAway)
4067 *MovedAway = false;
4068
Chandler Carruthc8925912013-01-05 02:09:22 +00004069 switch (Opcode) {
4070 case Instruction::PtrToInt:
4071 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004072 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00004073 case Instruction::IntToPtr: {
4074 auto AS = AddrInst->getType()->getPointerAddressSpace();
4075 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00004076 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00004077 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00004078 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00004079 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00004080 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004081 case Instruction::BitCast:
4082 // BitCast is always a noop, and we can handle it as long as it is
4083 // int->int or pointer->pointer (we don't want int<->fp or something).
Vedant Kumarb3091da2018-07-06 20:17:42 +00004084 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
Chandler Carruthc8925912013-01-05 02:09:22 +00004085 // Don't touch identity bitcasts. These were probably put here by LSR,
4086 // and we don't want to mess around with them. Assume it knows what it
4087 // is doing.
4088 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00004089 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00004090 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00004091 case Instruction::AddrSpaceCast: {
4092 unsigned SrcAS
4093 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
4094 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
4095 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00004096 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00004097 return false;
4098 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004099 case Instruction::Add: {
4100 // Check to see if we can merge in the RHS then the LHS. If so, we win.
4101 ExtAddrMode BackupAddrMode = AddrMode;
4102 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004103 // Start a transaction at this point.
4104 // The LHS may match but not the RHS.
4105 // Therefore, we need a higher level restoration point to undo partially
4106 // matched operation.
4107 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4108 TPT.getRestorationPoint();
4109
Tim Northover8935aca2019-03-12 15:22:23 +00004110 AddrMode.InBounds = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004111 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
4112 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00004113 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004114
Chandler Carruthc8925912013-01-05 02:09:22 +00004115 // Restore the old addr mode info.
4116 AddrMode = BackupAddrMode;
4117 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004118 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00004119
Chandler Carruthc8925912013-01-05 02:09:22 +00004120 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004121 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
4122 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00004123 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004124
Chandler Carruthc8925912013-01-05 02:09:22 +00004125 // Otherwise we definitely can't merge the ADD in.
4126 AddrMode = BackupAddrMode;
4127 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004128 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004129 break;
4130 }
4131 //case Instruction::Or:
4132 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
4133 //break;
4134 case Instruction::Mul:
4135 case Instruction::Shl: {
4136 // Can only handle X*C and X << C.
Tim Northover8935aca2019-03-12 15:22:23 +00004137 AddrMode.InBounds = false;
Chandler Carruthc8925912013-01-05 02:09:22 +00004138 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Philip Reames9c3cbee2017-10-30 23:59:51 +00004139 if (!RHS || RHS->getBitWidth() > 64)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00004140 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00004141 int64_t Scale = RHS->getSExtValue();
4142 if (Opcode == Instruction::Shl)
4143 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00004144
Sanjay Patelfc580a62015-09-21 23:03:16 +00004145 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00004146 }
4147 case Instruction::GetElementPtr: {
4148 // Scan the GEP. We check it if it contains constant offsets and at most
4149 // one variable offset.
4150 int VariableOperand = -1;
4151 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00004152
Chandler Carruthc8925912013-01-05 02:09:22 +00004153 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00004154 gep_type_iterator GTI = gep_type_begin(AddrInst);
4155 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00004156 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00004157 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00004158 unsigned Idx =
4159 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
4160 ConstantOffset += SL->getElementOffset(Idx);
4161 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00004162 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00004163 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
Simon Pilgrimee82a792018-08-13 12:10:09 +00004164 const APInt &CVal = CI->getValue();
4165 if (CVal.getMinSignedBits() <= 64) {
4166 ConstantOffset += CVal.getSExtValue() * TypeSize;
4167 continue;
4168 }
4169 }
4170 if (TypeSize) { // Scales of zero don't do anything.
Chandler Carruthc8925912013-01-05 02:09:22 +00004171 // We only allow one variable index at the moment.
4172 if (VariableOperand != -1)
4173 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004174
Chandler Carruthc8925912013-01-05 02:09:22 +00004175 // Remember the variable index.
4176 VariableOperand = i;
4177 VariableScale = TypeSize;
4178 }
4179 }
4180 }
Stephen Lin837bba12013-07-15 17:55:02 +00004181
Chandler Carruthc8925912013-01-05 02:09:22 +00004182 // A common case is for the GEP to only do a constant offset. In this case,
4183 // just add it to the disp field and check validity.
4184 if (VariableOperand == -1) {
4185 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004186 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004187 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004188 // Check to see if we can fold the base pointer in too.
Tim Northover8935aca2019-03-12 15:22:23 +00004189 if (matchAddr(AddrInst->getOperand(0), Depth+1)) {
4190 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4191 AddrMode.InBounds = false;
Chandler Carruthc8925912013-01-05 02:09:22 +00004192 return true;
Tim Northover8935aca2019-03-12 15:22:23 +00004193 }
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004194 } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
4195 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
4196 ConstantOffset > 0) {
4197 // Record GEPs with non-zero offsets as candidates for splitting in the
4198 // event that the offset cannot fit into the r+i addressing mode.
4199 // Simple and common case that only one GEP is used in calculating the
4200 // address for the memory access.
4201 Value *Base = AddrInst->getOperand(0);
4202 auto *BaseI = dyn_cast<Instruction>(Base);
4203 auto *GEP = cast<GetElementPtrInst>(AddrInst);
4204 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
4205 (BaseI && !isa<CastInst>(BaseI) &&
4206 !isa<GetElementPtrInst>(BaseI))) {
4207 // If the base is an instruction, make sure the GEP is not in the same
4208 // basic block as the base. If the base is an argument or global
4209 // value, make sure the GEP is not in the entry block. Otherwise,
4210 // instruction selection can undo the split. Also make sure the
4211 // parent block allows inserting non-PHI instructions before the
4212 // terminator.
4213 BasicBlock *Parent =
4214 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
4215 if (GEP->getParent() != Parent && !Parent->getTerminator()->isEHPad())
4216 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
4217 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004218 }
4219 AddrMode.BaseOffs -= ConstantOffset;
4220 return false;
4221 }
4222
4223 // Save the valid addressing mode in case we can't match.
4224 ExtAddrMode BackupAddrMode = AddrMode;
4225 unsigned OldSize = AddrModeInsts.size();
4226
4227 // See if the scale and offset amount is valid for this target.
4228 AddrMode.BaseOffs += ConstantOffset;
Tim Northover8935aca2019-03-12 15:22:23 +00004229 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4230 AddrMode.InBounds = false;
Chandler Carruthc8925912013-01-05 02:09:22 +00004231
4232 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004233 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004234 // If it couldn't be matched, just stuff the value in a register.
4235 if (AddrMode.HasBaseReg) {
4236 AddrMode = BackupAddrMode;
4237 AddrModeInsts.resize(OldSize);
4238 return false;
4239 }
4240 AddrMode.HasBaseReg = true;
4241 AddrMode.BaseReg = AddrInst->getOperand(0);
4242 }
4243
4244 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004245 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00004246 Depth)) {
4247 // If it couldn't be matched, try stuffing the base into a register
4248 // instead of matching it, and retrying the match of the scale.
4249 AddrMode = BackupAddrMode;
4250 AddrModeInsts.resize(OldSize);
4251 if (AddrMode.HasBaseReg)
4252 return false;
4253 AddrMode.HasBaseReg = true;
4254 AddrMode.BaseReg = AddrInst->getOperand(0);
4255 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004256 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00004257 VariableScale, Depth)) {
4258 // If even that didn't work, bail.
4259 AddrMode = BackupAddrMode;
4260 AddrModeInsts.resize(OldSize);
4261 return false;
4262 }
4263 }
4264
4265 return true;
4266 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004267 case Instruction::SExt:
4268 case Instruction::ZExt: {
4269 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
4270 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00004271 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00004272
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004273 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004274 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004275 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004276 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004277 if (!TPH)
4278 return false;
4279
4280 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4281 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00004282 unsigned CreatedInstsCost = 0;
4283 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004284 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00004285 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004286 // SExt has been moved away.
4287 // Thus either it will be rematched later in the recursive calls or it is
4288 // gone. Anyway, we must not fold it into the addressing mode at this point.
4289 // E.g.,
4290 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004291 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004292 // addr = gep base, idx
4293 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004294 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004295 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
4296 // addr = gep base, op <- match
4297 if (MovedAway)
4298 *MovedAway = true;
4299
4300 assert(PromotedOperand &&
4301 "TypePromotionHelper should have filtered out those cases");
4302
4303 ExtAddrMode BackupAddrMode = AddrMode;
4304 unsigned OldSize = AddrModeInsts.size();
4305
Sanjay Patelfc580a62015-09-21 23:03:16 +00004306 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004307 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00004308 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004309 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00004310 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004311 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004312 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00004313 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004314 AddrMode = BackupAddrMode;
4315 AddrModeInsts.resize(OldSize);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004316 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004317 TPT.rollback(LastKnownGood);
4318 return false;
4319 }
4320 return true;
4321 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004322 }
4323 return false;
4324}
4325
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004326/// If we can, try to add the value of 'Addr' into the current addressing mode.
4327/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4328/// unmodified. This assumes that Addr is either a pointer type or intptr_t
4329/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00004330///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004331bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004332 // Start a transaction at this point that we will rollback if the matching
4333 // fails.
4334 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4335 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00004336 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4337 // Fold in immediates if legal for the target.
4338 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004339 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004340 return true;
4341 AddrMode.BaseOffs -= CI->getSExtValue();
4342 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4343 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00004344 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004345 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004346 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004347 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00004348 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004349 }
4350 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4351 ExtAddrMode BackupAddrMode = AddrMode;
4352 unsigned OldSize = AddrModeInsts.size();
4353
4354 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004355 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004356 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004357 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004358 // to check here.
4359 if (MovedAway)
4360 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004361 // Okay, it's possible to fold this. Check to see if it is actually
4362 // *profitable* to do so. We use a simple cost model to avoid increasing
4363 // register pressure too much.
4364 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00004365 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004366 AddrModeInsts.push_back(I);
4367 return true;
4368 }
Stephen Lin837bba12013-07-15 17:55:02 +00004369
Chandler Carruthc8925912013-01-05 02:09:22 +00004370 // It isn't profitable to do this, roll back.
4371 //cerr << "NOT FOLDING: " << *I;
4372 AddrMode = BackupAddrMode;
4373 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004374 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004375 }
4376 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00004377 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00004378 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004379 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004380 } else if (isa<ConstantPointerNull>(Addr)) {
4381 // Null pointer gets folded without affecting the addressing mode.
4382 return true;
4383 }
4384
4385 // Worse case, the target should support [reg] addressing modes. :)
4386 if (!AddrMode.HasBaseReg) {
4387 AddrMode.HasBaseReg = true;
4388 AddrMode.BaseReg = Addr;
4389 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004390 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004391 return true;
4392 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00004393 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004394 }
4395
4396 // If the base register is already taken, see if we can do [r+r].
4397 if (AddrMode.Scale == 0) {
4398 AddrMode.Scale = 1;
4399 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004400 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004401 return true;
4402 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00004403 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004404 }
4405 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004406 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004407 return false;
4408}
4409
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004410/// Check to see if all uses of OpVal by the specified inline asm call are due
4411/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00004412static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004413 const TargetLowering &TLI,
4414 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00004415 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00004416 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004417 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004418 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004419
Chandler Carruthc8925912013-01-05 02:09:22 +00004420 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4421 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00004422
Chandler Carruthc8925912013-01-05 02:09:22 +00004423 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004424 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00004425
4426 // If this asm operand is our Value*, and if it isn't an indirect memory
4427 // operand, we can't fold it!
4428 if (OpInfo.CallOperandVal == OpVal &&
4429 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4430 !OpInfo.isIndirect))
4431 return false;
4432 }
4433
4434 return true;
4435}
4436
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004437// Max number of memory uses to look at before aborting the search to conserve
4438// compile time.
4439static constexpr int MaxMemoryUsesToScan = 20;
4440
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004441/// Recursively walk all the uses of I until we find a memory use.
4442/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00004443/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00004444static bool FindAllMemoryUses(
4445 Instruction *I,
4446 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004447 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4448 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004449 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00004450 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00004451 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004452
Chandler Carruthc8925912013-01-05 02:09:22 +00004453 // If this is an obviously unfoldable instruction, bail out.
4454 if (!MightBeFoldableInst(I))
4455 return true;
4456
Evandro Menezes85bd3972019-04-04 22:40:06 +00004457 const bool OptSize = I->getFunction()->hasOptSize();
Philip Reamesac115ed2016-03-09 23:13:12 +00004458
Chandler Carruthc8925912013-01-05 02:09:22 +00004459 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004460 for (Use &U : I->uses()) {
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004461 // Conservatively return true if we're seeing a large number or a deep chain
4462 // of users. This avoids excessive compilation times in pathological cases.
4463 if (SeenInsts++ >= MaxMemoryUsesToScan)
4464 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004465
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004466 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthcdf47882014-03-09 03:16:01 +00004467 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4468 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00004469 continue;
4470 }
Stephen Lin837bba12013-07-15 17:55:02 +00004471
Chandler Carruthcdf47882014-03-09 03:16:01 +00004472 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4473 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00004474 if (opNo != StoreInst::getPointerOperandIndex())
4475 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00004476 MemoryUses.push_back(std::make_pair(SI, opNo));
4477 continue;
4478 }
Stephen Lin837bba12013-07-15 17:55:02 +00004479
Matt Arsenault02d915b2017-03-15 22:35:20 +00004480 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4481 unsigned opNo = U.getOperandNo();
4482 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4483 return true; // Storing addr, not into addr.
4484 MemoryUses.push_back(std::make_pair(RMW, opNo));
4485 continue;
4486 }
4487
4488 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4489 unsigned opNo = U.getOperandNo();
4490 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4491 return true; // Storing addr, not into addr.
4492 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4493 continue;
4494 }
4495
Chandler Carruthcdf47882014-03-09 03:16:01 +00004496 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004497 // If this is a cold call, we can sink the addressing calculation into
4498 // the cold path. See optimizeCallInst
4499 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4500 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004501
Chandler Carruthc8925912013-01-05 02:09:22 +00004502 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4503 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004504
Chandler Carruthc8925912013-01-05 02:09:22 +00004505 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004506 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004507 return true;
4508 continue;
4509 }
Stephen Lin837bba12013-07-15 17:55:02 +00004510
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004511 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4512 SeenInsts))
Chandler Carruthc8925912013-01-05 02:09:22 +00004513 return true;
4514 }
4515
4516 return false;
4517}
4518
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004519/// Return true if Val is already known to be live at the use site that we're
4520/// folding it into. If so, there is no cost to include it in the addressing
4521/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4522/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004523bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004524 Value *KnownLive2) {
4525 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004526 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004527 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004528
Chandler Carruthc8925912013-01-05 02:09:22 +00004529 // All values other than instructions and arguments (e.g. constants) are live.
4530 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004531
Chandler Carruthc8925912013-01-05 02:09:22 +00004532 // If Val is a constant sized alloca in the entry block, it is live, this is
4533 // true because it is just a reference to the stack/frame pointer, which is
4534 // live for the whole function.
4535 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4536 if (AI->isStaticAlloca())
4537 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004538
Chandler Carruthc8925912013-01-05 02:09:22 +00004539 // Check to see if this value is already used in the memory instruction's
4540 // block. If so, it's already live into the block at the very least, so we
4541 // can reasonably fold it.
4542 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4543}
4544
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004545/// It is possible for the addressing mode of the machine to fold the specified
4546/// instruction into a load or store that ultimately uses it.
4547/// However, the specified instruction has multiple uses.
4548/// Given this, it may actually increase register pressure to fold it
4549/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004550///
4551/// X = ...
4552/// Y = X+1
4553/// use(Y) -> nonload/store
4554/// Z = Y+1
4555/// load Z
4556///
4557/// In this case, Y has multiple uses, and can be folded into the load of Z
4558/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4559/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4560/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4561/// number of computations either.
4562///
4563/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4564/// X was live across 'load Z' for other reasons, we actually *would* want to
4565/// fold the addressing mode in the Z case. This would make Y die earlier.
4566bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004567isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004568 ExtAddrMode &AMAfter) {
4569 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004570
Chandler Carruthc8925912013-01-05 02:09:22 +00004571 // AMBefore is the addressing mode before this instruction was folded into it,
4572 // and AMAfter is the addressing mode after the instruction was folded. Get
4573 // the set of registers referenced by AMAfter and subtract out those
4574 // referenced by AMBefore: this is the set of values which folding in this
4575 // address extends the lifetime of.
4576 //
4577 // Note that there are only two potential values being referenced here,
4578 // BaseReg and ScaleReg (global addresses are always available, as are any
4579 // folded immediates).
4580 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004581
Chandler Carruthc8925912013-01-05 02:09:22 +00004582 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4583 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004584 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004585 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004586 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004587 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004588
4589 // If folding this instruction (and it's subexprs) didn't extend any live
4590 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004591 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004592 return true;
4593
Philip Reamesac115ed2016-03-09 23:13:12 +00004594 // If all uses of this instruction can have the address mode sunk into them,
4595 // we can remove the addressing mode and effectively trade one live register
4596 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004597 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004598 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4599 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004600 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004601 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004602
Chandler Carruthc8925912013-01-05 02:09:22 +00004603 // Now that we know that all uses of this instruction are part of a chain of
4604 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004605 // into a memory use, loop over each of these memory operation uses and see
4606 // if they could *actually* fold the instruction. The assumption is that
4607 // addressing modes are cheap and that duplicating the computation involved
4608 // many times is worthwhile, even on a fastpath. For sinking candidates
4609 // (i.e. cold call sites), this serves as a way to prevent excessive code
4610 // growth since most architectures have some reasonable small and fast way to
4611 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004612 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4613 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4614 Instruction *User = MemoryUses[i].first;
4615 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004616
Chandler Carruthc8925912013-01-05 02:09:22 +00004617 // Get the access type of this use. If the use isn't a pointer, we don't
4618 // know what it accesses.
4619 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004620 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4621 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004622 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004623 Type *AddressAccessTy = AddrTy->getElementType();
4624 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004625
Chandler Carruthc8925912013-01-05 02:09:22 +00004626 // Do a match against the root of this address, ignoring profitability. This
4627 // will tell us if the addressing mode for the memory operation will
4628 // *actually* cover the shared instruction.
4629 ExtAddrMode Result;
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004630 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4631 0);
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004632 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4633 TPT.getRestorationPoint();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004634 AddressingModeMatcher Matcher(
4635 MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result,
4636 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Chandler Carruthc8925912013-01-05 02:09:22 +00004637 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004638 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004639 (void)Success; assert(Success && "Couldn't select *anything*?");
4640
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004641 // The match was to check the profitability, the changes made are not
4642 // part of the original matcher. Therefore, they should be dropped
4643 // otherwise the original matcher will not present the right state.
4644 TPT.rollback(LastKnownGood);
4645
Chandler Carruthc8925912013-01-05 02:09:22 +00004646 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004647 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004648 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004649
Chandler Carruthc8925912013-01-05 02:09:22 +00004650 MatchedAddrModeInsts.clear();
4651 }
Stephen Lin837bba12013-07-15 17:55:02 +00004652
Chandler Carruthc8925912013-01-05 02:09:22 +00004653 return true;
4654}
4655
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004656/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004657/// different basic block than BB.
4658static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4659 if (Instruction *I = dyn_cast<Instruction>(V))
4660 return I->getParent() != BB;
4661 return false;
4662}
4663
Philip Reamesac115ed2016-03-09 23:13:12 +00004664/// Sink addressing mode computation immediate before MemoryInst if doing so
4665/// can be done without increasing register pressure. The need for the
4666/// register pressure constraint means this can end up being an all or nothing
4667/// decision for all uses of the same addressing computation.
4668///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004669/// Load and Store Instructions often have addressing modes that can do
4670/// significant amounts of computation. As such, instruction selection will try
4671/// to get the load or store to do as much computation as possible for the
4672/// program. The problem is that isel can only see within a single block. As
4673/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004674///
4675/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004676/// operands. It's also used to sink addressing computations feeding into cold
4677/// call sites into their (cold) basic block.
4678///
4679/// The motivation for handling sinking into cold blocks is that doing so can
4680/// both enable other address mode sinking (by satisfying the register pressure
4681/// constraint above), and reduce register pressure globally (by removing the
4682/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004683bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004684 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004685 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004686
4687 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004688 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004689 SmallVector<Value*, 8> worklist;
4690 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004691 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004692
John Brawneb83c752017-10-03 13:04:15 +00004693 // Use a worklist to iteratively look through PHI and select nodes, and
4694 // ensure that the addressing mode obtained from the non-PHI/select roots of
John Brawn736bf002017-10-03 13:08:22 +00004695 // the graph are compatible.
John Brawneb83c752017-10-03 13:04:15 +00004696 bool PhiOrSelectSeen = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004697 SmallVector<Instruction*, 16> AddrModeInsts;
Serguei Katkovaee63752017-11-05 07:59:02 +00004698 const SimplifyQuery SQ(*DL, TLInfo);
Serguei Katkov2673f172018-11-29 06:45:18 +00004699 AddressingModeCombiner AddrModes(SQ, Addr);
Jun Bum Limdee55652017-04-03 19:20:07 +00004700 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004701 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4702 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004703 while (!worklist.empty()) {
4704 Value *V = worklist.back();
4705 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004706
Serguei Katkov4ea855e2017-07-19 04:49:17 +00004707 // We allow traversing cyclic Phi nodes.
4708 // In case of success after this loop we ensure that traversing through
4709 // Phi nodes ends up with all cases to compute address of the form
4710 // BaseGV + Base + Scale * Index + Offset
4711 // where Scale and Offset are constans and BaseGV, Base and Index
4712 // are exactly the same Values in all cases.
4713 // It means that BaseGV, Scale and Offset dominate our memory instruction
4714 // and have the same value as they had in address computation represented
4715 // as Phi. So we can safely sink address computation to memory instruction.
4716 if (!Visited.insert(V).second)
4717 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00004718
Owen Anderson8ba5f392010-11-27 08:15:55 +00004719 // For a PHI node, push all of its incoming values.
4720 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004721 for (Value *IncValue : P->incoming_values())
4722 worklist.push_back(IncValue);
John Brawneb83c752017-10-03 13:04:15 +00004723 PhiOrSelectSeen = true;
4724 continue;
4725 }
4726 // Similar for select.
4727 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4728 worklist.push_back(SI->getFalseValue());
4729 worklist.push_back(SI->getTrueValue());
4730 PhiOrSelectSeen = true;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004731 continue;
4732 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004733
Philip Reamesac115ed2016-03-09 23:13:12 +00004734 // For non-PHIs, determine the addressing mode being computed. Note that
4735 // the result may differ depending on what other uses our candidate
4736 // addressing instructions might have.
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004737 AddrModeInsts.clear();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004738 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4739 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004740 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004741 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004742 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004743
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004744 GetElementPtrInst *GEP = LargeOffsetGEP.first;
4745 if (GEP && GEP->getParent() != MemoryInst->getParent() &&
4746 !NewGEPBases.count(GEP)) {
4747 // If splitting the underlying data structure can reduce the offset of a
4748 // GEP, collect the GEP. Skip the GEPs that are the new bases of
4749 // previously split data structures.
4750 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
4751 if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
4752 LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
4753 }
4754
4755 NewAddrMode.OriginalValue = V;
John Brawn736bf002017-10-03 13:08:22 +00004756 if (!AddrModes.addNewAddrMode(NewAddrMode))
4757 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004758 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004759
John Brawn736bf002017-10-03 13:08:22 +00004760 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4761 // or we have multiple but either couldn't combine them or combining them
4762 // wouldn't do anything useful, bail out now.
4763 if (!AddrModes.combineAddrModes()) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004764 TPT.rollback(LastKnownGood);
4765 return false;
4766 }
4767 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004768
John Brawn736bf002017-10-03 13:08:22 +00004769 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4770 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4771
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004772 // If all the instructions matched are already in this BB, don't do anything.
John Brawneb83c752017-10-03 13:04:15 +00004773 // If we saw a Phi node then it is not local definitely, and if we saw a select
4774 // then we want to push the address calculation past it even if it's already
4775 // in this BB.
4776 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
Justin Lebar838c7f52016-11-21 22:49:11 +00004777 return IsNonLocalValue(V, MemoryInst->getParent());
Serguei Katkov0b7b59a2017-07-11 06:24:44 +00004778 })) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004779 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
4780 << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004781 return false;
4782 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004783
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004784 // Insert this computation right after this user. Since our caller is
4785 // scanning from the top of the BB to the bottom, reuse of the expr are
4786 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004787 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004788
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004789 // Now that we determined the addressing expression we want to use and know
4790 // that we have to sink it into this block. Check to see if we have already
Simon Dardis230f4532017-11-24 16:45:28 +00004791 // done this for some other load/store instr in this block. If so, reuse
4792 // the computation. Before attempting reuse, check if the address is valid
4793 // as it may have been erased.
4794
4795 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
4796
4797 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004798 if (SunkAddr) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004799 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
4800 << " for " << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004801 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004802 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004803 } else if (AddrSinkUsingGEPs ||
David Blaikie8ad9a972018-03-28 22:28:50 +00004804 (!AddrSinkUsingGEPs.getNumOccurrences() && TM && TTI->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004805 // By default, we use the GEP-based method when AA is used later. This
4806 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004807 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4808 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004809 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004810 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004811
4812 // First, find the pointer.
4813 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4814 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004815 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004816 }
4817
4818 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4819 // We can't add more than one pointer together, nor can we scale a
4820 // pointer (both of which seem meaningless).
4821 if (ResultPtr || AddrMode.Scale != 1)
4822 return false;
4823
4824 ResultPtr = AddrMode.ScaledReg;
4825 AddrMode.Scale = 0;
4826 }
4827
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004828 // It is only safe to sign extend the BaseReg if we know that the math
4829 // required to create it did not overflow before we extend it. Since
4830 // the original IR value was tossed in favor of a constant back when
4831 // the AddrMode was created we need to bail out gracefully if widths
4832 // do not match instead of extending it.
4833 //
4834 // (See below for code to add the scale.)
4835 if (AddrMode.Scale) {
4836 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4837 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4838 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4839 return false;
4840 }
4841
Hal Finkelc3998302014-04-12 00:59:48 +00004842 if (AddrMode.BaseGV) {
4843 if (ResultPtr)
4844 return false;
4845
4846 ResultPtr = AddrMode.BaseGV;
4847 }
4848
4849 // If the real base value actually came from an inttoptr, then the matcher
4850 // will look through it and provide only the integer value. In that case,
4851 // use it here.
Keno Fischer05e4ac22017-06-29 20:28:59 +00004852 if (!DL->isNonIntegralPointerType(Addr->getType())) {
4853 if (!ResultPtr && AddrMode.BaseReg) {
David L. Jonesd81f2302019-01-31 03:28:46 +00004854 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4855 "sunkaddr");
Keno Fischer05e4ac22017-06-29 20:28:59 +00004856 AddrMode.BaseReg = nullptr;
4857 } else if (!ResultPtr && AddrMode.Scale == 1) {
David L. Jonesd81f2302019-01-31 03:28:46 +00004858 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4859 "sunkaddr");
Keno Fischer05e4ac22017-06-29 20:28:59 +00004860 AddrMode.Scale = 0;
4861 }
Hal Finkelc3998302014-04-12 00:59:48 +00004862 }
4863
4864 if (!ResultPtr &&
4865 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4866 SunkAddr = Constant::getNullValue(Addr->getType());
4867 } else if (!ResultPtr) {
4868 return false;
4869 } else {
4870 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004871 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4872 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004873
4874 // Start with the base register. Do this first so that subsequent address
4875 // matching finds it last, which will prevent it from trying to match it
4876 // as the scaled value in case it happens to be a mul. That would be
4877 // problematic if we've sunk a different mul for the scale, because then
4878 // we'd end up sinking both muls.
4879 if (AddrMode.BaseReg) {
4880 Value *V = AddrMode.BaseReg;
4881 if (V->getType() != IntPtrTy)
4882 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4883
4884 ResultIndex = V;
4885 }
4886
4887 // Add the scale value.
4888 if (AddrMode.Scale) {
4889 Value *V = AddrMode.ScaledReg;
4890 if (V->getType() == IntPtrTy) {
4891 // done.
Hal Finkelc3998302014-04-12 00:59:48 +00004892 } else {
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004893 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4894 cast<IntegerType>(V->getType())->getBitWidth() &&
4895 "We can't transform if ScaledReg is too narrow");
4896 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004897 }
4898
4899 if (AddrMode.Scale != 1)
4900 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4901 "sunkaddr");
4902 if (ResultIndex)
4903 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4904 else
4905 ResultIndex = V;
4906 }
4907
4908 // Add in the Base Offset if present.
4909 if (AddrMode.BaseOffs) {
4910 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4911 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004912 // We need to add this separately from the scale above to help with
4913 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004914 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004915 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
Tim Northover8935aca2019-03-12 15:22:23 +00004916 ResultPtr =
4917 AddrMode.InBounds
4918 ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex,
4919 "sunkaddr")
4920 : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004921 }
4922
4923 ResultIndex = V;
4924 }
4925
4926 if (!ResultIndex) {
4927 SunkAddr = ResultPtr;
4928 } else {
4929 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004930 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
Tim Northover8935aca2019-03-12 15:22:23 +00004931 SunkAddr =
4932 AddrMode.InBounds
4933 ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex,
4934 "sunkaddr")
4935 : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004936 }
4937
4938 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004939 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004940 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004941 } else {
Keno Fischer05e4ac22017-06-29 20:28:59 +00004942 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4943 // non-integral pointers, so in that case bail out now.
4944 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4945 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4946 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4947 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4948 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4949 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4950 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4951 (AddrMode.BaseGV &&
4952 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4953 return false;
4954
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004955 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4956 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004957 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004958 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004959
4960 // Start with the base register. Do this first so that subsequent address
4961 // matching finds it last, which will prevent it from trying to match it
4962 // as the scaled value in case it happens to be a mul. That would be
4963 // problematic if we've sunk a different mul for the scale, because then
4964 // we'd end up sinking both muls.
4965 if (AddrMode.BaseReg) {
4966 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004967 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004968 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004969 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004970 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004971 Result = V;
4972 }
4973
4974 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004975 if (AddrMode.Scale) {
4976 Value *V = AddrMode.ScaledReg;
4977 if (V->getType() == IntPtrTy) {
4978 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004979 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004980 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004981 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4982 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004983 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004984 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004985 // It is only safe to sign extend the BaseReg if we know that the math
4986 // required to create it did not overflow before we extend it. Since
4987 // the original IR value was tossed in favor of a constant back when
4988 // the AddrMode was created we need to bail out gracefully if widths
4989 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004990 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004991 if (I && (Result != AddrMode.BaseReg))
4992 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004993 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004994 }
4995 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004996 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4997 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004998 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004999 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005000 else
5001 Result = V;
5002 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00005003
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005004 // Add in the BaseGV if present.
5005 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00005006 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005007 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00005008 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005009 else
5010 Result = V;
5011 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00005012
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005013 // Add in the Base Offset if present.
5014 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00005015 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005016 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00005017 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005018 else
5019 Result = V;
5020 }
5021
Craig Topperc0196b12014-04-14 00:51:57 +00005022 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00005023 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005024 else
Devang Patelc10e52a2011-09-06 18:49:53 +00005025 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005026 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00005027
Owen Andersondfb8c3b2010-11-19 22:15:03 +00005028 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Simon Dardis230f4532017-11-24 16:45:28 +00005029 // Store the newly computed address into the cache. In the case we reused a
5030 // value, this should be idempotent.
5031 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00005032
Chris Lattneraf1bcce2011-04-09 07:05:44 +00005033 // If we have no uses, recursively delete the value and all dead instructions
5034 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00005035 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00005036 // This can cause recursive deletion, which can invalidate our iterator.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00005037 // Use a WeakTrackingVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00005038 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00005039 WeakTrackingVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00005040 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00005041
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00005042 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00005043
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00005044 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00005045 // If the iterator instruction was recursively deleted, start over at the
5046 // start of the block.
5047 CurInstIterator = BB->begin();
5048 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00005049 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00005050 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00005051 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00005052 return true;
5053}
5054
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005055/// If there are any memory operands, use OptimizeMemoryInst to sink their
5056/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005057bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00005058 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00005059
Eric Christopher11e4df72015-02-26 22:38:43 +00005060 const TargetRegisterInfo *TRI =
Sanjay Patel4137d512017-06-07 14:29:52 +00005061 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00005062 TargetLowering::AsmOperandInfoVector TargetConstraints =
5063 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00005064 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00005065 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5066 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00005067
Evan Cheng1da25002008-02-26 02:42:37 +00005068 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00005069 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00005070
Eli Friedman666bbe32008-02-26 18:37:49 +00005071 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5072 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00005073 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00005074 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00005075 } else if (OpInfo.Type == InlineAsm::isInput)
5076 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00005077 }
5078
5079 return MadeChange;
5080}
5081
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005082/// Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005083/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00005084static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
5085 assert(!Val->use_empty() && "Input must have at least one use");
5086 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005087 bool IsSExt = isa<SExtInst>(FirstUser);
5088 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00005089 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005090 const Instruction *UI = cast<Instruction>(U);
5091 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
5092 return false;
5093 Type *CurTy = UI->getType();
5094 // Same input and output types: Same instruction after CSE.
5095 if (CurTy == ExtTy)
5096 continue;
5097
5098 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00005099 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005100 // b = sext ty1 a to ty2
5101 // c = sext ty1 a to ty3
5102 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00005103 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005104 // b = sext ty1 a to ty2
5105 // c = sext ty2 b to ty3
5106 // However, the last sext is not free.
5107 if (IsSExt)
5108 return false;
5109
5110 // This is a ZExt, maybe this is free to extend from one type to another.
5111 // In that case, we would not account for a different use.
5112 Type *NarrowTy;
5113 Type *LargeTy;
5114 if (ExtTy->getScalarType()->getIntegerBitWidth() >
5115 CurTy->getScalarType()->getIntegerBitWidth()) {
5116 NarrowTy = CurTy;
5117 LargeTy = ExtTy;
5118 } else {
5119 NarrowTy = ExtTy;
5120 LargeTy = CurTy;
5121 }
5122
5123 if (!TLI.isZExtFree(NarrowTy, LargeTy))
5124 return false;
5125 }
5126 // All uses are the same or can be derived from one another for free.
5127 return true;
5128}
5129
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005130/// Try to speculatively promote extensions in \p Exts and continue
Jun Bum Lim42301012017-03-17 19:05:21 +00005131/// promoting through newly promoted operands recursively as far as doing so is
5132/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
5133/// When some promotion happened, \p TPT contains the proper state to revert
5134/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005135///
Jun Bum Lim42301012017-03-17 19:05:21 +00005136/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00005137bool CodeGenPrepare::tryToPromoteExts(
5138 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
5139 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
5140 unsigned CreatedInstsCost) {
5141 bool Promoted = false;
5142
5143 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005144 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00005145 // Early check if we directly have ext(load).
5146 if (isa<LoadInst>(I->getOperand(0))) {
5147 ProfitablyMovedExts.push_back(I);
5148 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005149 }
Jun Bum Lim42301012017-03-17 19:05:21 +00005150
5151 // Check whether or not we want to do any promotion. The reason we have
5152 // this check inside the for loop is to catch the case where an extension
5153 // is directly fed by a load because in such case the extension can be moved
5154 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005155 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00005156 return false;
5157
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005158 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00005159 TypePromotionHelper::Action TPH =
5160 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005161 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00005162 if (!TPH) {
5163 // Save the current extension as we cannot move up through its operand.
5164 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005165 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00005166 }
5167
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005168 // Save the current state.
5169 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5170 TPT.getRestorationPoint();
5171 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00005172 unsigned NewCreatedInstsCost = 0;
5173 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005174 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00005175 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
5176 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005177 assert(PromotedVal &&
5178 "TypePromotionHelper should have filtered out those cases");
5179
5180 // We would be able to merge only one extension in a load.
5181 // Therefore, if we have more than 1 new extension we heuristically
5182 // cut this search path, because it means we degrade the code quality.
5183 // With exactly 2, the transformation is neutral, because we will merge
5184 // one extension but leave one. However, we optimistically keep going,
5185 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00005186 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00005187 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00005188 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00005189 TotalCreatedInstsCost =
5190 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005191 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00005192 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00005193 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00005194 // This promotion is not profitable, rollback to the previous state, and
5195 // save the current extension in ProfitablyMovedExts as the latest
5196 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005197 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00005198 ProfitablyMovedExts.push_back(I);
5199 continue;
5200 }
5201 // Continue promoting NewExts as far as doing so is profitable.
5202 SmallVector<Instruction *, 2> NewlyMovedExts;
5203 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
5204 bool NewPromoted = false;
5205 for (auto ExtInst : NewlyMovedExts) {
5206 Instruction *MovedExt = cast<Instruction>(ExtInst);
5207 Value *ExtOperand = MovedExt->getOperand(0);
5208 // If we have reached to a load, we need this extra profitability check
5209 // as it could potentially be merged into an ext(load).
5210 if (isa<LoadInst>(ExtOperand) &&
5211 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
5212 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
5213 continue;
5214
5215 ProfitablyMovedExts.push_back(MovedExt);
5216 NewPromoted = true;
5217 }
5218
5219 // If none of speculative promotions for NewExts is profitable, rollback
5220 // and save the current extension (I) as the last profitable extension.
5221 if (!NewPromoted) {
5222 TPT.rollback(LastKnownGood);
5223 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005224 continue;
5225 }
5226 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00005227 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005228 }
Jun Bum Lim42301012017-03-17 19:05:21 +00005229 return Promoted;
5230}
5231
Jun Bum Limdee55652017-04-03 19:20:07 +00005232/// Merging redundant sexts when one is dominating the other.
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00005233bool CodeGenPrepare::mergeSExts(Function &F) {
Jun Bum Limdee55652017-04-03 19:20:07 +00005234 bool Changed = false;
5235 for (auto &Entry : ValToSExtendedUses) {
5236 SExts &Insts = Entry.second;
5237 SExts CurPts;
5238 for (Instruction *Inst : Insts) {
5239 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
5240 Inst->getOperand(0) != Entry.first)
5241 continue;
5242 bool inserted = false;
5243 for (auto &Pt : CurPts) {
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00005244 if (getDT(F).dominates(Inst, Pt)) {
Jun Bum Limdee55652017-04-03 19:20:07 +00005245 Pt->replaceAllUsesWith(Inst);
5246 RemovedInsts.insert(Pt);
5247 Pt->removeFromParent();
5248 Pt = Inst;
5249 inserted = true;
5250 Changed = true;
5251 break;
5252 }
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00005253 if (!getDT(F).dominates(Pt, Inst))
Jun Bum Limdee55652017-04-03 19:20:07 +00005254 // Give up if we need to merge in a common dominator as the
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00005255 // experiments show it is not profitable.
Jun Bum Limdee55652017-04-03 19:20:07 +00005256 continue;
5257 Inst->replaceAllUsesWith(Pt);
5258 RemovedInsts.insert(Inst);
5259 Inst->removeFromParent();
5260 inserted = true;
5261 Changed = true;
5262 break;
5263 }
5264 if (!inserted)
5265 CurPts.push_back(Inst);
5266 }
5267 }
5268 return Changed;
5269}
5270
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005271// Spliting large data structures so that the GEPs accessing them can have
5272// smaller offsets so that they can be sunk to the same blocks as their users.
5273// For example, a large struct starting from %base is splitted into two parts
5274// where the second part starts from %new_base.
5275//
5276// Before:
5277// BB0:
5278// %base =
5279//
5280// BB1:
5281// %gep0 = gep %base, off0
5282// %gep1 = gep %base, off1
5283// %gep2 = gep %base, off2
5284//
5285// BB2:
5286// %load1 = load %gep0
5287// %load2 = load %gep1
5288// %load3 = load %gep2
5289//
5290// After:
5291// BB0:
5292// %base =
5293// %new_base = gep %base, off0
5294//
5295// BB1:
5296// %new_gep0 = %new_base
5297// %new_gep1 = gep %new_base, off1 - off0
5298// %new_gep2 = gep %new_base, off2 - off0
5299//
5300// BB2:
5301// %load1 = load i32, i32* %new_gep0
5302// %load2 = load i32, i32* %new_gep1
5303// %load3 = load i32, i32* %new_gep2
5304//
5305// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
5306// their offsets are smaller enough to fit into the addressing mode.
5307bool CodeGenPrepare::splitLargeGEPOffsets() {
5308 bool Changed = false;
5309 for (auto &Entry : LargeOffsetGEPMap) {
5310 Value *OldBase = Entry.first;
5311 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
5312 &LargeOffsetGEPs = Entry.second;
5313 auto compareGEPOffset =
5314 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
5315 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
5316 if (LHS.first == RHS.first)
5317 return false;
5318 if (LHS.second != RHS.second)
5319 return LHS.second < RHS.second;
5320 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
5321 };
5322 // Sorting all the GEPs of the same data structures based on the offsets.
Fangrui Song0cac7262018-09-27 02:13:45 +00005323 llvm::sort(LargeOffsetGEPs, compareGEPOffset);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005324 LargeOffsetGEPs.erase(
5325 std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()),
5326 LargeOffsetGEPs.end());
5327 // Skip if all the GEPs have the same offsets.
5328 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
5329 continue;
5330 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
5331 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
5332 Value *NewBaseGEP = nullptr;
5333
5334 auto LargeOffsetGEP = LargeOffsetGEPs.begin();
5335 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
5336 GetElementPtrInst *GEP = LargeOffsetGEP->first;
5337 int64_t Offset = LargeOffsetGEP->second;
5338 if (Offset != BaseOffset) {
5339 TargetLowering::AddrMode AddrMode;
5340 AddrMode.BaseOffs = Offset - BaseOffset;
5341 // The result type of the GEP might not be the type of the memory
5342 // access.
5343 if (!TLI->isLegalAddressingMode(*DL, AddrMode,
5344 GEP->getResultElementType(),
5345 GEP->getAddressSpace())) {
5346 // We need to create a new base if the offset to the current base is
5347 // too large to fit into the addressing mode. So, a very large struct
5348 // may be splitted into several parts.
5349 BaseGEP = GEP;
5350 BaseOffset = Offset;
5351 NewBaseGEP = nullptr;
5352 }
5353 }
5354
5355 // Generate a new GEP to replace the current one.
Eli Friedmana69084f2018-12-19 22:52:04 +00005356 LLVMContext &Ctx = GEP->getContext();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005357 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
5358 Type *I8PtrTy =
Eli Friedmana69084f2018-12-19 22:52:04 +00005359 Type::getInt8PtrTy(Ctx, GEP->getType()->getPointerAddressSpace());
5360 Type *I8Ty = Type::getInt8Ty(Ctx);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005361
5362 if (!NewBaseGEP) {
5363 // Create a new base if we don't have one yet. Find the insertion
5364 // pointer for the new base first.
5365 BasicBlock::iterator NewBaseInsertPt;
5366 BasicBlock *NewBaseInsertBB;
5367 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
5368 // If the base of the struct is an instruction, the new base will be
5369 // inserted close to it.
5370 NewBaseInsertBB = BaseI->getParent();
5371 if (isa<PHINode>(BaseI))
5372 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5373 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
5374 NewBaseInsertBB =
5375 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
5376 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5377 } else
5378 NewBaseInsertPt = std::next(BaseI->getIterator());
5379 } else {
5380 // If the current base is an argument or global value, the new base
5381 // will be inserted to the entry block.
5382 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
5383 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5384 }
5385 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
5386 // Create a new base.
5387 Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset);
5388 NewBaseGEP = OldBase;
5389 if (NewBaseGEP->getType() != I8PtrTy)
5390 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
5391 NewBaseGEP =
5392 NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep");
5393 NewGEPBases.insert(NewBaseGEP);
5394 }
5395
Eli Friedmana69084f2018-12-19 22:52:04 +00005396 IRBuilder<> Builder(GEP);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005397 Value *NewGEP = NewBaseGEP;
5398 if (Offset == BaseOffset) {
5399 if (GEP->getType() != I8PtrTy)
5400 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5401 } else {
5402 // Calculate the new offset for the new GEP.
5403 Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset);
5404 NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index);
5405
5406 if (GEP->getType() != I8PtrTy)
5407 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5408 }
5409 GEP->replaceAllUsesWith(NewGEP);
5410 LargeOffsetGEPID.erase(GEP);
5411 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
5412 GEP->eraseFromParent();
5413 Changed = true;
5414 }
5415 }
5416 return Changed;
5417}
5418
Jun Bum Lim42301012017-03-17 19:05:21 +00005419/// Return true, if an ext(load) can be formed from an extension in
5420/// \p MovedExts.
5421bool CodeGenPrepare::canFormExtLd(
5422 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
5423 Instruction *&Inst, bool HasPromoted) {
5424 for (auto *MovedExtInst : MovedExts) {
5425 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
5426 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
5427 Inst = MovedExtInst;
5428 break;
5429 }
5430 }
5431 if (!LI)
5432 return false;
5433
5434 // If they're already in the same block, there's nothing to do.
5435 // Make the cheap checks first if we did not promote.
5436 // If we promoted, we need to check if it is indeed profitable.
5437 if (!HasPromoted && LI->getParent() == Inst->getParent())
5438 return false;
5439
Haicheng Wuabdef9e2017-07-15 02:12:16 +00005440 return TLI->isExtLoad(LI, Inst, *DL);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005441}
5442
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005443/// Move a zext or sext fed by a load into the same basic block as the load,
5444/// unless conditions are unfavorable. This allows SelectionDAG to fold the
5445/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00005446///
Jun Bum Limdee55652017-04-03 19:20:07 +00005447/// E.g.,
5448/// \code
5449/// %ld = load i32* %addr
5450/// %add = add nuw i32 %ld, 4
5451/// %zext = zext i32 %add to i64
5452// \endcode
5453/// =>
5454/// \code
5455/// %ld = load i32* %addr
5456/// %zext = zext i32 %ld to i64
5457/// %add = add nuw i64 %zext, 4
5458/// \encode
5459/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
5460/// allow us to match zext(load i32*) to i64.
5461///
5462/// Also, try to promote the computations used to obtain a sign extended
5463/// value used into memory accesses.
5464/// E.g.,
5465/// \code
5466/// a = add nsw i32 b, 3
5467/// d = sext i32 a to i64
5468/// e = getelementptr ..., i64 d
5469/// \endcode
5470/// =>
5471/// \code
5472/// f = sext i32 b to i64
5473/// a = add nsw i64 f, 3
5474/// e = getelementptr ..., i64 a
5475/// \endcode
5476///
5477/// \p Inst[in/out] the extension may be modified during the process if some
5478/// promotions apply.
5479bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
5480 // ExtLoad formation and address type promotion infrastructure requires TLI to
5481 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00005482 if (!TLI)
5483 return false;
5484
Jun Bum Limdee55652017-04-03 19:20:07 +00005485 bool AllowPromotionWithoutCommonHeader = false;
5486 /// See if it is an interesting sext operations for the address type
5487 /// promotion before trying to promote it, e.g., the ones with the right
5488 /// type and used in memory accesses.
5489 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
5490 *Inst, AllowPromotionWithoutCommonHeader);
5491 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005492 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00005493 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005494 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00005495 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
5496 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00005497
Jun Bum Limdee55652017-04-03 19:20:07 +00005498 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00005499
Dan Gohman99429a02009-10-16 20:59:35 +00005500 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005501 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00005502 Instruction *ExtFedByLoad;
5503
5504 // Try to promote a chain of computation if it allows to form an extended
5505 // load.
5506 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
5507 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
5508 TPT.commit();
5509 // Move the extend into the same block as the load
Sanjay Patel674d2c22017-08-29 14:07:48 +00005510 ExtFedByLoad->moveAfter(LI);
Jun Bum Limdee55652017-04-03 19:20:07 +00005511 // CGP does not check if the zext would be speculatively executed when moved
5512 // to the same basic block as the load. Preserving its original location
5513 // would pessimize the debugging experience, as well as negatively impact
5514 // the quality of sample pgo. We don't want to use "line 0" as that has a
5515 // size cost in the line-table section and logically the zext can be seen as
5516 // part of the load. Therefore we conservatively reuse the same debug
5517 // location for the load and the zext.
5518 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
5519 ++NumExtsMoved;
5520 Inst = ExtFedByLoad;
5521 return true;
5522 }
5523
5524 // Continue promoting SExts if known as considerable depending on targets.
5525 if (ATPConsiderable &&
5526 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
5527 HasPromoted, TPT, SpeculativelyMovedExts))
5528 return true;
5529
5530 TPT.rollback(LastKnownGood);
5531 return false;
5532}
5533
5534// Perform address type promotion if doing so is profitable.
5535// If AllowPromotionWithoutCommonHeader == false, we should find other sext
5536// instructions that sign extended the same initial value. However, if
5537// AllowPromotionWithoutCommonHeader == true, we expect promoting the
5538// extension is just profitable.
5539bool CodeGenPrepare::performAddressTypePromotion(
5540 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
5541 bool HasPromoted, TypePromotionTransaction &TPT,
5542 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
5543 bool Promoted = false;
5544 SmallPtrSet<Instruction *, 1> UnhandledExts;
5545 bool AllSeenFirst = true;
5546 for (auto I : SpeculativelyMovedExts) {
5547 Value *HeadOfChain = I->getOperand(0);
5548 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
5549 SeenChainsForSExt.find(HeadOfChain);
5550 // If there is an unhandled SExt which has the same header, try to promote
5551 // it as well.
5552 if (AlreadySeen != SeenChainsForSExt.end()) {
5553 if (AlreadySeen->second != nullptr)
5554 UnhandledExts.insert(AlreadySeen->second);
5555 AllSeenFirst = false;
5556 }
5557 }
5558
5559 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
5560 SpeculativelyMovedExts.size() == 1)) {
5561 TPT.commit();
5562 if (HasPromoted)
5563 Promoted = true;
5564 for (auto I : SpeculativelyMovedExts) {
5565 Value *HeadOfChain = I->getOperand(0);
5566 SeenChainsForSExt[HeadOfChain] = nullptr;
5567 ValToSExtendedUses[HeadOfChain].push_back(I);
5568 }
5569 // Update Inst as promotion happen.
5570 Inst = SpeculativelyMovedExts.pop_back_val();
5571 } else {
5572 // This is the first chain visited from the header, keep the current chain
5573 // as unhandled. Defer to promote this until we encounter another SExt
5574 // chain derived from the same header.
5575 for (auto I : SpeculativelyMovedExts) {
5576 Value *HeadOfChain = I->getOperand(0);
5577 SeenChainsForSExt[HeadOfChain] = Inst;
5578 }
Dan Gohman99429a02009-10-16 20:59:35 +00005579 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005580 }
Dan Gohman99429a02009-10-16 20:59:35 +00005581
Jun Bum Limdee55652017-04-03 19:20:07 +00005582 if (!AllSeenFirst && !UnhandledExts.empty())
5583 for (auto VisitedSExt : UnhandledExts) {
5584 if (RemovedInsts.count(VisitedSExt))
5585 continue;
5586 TypePromotionTransaction TPT(RemovedInsts);
5587 SmallVector<Instruction *, 1> Exts;
5588 SmallVector<Instruction *, 2> Chains;
5589 Exts.push_back(VisitedSExt);
5590 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
5591 TPT.commit();
5592 if (HasPromoted)
5593 Promoted = true;
5594 for (auto I : Chains) {
5595 Value *HeadOfChain = I->getOperand(0);
5596 // Mark this as handled.
5597 SeenChainsForSExt[HeadOfChain] = nullptr;
5598 ValToSExtendedUses[HeadOfChain].push_back(I);
5599 }
5600 }
5601 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00005602}
5603
Sanjay Patelfc580a62015-09-21 23:03:16 +00005604bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00005605 BasicBlock *DefBB = I->getParent();
5606
Bob Wilsonff714f92010-09-21 21:44:14 +00005607 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00005608 // other uses of the source with result of extension.
5609 Value *Src = I->getOperand(0);
5610 if (Src->hasOneUse())
5611 return false;
5612
Evan Cheng2011df42007-12-13 07:50:36 +00005613 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00005614 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00005615 return false;
5616
Evan Cheng7bc89422007-12-12 00:51:06 +00005617 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00005618 // this block.
5619 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00005620 return false;
5621
Evan Chengd3d80172007-12-05 23:58:20 +00005622 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005623 for (User *U : I->users()) {
5624 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00005625
5626 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005627 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00005628 if (UserBB == DefBB) continue;
5629 DefIsLiveOut = true;
5630 break;
5631 }
5632 if (!DefIsLiveOut)
5633 return false;
5634
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00005635 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005636 for (User *U : Src->users()) {
5637 Instruction *UI = cast<Instruction>(U);
5638 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00005639 if (UserBB == DefBB) continue;
5640 // Be conservative. We don't want this xform to end up introducing
5641 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005642 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00005643 return false;
5644 }
5645
Evan Chengd3d80172007-12-05 23:58:20 +00005646 // InsertedTruncs - Only insert one trunc in each block once.
5647 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5648
5649 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005650 for (Use &U : Src->uses()) {
5651 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00005652
5653 // Figure out which BB this ext is used in.
5654 BasicBlock *UserBB = User->getParent();
5655 if (UserBB == DefBB) continue;
5656
5657 // Both src and def are live in this block. Rewrite the use.
5658 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5659
5660 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00005661 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005662 assert(InsertPt != UserBB->end());
5663 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005664 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00005665 }
5666
5667 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005668 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00005669 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00005670 MadeChange = true;
5671 }
5672
5673 return MadeChange;
5674}
5675
Geoff Berry5256fca2015-11-20 22:34:39 +00005676// Find loads whose uses only use some of the loaded value's bits. Add an "and"
5677// just after the load if the target can fold this into one extload instruction,
5678// with the hope of eliminating some of the other later "and" instructions using
5679// the loaded value. "and"s that are made trivially redundant by the insertion
5680// of the new "and" are removed by this function, while others (e.g. those whose
5681// path from the load goes through a phi) are left for isel to potentially
5682// remove.
5683//
5684// For example:
5685//
5686// b0:
5687// x = load i32
5688// ...
5689// b1:
5690// y = and x, 0xff
5691// z = use y
5692//
5693// becomes:
5694//
5695// b0:
5696// x = load i32
5697// x' = and x, 0xff
5698// ...
5699// b1:
5700// z = use x'
5701//
5702// whereas:
5703//
5704// b0:
5705// x1 = load i32
5706// ...
5707// b1:
5708// x2 = load i32
5709// ...
5710// b2:
5711// x = phi x1, x2
5712// y = and x, 0xff
5713//
5714// becomes (after a call to optimizeLoadExt for each load):
5715//
5716// b0:
5717// x1 = load i32
5718// x1' = and x1, 0xff
5719// ...
5720// b1:
5721// x2 = load i32
5722// x2' = and x2, 0xff
5723// ...
5724// b2:
5725// x = phi x1', x2'
5726// y = and x, 0xff
Geoff Berry5256fca2015-11-20 22:34:39 +00005727bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
Vedant Kumarb3091da2018-07-06 20:17:42 +00005728 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
Geoff Berry5256fca2015-11-20 22:34:39 +00005729 return false;
5730
Geoff Berry5d534b62017-02-21 18:53:14 +00005731 // Skip loads we've already transformed.
5732 if (Load->hasOneUse() &&
5733 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5734 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005735
5736 // Look at all uses of Load, looking through phis, to determine how many bits
5737 // of the loaded value are needed.
5738 SmallVector<Instruction *, 8> WorkList;
5739 SmallPtrSet<Instruction *, 16> Visited;
5740 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5741 for (auto *U : Load->users())
5742 WorkList.push_back(cast<Instruction>(U));
5743
5744 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5745 unsigned BitWidth = LoadResultVT.getSizeInBits();
5746 APInt DemandBits(BitWidth, 0);
5747 APInt WidestAndBits(BitWidth, 0);
5748
5749 while (!WorkList.empty()) {
5750 Instruction *I = WorkList.back();
5751 WorkList.pop_back();
5752
5753 // Break use-def graph loops.
5754 if (!Visited.insert(I).second)
5755 continue;
5756
5757 // For a PHI node, push all of its users.
5758 if (auto *Phi = dyn_cast<PHINode>(I)) {
5759 for (auto *U : Phi->users())
5760 WorkList.push_back(cast<Instruction>(U));
5761 continue;
5762 }
5763
5764 switch (I->getOpcode()) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005765 case Instruction::And: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005766 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5767 if (!AndC)
5768 return false;
5769 APInt AndBits = AndC->getValue();
5770 DemandBits |= AndBits;
5771 // Keep track of the widest and mask we see.
5772 if (AndBits.ugt(WidestAndBits))
5773 WidestAndBits = AndBits;
5774 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5775 AndsToMaybeRemove.push_back(I);
5776 break;
5777 }
5778
Eugene Zelenko900b6332017-08-29 22:32:07 +00005779 case Instruction::Shl: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005780 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5781 if (!ShlC)
5782 return false;
5783 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00005784 DemandBits.setLowBits(BitWidth - ShiftAmt);
Geoff Berry5256fca2015-11-20 22:34:39 +00005785 break;
5786 }
5787
Eugene Zelenko900b6332017-08-29 22:32:07 +00005788 case Instruction::Trunc: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005789 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5790 unsigned TruncBitWidth = TruncVT.getSizeInBits();
Craig Topperfc947bc2017-04-18 17:14:21 +00005791 DemandBits.setLowBits(TruncBitWidth);
Geoff Berry5256fca2015-11-20 22:34:39 +00005792 break;
5793 }
5794
5795 default:
5796 return false;
5797 }
5798 }
5799
5800 uint32_t ActiveBits = DemandBits.getActiveBits();
5801 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5802 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5803 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5804 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5805 // followed by an AND.
5806 // TODO: Look into removing this restriction by fixing backends to either
5807 // return false for isLoadExtLegal for i1 or have them select this pattern to
5808 // a single instruction.
5809 //
5810 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5811 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005812 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005813 WidestAndBits != DemandBits)
5814 return false;
5815
5816 LLVMContext &Ctx = Load->getType()->getContext();
5817 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5818 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5819
5820 // Reject cases that won't be matched as extloads.
5821 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5822 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5823 return false;
5824
5825 IRBuilder<> Builder(Load->getNextNode());
5826 auto *NewAnd = dyn_cast<Instruction>(
5827 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005828 // Mark this instruction as "inserted by CGP", so that other
5829 // optimizations don't touch it.
5830 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005831
5832 // Replace all uses of load with new and (except for the use of load in the
5833 // new and itself).
5834 Load->replaceAllUsesWith(NewAnd);
5835 NewAnd->setOperand(0, Load);
5836
5837 // Remove any and instructions that are now redundant.
5838 for (auto *And : AndsToMaybeRemove)
5839 // Check that the and mask is the same as the one we decided to put on the
5840 // new and.
5841 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5842 And->replaceAllUsesWith(NewAnd);
5843 if (&*CurInstIterator == And)
5844 CurInstIterator = std::next(And->getIterator());
5845 And->eraseFromParent();
5846 ++NumAndUses;
5847 }
5848
5849 ++NumAndsAdded;
5850 return true;
5851}
5852
Sanjay Patel69a50a12015-10-19 21:59:12 +00005853/// Check if V (an operand of a select instruction) is an expensive instruction
5854/// that is only used once.
5855static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5856 auto *I = dyn_cast<Instruction>(V);
5857 // If it's safe to speculatively execute, then it should not have side
5858 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005859 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5860 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005861}
5862
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005863/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005864static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005865 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005866 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005867 // If even a predictable select is cheap, then a branch can't be cheaper.
5868 if (!TLI->isPredictableSelectExpensive())
5869 return false;
5870
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005871 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005872 // whether a select is better represented as a branch.
5873
5874 // If metadata tells us that the select condition is obviously predictable,
5875 // then we want to replace the select with a branch.
5876 uint64_t TrueWeight, FalseWeight;
5877 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5878 uint64_t Max = std::max(TrueWeight, FalseWeight);
5879 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005880 if (Sum != 0) {
5881 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5882 if (Probability > TLI->getPredictableBranchThreshold())
5883 return true;
5884 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005885 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005886
5887 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5888
Sanjay Patel4e652762015-09-28 22:14:51 +00005889 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5890 // comparison condition. If the compare has more than one use, there's
5891 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005892 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005893 return false;
5894
Sanjay Patel69a50a12015-10-19 21:59:12 +00005895 // If either operand of the select is expensive and only needed on one side
5896 // of the select, we should form a branch.
5897 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5898 sinkSelectOperand(TTI, SI->getFalseValue()))
5899 return true;
5900
5901 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005902}
5903
Dehao Chen9bbb9412016-09-12 20:23:28 +00005904/// If \p isTrue is true, return the true value of \p SI, otherwise return
5905/// false value of \p SI. If the true/false value of \p SI is defined by any
5906/// select instructions in \p Selects, look through the defining select
5907/// instruction until the true/false value is not defined in \p Selects.
5908static Value *getTrueOrFalseValue(
5909 SelectInst *SI, bool isTrue,
5910 const SmallPtrSet<const Instruction *, 2> &Selects) {
5911 Value *V;
5912
5913 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5914 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005915 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005916 "The condition of DefSI does not match with SI");
5917 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5918 }
5919 return V;
5920}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005921
Nadav Rotem9d832022012-09-02 12:10:19 +00005922/// If we have a SelectInst that will likely profit from branch prediction,
5923/// turn it into a branch.
Teresa Johnsonb7e21382019-03-27 18:44:25 +00005924bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Vedant Kumarfbc38732018-08-21 23:42:23 +00005925 // If branch conversion isn't desirable, exit early.
5926 if (DisableSelectToBranch || OptSize || !TLI)
5927 return false;
5928
Dehao Chen9bbb9412016-09-12 20:23:28 +00005929 // Find all consecutive select instructions that share the same condition.
5930 SmallVector<SelectInst *, 2> ASI;
5931 ASI.push_back(SI);
David Blaikie7d306532018-08-28 00:55:19 +00005932 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5933 It != SI->getParent()->end(); ++It) {
5934 SelectInst *I = dyn_cast<SelectInst>(&*It);
Dehao Chen9bbb9412016-09-12 20:23:28 +00005935 if (I && SI->getCondition() == I->getCondition()) {
5936 ASI.push_back(I);
5937 } else {
5938 break;
5939 }
5940 }
5941
5942 SelectInst *LastSI = ASI.back();
5943 // Increment the current iterator to skip all the rest of select instructions
5944 // because they will be either "not lowered" or "all lowered" to branch.
5945 CurInstIterator = std::next(LastSI->getIterator());
5946
Nadav Rotem9d832022012-09-02 12:10:19 +00005947 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5948
5949 // Can we convert the 'select' to CF ?
Vedant Kumarfbc38732018-08-21 23:42:23 +00005950 if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005951 return false;
5952
Nadav Rotem9d832022012-09-02 12:10:19 +00005953 TargetLowering::SelectSupportKind SelectKind;
5954 if (VectorCond)
5955 SelectKind = TargetLowering::VectorMaskSelect;
5956 else if (SI->getType()->isVectorTy())
5957 SelectKind = TargetLowering::ScalarCondVectorVal;
5958 else
5959 SelectKind = TargetLowering::ScalarValSelect;
5960
Sanjay Pateld66607b2016-04-26 17:11:17 +00005961 if (TLI->isSelectSupported(SelectKind) &&
5962 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5963 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005964
Teresa Johnsonb7e21382019-03-27 18:44:25 +00005965 // The DominatorTree needs to be rebuilt by any consumers after this
5966 // transformation. We simply reset here rather than setting the ModifiedDT
5967 // flag to avoid restarting the function walk in runOnFunction for each
5968 // select optimized.
5969 DT.reset();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005970
Sanjay Patel69a50a12015-10-19 21:59:12 +00005971 // Transform a sequence like this:
5972 // start:
5973 // %cmp = cmp uge i32 %a, %b
5974 // %sel = select i1 %cmp, i32 %c, i32 %d
5975 //
5976 // Into:
5977 // start:
5978 // %cmp = cmp uge i32 %a, %b
5979 // br i1 %cmp, label %select.true, label %select.false
5980 // select.true:
5981 // br label %select.end
5982 // select.false:
5983 // br label %select.end
5984 // select.end:
5985 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5986 //
5987 // In addition, we may sink instructions that produce %c or %d from
5988 // the entry block into the destination(s) of the new branch.
5989 // If the true or false blocks do not contain a sunken instruction, that
5990 // block and its branch may be optimized away. In that case, one side of the
5991 // first branch will point directly to select.end, and the corresponding PHI
5992 // predecessor block will be the start block.
5993
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005994 // First, we split the block containing the select into 2 blocks.
5995 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005996 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005997 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005998
Sanjay Patel69a50a12015-10-19 21:59:12 +00005999 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006000 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00006001
6002 // These are the new basic blocks for the conditional branch.
6003 // At least one will become an actual new basic block.
6004 BasicBlock *TrueBlock = nullptr;
6005 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00006006 BranchInst *TrueBranch = nullptr;
6007 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00006008
6009 // Sink expensive instructions into the conditional blocks to avoid executing
6010 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00006011 for (SelectInst *SI : ASI) {
6012 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
6013 if (TrueBlock == nullptr) {
6014 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
6015 EndBlock->getParent(), EndBlock);
6016 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00006017 TrueBranch->setDebugLoc(SI->getDebugLoc());
Dehao Chen9bbb9412016-09-12 20:23:28 +00006018 }
6019 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
6020 TrueInst->moveBefore(TrueBranch);
6021 }
6022 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
6023 if (FalseBlock == nullptr) {
6024 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
6025 EndBlock->getParent(), EndBlock);
6026 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00006027 FalseBranch->setDebugLoc(SI->getDebugLoc());
Dehao Chen9bbb9412016-09-12 20:23:28 +00006028 }
6029 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
6030 FalseInst->moveBefore(FalseBranch);
6031 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00006032 }
6033
6034 // If there was nothing to sink, then arbitrarily choose the 'false' side
6035 // for a new input value to the PHI.
6036 if (TrueBlock == FalseBlock) {
6037 assert(TrueBlock == nullptr &&
6038 "Unexpected basic block transform while optimizing select");
6039
6040 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
6041 EndBlock->getParent(), EndBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00006042 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
6043 FalseBranch->setDebugLoc(SI->getDebugLoc());
Sanjay Patel69a50a12015-10-19 21:59:12 +00006044 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006045
6046 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00006047 // If we did not create a new block for one of the 'true' or 'false' paths
6048 // of the condition, it means that side of the branch goes to the end block
6049 // directly and the path originates from the start block from the point of
6050 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00006051 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00006052 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00006053 TT = EndBlock;
6054 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00006055 TrueBlock = StartBlock;
6056 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00006057 TT = TrueBlock;
6058 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00006059 FalseBlock = StartBlock;
6060 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00006061 TT = TrueBlock;
6062 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00006063 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00006064 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006065
Dehao Chen9bbb9412016-09-12 20:23:28 +00006066 SmallPtrSet<const Instruction *, 2> INS;
6067 INS.insert(ASI.begin(), ASI.end());
6068 // Use reverse iterator because later select may use the value of the
6069 // earlier select, and we need to propagate value through earlier select
6070 // to get the PHI operand.
6071 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
6072 SelectInst *SI = *It;
6073 // The select itself is replaced with a PHI Node.
6074 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
6075 PN->takeName(SI);
6076 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
6077 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00006078 PN->setDebugLoc(SI->getDebugLoc());
Sanjay Patel69a50a12015-10-19 21:59:12 +00006079
Dehao Chen9bbb9412016-09-12 20:23:28 +00006080 SI->replaceAllUsesWith(PN);
6081 SI->eraseFromParent();
6082 INS.erase(SI);
6083 ++NumSelectsExpanded;
6084 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006085
6086 // Instruct OptimizeBlock to skip to the next block.
6087 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006088 return true;
6089}
6090
Benjamin Kramer573ff362014-03-01 17:24:40 +00006091static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00006092 SmallVector<int, 16> Mask(SVI->getShuffleMask());
6093 int SplatElem = -1;
6094 for (unsigned i = 0; i < Mask.size(); ++i) {
6095 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
6096 return false;
6097 SplatElem = Mask[i];
6098 }
6099
6100 return true;
6101}
6102
6103/// Some targets have expensive vector shifts if the lanes aren't all the same
6104/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
6105/// it's often worth sinking a shufflevector splat down to its use so that
6106/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006107bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00006108 BasicBlock *DefBB = SVI->getParent();
6109
6110 // Only do this xform if variable vector shifts are particularly expensive.
6111 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
6112 return false;
6113
6114 // We only expect better codegen by sinking a shuffle if we can recognise a
6115 // constant splat.
6116 if (!isBroadcastShuffle(SVI))
6117 return false;
6118
6119 // InsertedShuffles - Only insert a shuffle in each block once.
6120 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
6121
6122 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00006123 for (User *U : SVI->users()) {
6124 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006125
6126 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00006127 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00006128 if (UserBB == DefBB) continue;
6129
6130 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00006131 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00006132
6133 // Everything checks out, sink the shuffle if the user's block doesn't
6134 // already have a copy.
6135 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
6136
6137 if (!InsertedShuffle) {
6138 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006139 assert(InsertPt != UserBB->end());
6140 InsertedShuffle =
6141 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
6142 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006143 }
6144
Chandler Carruthcdf47882014-03-09 03:16:01 +00006145 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006146 MadeChange = true;
6147 }
6148
6149 // If we removed all uses, nuke the shuffle.
6150 if (SVI->use_empty()) {
6151 SVI->eraseFromParent();
6152 MadeChange = true;
6153 }
6154
6155 return MadeChange;
6156}
6157
Florian Hahn3b251962019-02-05 10:27:40 +00006158bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
6159 // If the operands of I can be folded into a target instruction together with
6160 // I, duplicate and sink them.
6161 SmallVector<Use *, 4> OpsToSink;
6162 if (!TLI || !TLI->shouldSinkOperands(I, OpsToSink))
6163 return false;
6164
6165 // OpsToSink can contain multiple uses in a use chain (e.g.
6166 // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating
6167 // uses must come first, which means they are sunk first, temporarily creating
6168 // invalid IR. This will be fixed once their dominated users are sunk and
6169 // updated.
6170 BasicBlock *TargetBB = I->getParent();
6171 bool Changed = false;
6172 SmallVector<Use *, 4> ToReplace;
6173 for (Use *U : OpsToSink) {
6174 auto *UI = cast<Instruction>(U->get());
6175 if (UI->getParent() == TargetBB || isa<PHINode>(UI))
6176 continue;
6177 ToReplace.push_back(U);
6178 }
6179
6180 SmallPtrSet<Instruction *, 4> MaybeDead;
6181 for (Use *U : ToReplace) {
6182 auto *UI = cast<Instruction>(U->get());
6183 Instruction *NI = UI->clone();
6184 MaybeDead.insert(UI);
6185 LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
6186 NI->insertBefore(I);
6187 InsertedInsts.insert(NI);
6188 U->set(NI);
6189 Changed = true;
6190 }
6191
6192 // Remove instructions that are dead after sinking.
6193 for (auto *I : MaybeDead)
6194 if (!I->hasNUsesOrMore(1))
6195 I->eraseFromParent();
6196
6197 return Changed;
6198}
6199
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006200bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
6201 if (!TLI || !DL)
6202 return false;
6203
6204 Value *Cond = SI->getCondition();
6205 Type *OldType = Cond->getType();
6206 LLVMContext &Context = Cond->getContext();
6207 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
6208 unsigned RegWidth = RegType.getSizeInBits();
6209
6210 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
6211 return false;
6212
6213 // If the register width is greater than the type width, expand the condition
6214 // of the switch instruction and each case constant to the width of the
6215 // register. By widening the type of the switch condition, subsequent
6216 // comparisons (for case comparisons) will not need to be extended to the
6217 // preferred register width, so we will potentially eliminate N-1 extends,
6218 // where N is the number of cases in the switch.
6219 auto *NewType = Type::getIntNTy(Context, RegWidth);
6220
6221 // Zero-extend the switch condition and case constants unless the switch
6222 // condition is a function argument that is already being sign-extended.
6223 // In that case, we can avoid an unnecessary mask/extension by sign-extending
6224 // everything instead.
6225 Instruction::CastOps ExtType = Instruction::ZExt;
6226 if (auto *Arg = dyn_cast<Argument>(Cond))
6227 if (Arg->hasSExtAttr())
6228 ExtType = Instruction::SExt;
6229
6230 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
6231 ExtInst->insertBefore(SI);
Vedant Kumar47606862018-08-22 01:23:31 +00006232 ExtInst->setDebugLoc(SI->getDebugLoc());
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006233 SI->setCondition(ExtInst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00006234 for (auto Case : SI->cases()) {
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006235 APInt NarrowConst = Case.getCaseValue()->getValue();
6236 APInt WideConst = (ExtType == Instruction::ZExt) ?
6237 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
6238 Case.setValue(ConstantInt::get(Context, WideConst));
6239 }
6240
6241 return true;
6242}
6243
Zaara Syeda3a7578c2017-05-31 17:12:38 +00006244
Quentin Colombetc32615d2014-10-31 17:52:53 +00006245namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006246
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006247/// Helper class to promote a scalar operation to a vector one.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006248/// This class is used to move downward extractelement transition.
6249/// E.g.,
6250/// a = vector_op <2 x i32>
6251/// b = extractelement <2 x i32> a, i32 0
6252/// c = scalar_op b
6253/// store c
6254///
6255/// =>
6256/// a = vector_op <2 x i32>
6257/// c = vector_op a (equivalent to scalar_op on the related lane)
6258/// * d = extractelement <2 x i32> c, i32 0
6259/// * store d
6260/// Assuming both extractelement and store can be combine, we get rid of the
6261/// transition.
6262class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00006263 /// DataLayout associated with the current module.
6264 const DataLayout &DL;
6265
Quentin Colombetc32615d2014-10-31 17:52:53 +00006266 /// Used to perform some checks on the legality of vector operations.
6267 const TargetLowering &TLI;
6268
6269 /// Used to estimated the cost of the promoted chain.
6270 const TargetTransformInfo &TTI;
6271
6272 /// The transition being moved downwards.
6273 Instruction *Transition;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006274
Quentin Colombetc32615d2014-10-31 17:52:53 +00006275 /// The sequence of instructions to be promoted.
6276 SmallVector<Instruction *, 4> InstsToBePromoted;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006277
Quentin Colombetc32615d2014-10-31 17:52:53 +00006278 /// Cost of combining a store and an extract.
6279 unsigned StoreExtractCombineCost;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006280
Quentin Colombetc32615d2014-10-31 17:52:53 +00006281 /// Instruction that will be combined with the transition.
Eugene Zelenko900b6332017-08-29 22:32:07 +00006282 Instruction *CombineInst = nullptr;
Quentin Colombetc32615d2014-10-31 17:52:53 +00006283
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006284 /// The instruction that represents the current end of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006285 /// Since we are faking the promotion until we reach the end of the chain
6286 /// of computation, we need a way to get the current end of the transition.
6287 Instruction *getEndOfTransition() const {
6288 if (InstsToBePromoted.empty())
6289 return Transition;
6290 return InstsToBePromoted.back();
6291 }
6292
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006293 /// Return the index of the original value in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006294 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
6295 /// c, is at index 0.
6296 unsigned getTransitionOriginalValueIdx() const {
6297 assert(isa<ExtractElementInst>(Transition) &&
6298 "Other kind of transitions are not supported yet");
6299 return 0;
6300 }
6301
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006302 /// Return the index of the index in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006303 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
6304 /// is at index 1.
6305 unsigned getTransitionIdx() const {
6306 assert(isa<ExtractElementInst>(Transition) &&
6307 "Other kind of transitions are not supported yet");
6308 return 1;
6309 }
6310
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006311 /// Get the type of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006312 /// This is the type of the original value.
6313 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
6314 /// transition is <2 x i32>.
6315 Type *getTransitionType() const {
6316 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
6317 }
6318
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006319 /// Promote \p ToBePromoted by moving \p Def downward through.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006320 /// I.e., we have the following sequence:
6321 /// Def = Transition <ty1> a to <ty2>
6322 /// b = ToBePromoted <ty2> Def, ...
6323 /// =>
6324 /// b = ToBePromoted <ty1> a, ...
6325 /// Def = Transition <ty1> ToBePromoted to <ty2>
6326 void promoteImpl(Instruction *ToBePromoted);
6327
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006328 /// Check whether or not it is profitable to promote all the
Quentin Colombetc32615d2014-10-31 17:52:53 +00006329 /// instructions enqueued to be promoted.
6330 bool isProfitableToPromote() {
6331 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
6332 unsigned Index = isa<ConstantInt>(ValIdx)
6333 ? cast<ConstantInt>(ValIdx)->getZExtValue()
6334 : -1;
6335 Type *PromotedType = getTransitionType();
6336
6337 StoreInst *ST = cast<StoreInst>(CombineInst);
6338 unsigned AS = ST->getPointerAddressSpace();
6339 unsigned Align = ST->getAlignment();
6340 // Check if this store is supported.
6341 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00006342 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
6343 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00006344 // If this is not supported, there is no way we can combine
6345 // the extract with the store.
6346 return false;
6347 }
6348
6349 // The scalar chain of computation has to pay for the transition
6350 // scalar to vector.
6351 // The vector chain has to account for the combining cost.
6352 uint64_t ScalarCost =
6353 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
6354 uint64_t VectorCost = StoreExtractCombineCost;
6355 for (const auto &Inst : InstsToBePromoted) {
6356 // Compute the cost.
6357 // By construction, all instructions being promoted are arithmetic ones.
6358 // Moreover, one argument is a constant that can be viewed as a splat
6359 // constant.
6360 Value *Arg0 = Inst->getOperand(0);
6361 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
6362 isa<ConstantFP>(Arg0);
6363 TargetTransformInfo::OperandValueKind Arg0OVK =
6364 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
6365 : TargetTransformInfo::OK_AnyValue;
6366 TargetTransformInfo::OperandValueKind Arg1OVK =
6367 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
6368 : TargetTransformInfo::OK_AnyValue;
6369 ScalarCost += TTI.getArithmeticInstrCost(
6370 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
6371 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
6372 Arg0OVK, Arg1OVK);
6373 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006374 LLVM_DEBUG(
6375 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
6376 << ScalarCost << "\nVector: " << VectorCost << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006377 return ScalarCost > VectorCost;
6378 }
6379
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006380 /// Generate a constant vector with \p Val with the same
Quentin Colombetc32615d2014-10-31 17:52:53 +00006381 /// number of elements as the transition.
6382 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00006383 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006384 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
6385 /// otherwise we generate a vector with as many undef as possible:
6386 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
6387 /// used at the index of the extract.
6388 Value *getConstantVector(Constant *Val, bool UseSplat) const {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006389 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006390 if (!UseSplat) {
6391 // If we cannot determine where the constant must be, we have to
6392 // use a splat constant.
6393 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
6394 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
6395 ExtractIdx = CstVal->getSExtValue();
6396 else
6397 UseSplat = true;
6398 }
6399
6400 unsigned End = getTransitionType()->getVectorNumElements();
6401 if (UseSplat)
6402 return ConstantVector::getSplat(End, Val);
6403
6404 SmallVector<Constant *, 4> ConstVec;
6405 UndefValue *UndefVal = UndefValue::get(Val->getType());
6406 for (unsigned Idx = 0; Idx != End; ++Idx) {
6407 if (Idx == ExtractIdx)
6408 ConstVec.push_back(Val);
6409 else
6410 ConstVec.push_back(UndefVal);
6411 }
6412 return ConstantVector::get(ConstVec);
6413 }
6414
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006415 /// Check if promoting to a vector type an operand at \p OperandIdx
Quentin Colombetc32615d2014-10-31 17:52:53 +00006416 /// in \p Use can trigger undefined behavior.
6417 static bool canCauseUndefinedBehavior(const Instruction *Use,
6418 unsigned OperandIdx) {
6419 // This is not safe to introduce undef when the operand is on
6420 // the right hand side of a division-like instruction.
6421 if (OperandIdx != 1)
6422 return false;
6423 switch (Use->getOpcode()) {
6424 default:
6425 return false;
6426 case Instruction::SDiv:
6427 case Instruction::UDiv:
6428 case Instruction::SRem:
6429 case Instruction::URem:
6430 return true;
6431 case Instruction::FDiv:
6432 case Instruction::FRem:
6433 return !Use->hasNoNaNs();
6434 }
6435 llvm_unreachable(nullptr);
6436 }
6437
6438public:
Mehdi Amini44ede332015-07-09 02:09:04 +00006439 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
6440 const TargetTransformInfo &TTI, Instruction *Transition,
6441 unsigned CombineCost)
6442 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Eugene Zelenko900b6332017-08-29 22:32:07 +00006443 StoreExtractCombineCost(CombineCost) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00006444 assert(Transition && "Do not know how to promote null");
6445 }
6446
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006447 /// Check if we can promote \p ToBePromoted to \p Type.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006448 bool canPromote(const Instruction *ToBePromoted) const {
6449 // We could support CastInst too.
6450 return isa<BinaryOperator>(ToBePromoted);
6451 }
6452
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006453 /// Check if it is profitable to promote \p ToBePromoted
Quentin Colombetc32615d2014-10-31 17:52:53 +00006454 /// by moving downward the transition through.
6455 bool shouldPromote(const Instruction *ToBePromoted) const {
6456 // Promote only if all the operands can be statically expanded.
6457 // Indeed, we do not want to introduce any new kind of transitions.
6458 for (const Use &U : ToBePromoted->operands()) {
6459 const Value *Val = U.get();
6460 if (Val == getEndOfTransition()) {
6461 // If the use is a division and the transition is on the rhs,
6462 // we cannot promote the operation, otherwise we may create a
6463 // division by zero.
6464 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
6465 return false;
6466 continue;
6467 }
6468 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
6469 !isa<ConstantFP>(Val))
6470 return false;
6471 }
6472 // Check that the resulting operation is legal.
6473 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
6474 if (!ISDOpcode)
6475 return false;
6476 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00006477 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00006478 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00006479 }
6480
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006481 /// Check whether or not \p Use can be combined
Quentin Colombetc32615d2014-10-31 17:52:53 +00006482 /// with the transition.
6483 /// I.e., is it possible to do Use(Transition) => AnotherUse?
6484 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
6485
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006486 /// Record \p ToBePromoted as part of the chain to be promoted.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006487 void enqueueForPromotion(Instruction *ToBePromoted) {
6488 InstsToBePromoted.push_back(ToBePromoted);
6489 }
6490
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006491 /// Set the instruction that will be combined with the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006492 void recordCombineInstruction(Instruction *ToBeCombined) {
6493 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
6494 CombineInst = ToBeCombined;
6495 }
6496
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006497 /// Promote all the instructions enqueued for promotion if it is
Quentin Colombetc32615d2014-10-31 17:52:53 +00006498 /// is profitable.
6499 /// \return True if the promotion happened, false otherwise.
6500 bool promote() {
6501 // Check if there is something to promote.
6502 // Right now, if we do not have anything to combine with,
6503 // we assume the promotion is not profitable.
6504 if (InstsToBePromoted.empty() || !CombineInst)
6505 return false;
6506
6507 // Check cost.
6508 if (!StressStoreExtract && !isProfitableToPromote())
6509 return false;
6510
6511 // Promote.
6512 for (auto &ToBePromoted : InstsToBePromoted)
6513 promoteImpl(ToBePromoted);
6514 InstsToBePromoted.clear();
6515 return true;
6516 }
6517};
Eugene Zelenko900b6332017-08-29 22:32:07 +00006518
6519} // end anonymous namespace
Quentin Colombetc32615d2014-10-31 17:52:53 +00006520
6521void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
6522 // At this point, we know that all the operands of ToBePromoted but Def
6523 // can be statically promoted.
6524 // For Def, we need to use its parameter in ToBePromoted:
6525 // b = ToBePromoted ty1 a
6526 // Def = Transition ty1 b to ty2
6527 // Move the transition down.
6528 // 1. Replace all uses of the promoted operation by the transition.
6529 // = ... b => = ... Def.
6530 assert(ToBePromoted->getType() == Transition->getType() &&
6531 "The type of the result of the transition does not match "
6532 "the final type");
6533 ToBePromoted->replaceAllUsesWith(Transition);
6534 // 2. Update the type of the uses.
6535 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
6536 Type *TransitionTy = getTransitionType();
6537 ToBePromoted->mutateType(TransitionTy);
6538 // 3. Update all the operands of the promoted operation with promoted
6539 // operands.
6540 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
6541 for (Use &U : ToBePromoted->operands()) {
6542 Value *Val = U.get();
6543 Value *NewVal = nullptr;
6544 if (Val == Transition)
6545 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
6546 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
6547 isa<ConstantFP>(Val)) {
6548 // Use a splat constant if it is not safe to use undef.
6549 NewVal = getConstantVector(
6550 cast<Constant>(Val),
6551 isa<UndefValue>(Val) ||
6552 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
6553 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00006554 llvm_unreachable("Did you modified shouldPromote and forgot to update "
6555 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006556 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
6557 }
Sanjay Patel674d2c22017-08-29 14:07:48 +00006558 Transition->moveAfter(ToBePromoted);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006559 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6560}
6561
6562/// Some targets can do store(extractelement) with one instruction.
6563/// Try to push the extractelement towards the stores when the target
6564/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006565bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006566 unsigned CombineCost = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006567 if (DisableStoreExtract || !TLI ||
6568 (!StressStoreExtract &&
6569 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
6570 Inst->getOperand(1), CombineCost)))
6571 return false;
6572
6573 // At this point we know that Inst is a vector to scalar transition.
6574 // Try to move it down the def-use chain, until:
6575 // - We can combine the transition with its single use
6576 // => we got rid of the transition.
6577 // - We escape the current basic block
6578 // => we would need to check that we are moving it at a cheaper place and
6579 // we do not do that for now.
6580 BasicBlock *Parent = Inst->getParent();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006581 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00006582 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006583 // If the transition has more than one use, assume this is not going to be
6584 // beneficial.
6585 while (Inst->hasOneUse()) {
6586 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006587 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006588
6589 if (ToBePromoted->getParent() != Parent) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006590 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
6591 << ToBePromoted->getParent()->getName()
6592 << ") than the transition (" << Parent->getName()
6593 << ").\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006594 return false;
6595 }
6596
6597 if (VPH.canCombine(ToBePromoted)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006598 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
6599 << "will be combined with: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006600 VPH.recordCombineInstruction(ToBePromoted);
6601 bool Changed = VPH.promote();
6602 NumStoreExtractExposed += Changed;
6603 return Changed;
6604 }
6605
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006606 LLVM_DEBUG(dbgs() << "Try promoting.\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006607 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6608 return false;
6609
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006610 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006611
6612 VPH.enqueueForPromotion(ToBePromoted);
6613 Inst = ToBePromoted;
6614 }
6615 return false;
6616}
6617
Wei Mia2f0b592016-12-22 19:44:45 +00006618/// For the instruction sequence of store below, F and I values
6619/// are bundled together as an i64 value before being stored into memory.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006620/// Sometimes it is more efficient to generate separate stores for F and I,
Wei Mia2f0b592016-12-22 19:44:45 +00006621/// which can remove the bitwise instructions or sink them to colder places.
6622///
6623/// (store (or (zext (bitcast F to i32) to i64),
6624/// (shl (zext I to i64), 32)), addr) -->
6625/// (store F, addr) and (store I, addr+4)
6626///
6627/// Similarly, splitting for other merged store can also be beneficial, like:
6628/// For pair of {i32, i32}, i64 store --> two i32 stores.
6629/// For pair of {i32, i16}, i64 store --> two i32 stores.
6630/// For pair of {i16, i16}, i32 store --> two i16 stores.
6631/// For pair of {i16, i8}, i32 store --> two i16 stores.
6632/// For pair of {i8, i8}, i16 store --> two i8 stores.
6633///
6634/// We allow each target to determine specifically which kind of splitting is
6635/// supported.
6636///
6637/// The store patterns are commonly seen from the simple code snippet below
6638/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
6639/// void goo(const std::pair<int, float> &);
6640/// hoo() {
6641/// ...
6642/// goo(std::make_pair(tmp, ftmp));
6643/// ...
6644/// }
6645///
6646/// Although we already have similar splitting in DAG Combine, we duplicate
6647/// it in CodeGenPrepare to catch the case in which pattern is across
6648/// multiple BBs. The logic in DAG Combine is kept to catch case generated
6649/// during code expansion.
6650static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
6651 const TargetLowering &TLI) {
6652 // Handle simple but common cases only.
6653 Type *StoreType = SI.getValueOperand()->getType();
6654 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6655 DL.getTypeSizeInBits(StoreType) == 0)
6656 return false;
6657
6658 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6659 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6660 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6661 DL.getTypeSizeInBits(SplitStoreType))
6662 return false;
6663
6664 // Match the following patterns:
6665 // (store (or (zext LValue to i64),
6666 // (shl (zext HValue to i64), 32)), HalfValBitSize)
6667 // or
6668 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6669 // (zext LValue to i64),
6670 // Expect both operands of OR and the first operand of SHL have only
6671 // one use.
6672 Value *LValue, *HValue;
6673 if (!match(SI.getValueOperand(),
6674 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6675 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6676 m_SpecificInt(HalfValBitSize))))))
6677 return false;
6678
6679 // Check LValue and HValue are int with size less or equal than 32.
6680 if (!LValue->getType()->isIntegerTy() ||
6681 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6682 !HValue->getType()->isIntegerTy() ||
6683 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6684 return false;
6685
6686 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6687 // as the input of target query.
6688 auto *LBC = dyn_cast<BitCastInst>(LValue);
6689 auto *HBC = dyn_cast<BitCastInst>(HValue);
6690 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6691 : EVT::getEVT(LValue->getType());
6692 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6693 : EVT::getEVT(HValue->getType());
6694 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6695 return false;
6696
6697 // Start to split store.
6698 IRBuilder<> Builder(SI.getContext());
6699 Builder.SetInsertPoint(&SI);
6700
6701 // If LValue/HValue is a bitcast in another BB, create a new one in current
6702 // BB so it may be merged with the splitted stores by dag combiner.
6703 if (LBC && LBC->getParent() != SI.getParent())
6704 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6705 if (HBC && HBC->getParent() != SI.getParent())
6706 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6707
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006708 bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
Wei Mia2f0b592016-12-22 19:44:45 +00006709 auto CreateSplitStore = [&](Value *V, bool Upper) {
6710 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6711 Value *Addr = Builder.CreateBitCast(
6712 SI.getOperand(1),
6713 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006714 if ((IsLE && Upper) || (!IsLE && !Upper))
Wei Mia2f0b592016-12-22 19:44:45 +00006715 Addr = Builder.CreateGEP(
6716 SplitStoreType, Addr,
6717 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6718 Builder.CreateAlignedStore(
6719 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6720 };
6721
6722 CreateSplitStore(LValue, false);
6723 CreateSplitStore(HValue, true);
6724
6725 // Delete the old store.
6726 SI.eraseFromParent();
6727 return true;
6728}
6729
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006730// Return true if the GEP has two operands, the first operand is of a sequential
6731// type, and the second operand is a constant.
6732static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6733 gep_type_iterator I = gep_type_begin(*GEP);
6734 return GEP->getNumOperands() == 2 &&
6735 I.isSequential() &&
6736 isa<ConstantInt>(GEP->getOperand(1));
6737}
6738
6739// Try unmerging GEPs to reduce liveness interference (register pressure) across
6740// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6741// reducing liveness interference across those edges benefits global register
6742// allocation. Currently handles only certain cases.
6743//
6744// For example, unmerge %GEPI and %UGEPI as below.
6745//
6746// ---------- BEFORE ----------
6747// SrcBlock:
6748// ...
6749// %GEPIOp = ...
6750// ...
6751// %GEPI = gep %GEPIOp, Idx
6752// ...
6753// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6754// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6755// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6756// %UGEPI)
6757//
6758// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6759// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6760// ...
6761//
6762// DstBi:
6763// ...
6764// %UGEPI = gep %GEPIOp, UIdx
6765// ...
6766// ---------------------------
6767//
6768// ---------- AFTER ----------
6769// SrcBlock:
6770// ... (same as above)
6771// (* %GEPI is still alive on the indirectbr edges)
6772// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6773// unmerging)
6774// ...
6775//
6776// DstBi:
6777// ...
6778// %UGEPI = gep %GEPI, (UIdx-Idx)
6779// ...
6780// ---------------------------
6781//
6782// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6783// no longer alive on them.
6784//
6785// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6786// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6787// not to disable further simplications and optimizations as a result of GEP
6788// merging.
6789//
6790// Note this unmerging may increase the length of the data flow critical path
6791// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6792// between the register pressure and the length of data-flow critical
6793// path. Restricting this to the uncommon IndirectBr case would minimize the
6794// impact of potentially longer critical path, if any, and the impact on compile
6795// time.
6796static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6797 const TargetTransformInfo *TTI) {
6798 BasicBlock *SrcBlock = GEPI->getParent();
6799 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6800 // (non-IndirectBr) cases exit early here.
6801 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6802 return false;
6803 // Check that GEPI is a simple gep with a single constant index.
6804 if (!GEPSequentialConstIndexed(GEPI))
6805 return false;
6806 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6807 // Check that GEPI is a cheap one.
6808 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6809 > TargetTransformInfo::TCC_Basic)
6810 return false;
6811 Value *GEPIOp = GEPI->getOperand(0);
6812 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6813 if (!isa<Instruction>(GEPIOp))
6814 return false;
6815 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6816 if (GEPIOpI->getParent() != SrcBlock)
6817 return false;
6818 // Check that GEP is used outside the block, meaning it's alive on the
6819 // IndirectBr edge(s).
6820 if (find_if(GEPI->users(), [&](User *Usr) {
6821 if (auto *I = dyn_cast<Instruction>(Usr)) {
6822 if (I->getParent() != SrcBlock) {
6823 return true;
6824 }
6825 }
6826 return false;
6827 }) == GEPI->users().end())
6828 return false;
6829 // The second elements of the GEP chains to be unmerged.
6830 std::vector<GetElementPtrInst *> UGEPIs;
6831 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6832 // on IndirectBr edges.
6833 for (User *Usr : GEPIOp->users()) {
6834 if (Usr == GEPI) continue;
6835 // Check if Usr is an Instruction. If not, give up.
6836 if (!isa<Instruction>(Usr))
6837 return false;
6838 auto *UI = cast<Instruction>(Usr);
6839 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6840 if (UI->getParent() == SrcBlock)
6841 continue;
6842 // Check if Usr is a GEP. If not, give up.
6843 if (!isa<GetElementPtrInst>(Usr))
6844 return false;
6845 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6846 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6847 // the pointer operand to it. If so, record it in the vector. If not, give
6848 // up.
6849 if (!GEPSequentialConstIndexed(UGEPI))
6850 return false;
6851 if (UGEPI->getOperand(0) != GEPIOp)
6852 return false;
6853 if (GEPIIdx->getType() !=
6854 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6855 return false;
6856 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6857 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6858 > TargetTransformInfo::TCC_Basic)
6859 return false;
6860 UGEPIs.push_back(UGEPI);
6861 }
6862 if (UGEPIs.size() == 0)
6863 return false;
6864 // Check the materializing cost of (Uidx-Idx).
6865 for (GetElementPtrInst *UGEPI : UGEPIs) {
6866 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6867 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6868 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6869 if (ImmCost > TargetTransformInfo::TCC_Basic)
6870 return false;
6871 }
6872 // Now unmerge between GEPI and UGEPIs.
6873 for (GetElementPtrInst *UGEPI : UGEPIs) {
6874 UGEPI->setOperand(0, GEPI);
6875 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6876 Constant *NewUGEPIIdx =
6877 ConstantInt::get(GEPIIdx->getType(),
6878 UGEPIIdx->getValue() - GEPIIdx->getValue());
6879 UGEPI->setOperand(1, NewUGEPIIdx);
6880 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6881 // inbounds to avoid UB.
6882 if (!GEPI->isInBounds()) {
6883 UGEPI->setIsInBounds(false);
6884 }
6885 }
6886 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6887 // alive on IndirectBr edges).
6888 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6889 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6890 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6891 return true;
6892}
6893
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00006894bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00006895 // Bail out if we inserted the instruction to prevent optimizations from
6896 // stepping on each other's toes.
6897 if (InsertedInsts.count(I))
6898 return false;
6899
Sanjay Pateld1ce4552019-03-20 15:53:06 +00006900 // TODO: Move into the switch on opcode below here.
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006901 if (PHINode *P = dyn_cast<PHINode>(I)) {
6902 // It is possible for very late stage optimizations (such as SimplifyCFG)
6903 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6904 // trivial PHI, go ahead and zap it here.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00006905 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
Eugene Leviant1e249ca2019-03-12 10:10:29 +00006906 LargeOffsetGEPMap.erase(P);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006907 P->replaceAllUsesWith(V);
6908 P->eraseFromParent();
6909 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00006910 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006911 }
Chris Lattneree588de2011-01-15 07:29:01 +00006912 return false;
6913 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006914
Chris Lattneree588de2011-01-15 07:29:01 +00006915 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006916 // If the source of the cast is a constant, then this should have
6917 // already been constant folded. The only reason NOT to constant fold
6918 // it is if something (e.g. LSR) was careful to place the constant
6919 // evaluation in a block other than then one that uses it (e.g. to hoist
6920 // the address of globals out of a loop). If this is the case, we don't
6921 // want to forward-subst the cast.
6922 if (isa<Constant>(CI->getOperand(0)))
6923 return false;
6924
Mehdi Amini44ede332015-07-09 02:09:04 +00006925 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00006926 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006927
Chris Lattneree588de2011-01-15 07:29:01 +00006928 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006929 /// Sink a zext or sext into its user blocks if the target type doesn't
6930 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00006931 if (TLI &&
6932 TLI->getTypeAction(CI->getContext(),
6933 TLI->getValueType(*DL, CI->getType())) ==
6934 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006935 return SinkCast(CI);
6936 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00006937 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00006938 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006939 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006940 }
Chris Lattneree588de2011-01-15 07:29:01 +00006941 return false;
6942 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006943
Sanjay Pateld8b4efc2019-02-18 23:33:05 +00006944 if (auto *Cmp = dyn_cast<CmpInst>(I))
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00006945 if (TLI && optimizeCmp(Cmp, ModifiedDT))
Sanjay Patel00fcc742019-02-03 13:48:03 +00006946 return true;
Nadav Rotem465834c2012-07-24 10:51:42 +00006947
Chris Lattneree588de2011-01-15 07:29:01 +00006948 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006949 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006950 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006951 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006952 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006953 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6954 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006955 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006956 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006957 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006958
Chris Lattneree588de2011-01-15 07:29:01 +00006959 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006960 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6961 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006962 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006963 if (TLI) {
6964 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006965 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006966 SI->getOperand(0)->getType(), AS);
6967 }
Chris Lattneree588de2011-01-15 07:29:01 +00006968 return false;
6969 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006970
Matt Arsenault02d915b2017-03-15 22:35:20 +00006971 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6972 unsigned AS = RMW->getPointerAddressSpace();
6973 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6974 RMW->getType(), AS);
6975 }
6976
6977 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6978 unsigned AS = CmpX->getPointerAddressSpace();
6979 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6980 CmpX->getCompareOperand()->getType(), AS);
6981 }
6982
Yi Jiangd069f632014-04-21 19:34:27 +00006983 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6984
Geoff Berry5d534b62017-02-21 18:53:14 +00006985 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6986 EnableAndCmpSinking && TLI)
6987 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6988
Yi Jiangd069f632014-04-21 19:34:27 +00006989 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6990 BinOp->getOpcode() == Instruction::LShr)) {
6991 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6992 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006993 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006994
6995 return false;
6996 }
6997
Chris Lattneree588de2011-01-15 07:29:01 +00006998 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006999 if (GEPI->hasAllZeroIndices()) {
7000 /// The GEP operand must be a pointer, so must its result -> BitCast
7001 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
7002 GEPI->getName(), GEPI);
Vedant Kumar40399a22018-05-24 23:00:21 +00007003 NC->setDebugLoc(GEPI->getDebugLoc());
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00007004 GEPI->replaceAllUsesWith(NC);
7005 GEPI->eraseFromParent();
7006 ++NumGEPsElim;
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00007007 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00007008 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00007009 }
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00007010 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
7011 return true;
7012 }
Chris Lattneree588de2011-01-15 07:29:01 +00007013 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00007014 }
Nadav Rotem465834c2012-07-24 10:51:42 +00007015
Florian Hahn3b251962019-02-05 10:27:40 +00007016 if (tryToSinkFreeOperands(I))
7017 return true;
7018
Sanjay Pateld1ce4552019-03-20 15:53:06 +00007019 switch (I->getOpcode()) {
7020 case Instruction::Call:
7021 return optimizeCallInst(cast<CallInst>(I), ModifiedDT);
7022 case Instruction::Select:
Teresa Johnsonb7e21382019-03-27 18:44:25 +00007023 return optimizeSelectInst(cast<SelectInst>(I));
Sanjay Pateld1ce4552019-03-20 15:53:06 +00007024 case Instruction::ShuffleVector:
7025 return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I));
7026 case Instruction::Switch:
7027 return optimizeSwitchInst(cast<SwitchInst>(I));
7028 case Instruction::ExtractElement:
7029 return optimizeExtractElementInst(cast<ExtractElementInst>(I));
7030 }
Quentin Colombetc32615d2014-10-31 17:52:53 +00007031
Chris Lattneree588de2011-01-15 07:29:01 +00007032 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00007033}
7034
James Molloyf01488e2016-01-15 09:20:19 +00007035/// Given an OR instruction, check to see if this is a bitreverse
7036/// idiom. If so, insert the new intrinsic and return true.
7037static bool makeBitReverse(Instruction &I, const DataLayout &DL,
7038 const TargetLowering &TLI) {
7039 if (!I.getType()->isIntegerTy() ||
7040 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
7041 TLI.getValueType(DL, I.getType(), true)))
7042 return false;
7043
7044 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00007045 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00007046 return false;
7047 Instruction *LastInst = Insts.back();
7048 I.replaceAllUsesWith(LastInst);
7049 RecursivelyDeleteTriviallyDeadInstructions(&I);
7050 return true;
7051}
7052
Chris Lattnerf2836d12007-03-31 04:06:36 +00007053// In this pass we look for GEP and cast instructions that are used
7054// across basic blocks and rewrite them to improve basic-block-at-a-time
7055// selection.
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00007056bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00007057 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00007058 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00007059
Chris Lattner7a277142011-01-15 07:14:54 +00007060 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00007061 while (CurInstIterator != BB.end()) {
Teresa Johnson3bd4b5a2019-03-25 18:38:48 +00007062 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00007063 if (ModifiedDT)
7064 return true;
7065 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00007066
James Molloyf01488e2016-01-15 09:20:19 +00007067 bool MadeBitReverse = true;
7068 while (TLI && MadeBitReverse) {
7069 MadeBitReverse = false;
7070 for (auto &I : reverse(BB)) {
7071 if (makeBitReverse(I, *DL, *TLI)) {
7072 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00007073 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00007074 break;
7075 }
7076 }
7077 }
Rong Xuce3be452019-03-08 22:46:18 +00007078 MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT);
Junmo Park7d6c5f12016-01-28 09:42:39 +00007079
Chris Lattnerf2836d12007-03-31 04:06:36 +00007080 return MadeChange;
7081}
Devang Patel53771ba2011-08-18 00:50:51 +00007082
7083// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00007084// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00007085// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00007086bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00007087 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00007088 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00007089 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00007090 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00007091 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00007092 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00007093 // Leave dbg.values that refer to an alloca alone. These
Craig Topper87e715f2017-11-07 20:56:17 +00007094 // intrinsics describe the address of a variable (= the alloca)
Adrian Prantl32da8892014-04-25 20:49:25 +00007095 // being taken. They should not be moved next to the alloca
7096 // (and to the beginning of the scope), but rather stay close to
7097 // where said address is used.
7098 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00007099 PrevNonDbgInst = Insn;
7100 continue;
7101 }
7102
7103 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
7104 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00007105 // If VI is a phi in a block with an EHPad terminator, we can't insert
7106 // after it.
7107 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
7108 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007109 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
7110 << *DVI << ' ' << *VI);
Devang Patel53771ba2011-08-18 00:50:51 +00007111 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00007112 if (isa<PHINode>(VI))
7113 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
7114 else
7115 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00007116 MadeChange = true;
7117 ++NumDbgValueMoved;
7118 }
7119 }
7120 }
7121 return MadeChange;
7122}
Tim Northovercea0abb2014-03-29 08:22:29 +00007123
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00007124/// Scale down both weights to fit into uint32_t.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007125static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
7126 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
Eugene Zelenko900b6332017-08-29 22:32:07 +00007127 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007128 NewTrue = NewTrue / Scale;
7129 NewFalse = NewFalse / Scale;
7130}
7131
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00007132/// Some targets prefer to split a conditional branch like:
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007133/// \code
7134/// %0 = icmp ne i32 %a, 0
7135/// %1 = icmp ne i32 %b, 0
7136/// %or.cond = or i1 %0, %1
7137/// br i1 %or.cond, label %TrueBB, label %FalseBB
7138/// \endcode
7139/// into multiple branch instructions like:
7140/// \code
7141/// bb1:
7142/// %0 = icmp ne i32 %a, 0
7143/// br i1 %0, label %TrueBB, label %bb2
7144/// bb2:
7145/// %1 = icmp ne i32 %b, 0
7146/// br i1 %1, label %TrueBB, label %FalseBB
7147/// \endcode
7148/// This usually allows instruction selection to do even further optimizations
7149/// and combine the compare with the branch instruction. Currently this is
7150/// applied for targets which have "cheap" jump instructions.
7151///
7152/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
7153///
Rong Xuce3be452019-03-08 22:46:18 +00007154bool CodeGenPrepare::splitBranchCondition(Function &F, bool &ModifiedDT) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00007155 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007156 return false;
7157
7158 bool MadeChange = false;
7159 for (auto &BB : F) {
7160 // Does this BB end with the following?
7161 // %cond1 = icmp|fcmp|binary instruction ...
7162 // %cond2 = icmp|fcmp|binary instruction ...
7163 // %cond.or = or|and i1 %cond1, cond2
7164 // br i1 %cond.or label %dest1, label %dest2"
7165 BinaryOperator *LogicOp;
7166 BasicBlock *TBB, *FBB;
7167 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
7168 continue;
7169
Sanjay Patel42574202015-09-02 19:23:23 +00007170 auto *Br1 = cast<BranchInst>(BB.getTerminator());
7171 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
7172 continue;
7173
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007174 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00007175 Value *Cond1, *Cond2;
7176 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
7177 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007178 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00007179 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
7180 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007181 Opc = Instruction::Or;
7182 else
7183 continue;
7184
7185 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
7186 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
7187 continue;
7188
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007189 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007190
7191 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00007192 auto TmpBB =
7193 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
7194 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007195
7196 // Update original basic block by using the first condition directly by the
7197 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007198 Br1->setCondition(Cond1);
7199 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00007200
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00007201 // Depending on the condition we have to either replace the true or the
7202 // false successor of the original branch instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007203 if (Opc == Instruction::And)
7204 Br1->setSuccessor(0, TmpBB);
7205 else
7206 Br1->setSuccessor(1, TmpBB);
7207
7208 // Fill in the new basic block.
7209 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00007210 if (auto *I = dyn_cast<Instruction>(Cond2)) {
7211 I->removeFromParent();
7212 I->insertBefore(Br2);
7213 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007214
7215 // Update PHI nodes in both successors. The original BB needs to be
Hiroshi Inoue6a391bb2017-06-27 10:35:37 +00007216 // replaced in one successor's PHI nodes, because the branch comes now from
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007217 // the newly generated BB (NewBB). In the other successor we need to add one
7218 // incoming edge to the PHI nodes, because both branch instructions target
7219 // now the same successor. Depending on the original branch condition
7220 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00007221 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007222 // This doesn't change the successor order of the just created branch
7223 // instruction (or any other instruction).
7224 if (Opc == Instruction::Or)
7225 std::swap(TBB, FBB);
7226
7227 // Replace the old BB with the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00007228 for (PHINode &PN : TBB->phis()) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007229 int i;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00007230 while ((i = PN.getBasicBlockIndex(&BB)) >= 0)
7231 PN.setIncomingBlock(i, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007232 }
7233
7234 // Add another incoming edge form the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00007235 for (PHINode &PN : FBB->phis()) {
7236 auto *Val = PN.getIncomingValueForBlock(&BB);
7237 PN.addIncoming(Val, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007238 }
7239
7240 // Update the branch weights (from SelectionDAGBuilder::
7241 // FindMergedConditions).
7242 if (Opc == Instruction::Or) {
7243 // Codegen X | Y as:
7244 // BB1:
7245 // jmp_if_X TBB
7246 // jmp TmpBB
7247 // TmpBB:
7248 // jmp_if_Y TBB
7249 // jmp FBB
7250 //
7251
7252 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
7253 // The requirement is that
7254 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00007255 // = TrueProb for original BB.
7256 // Assuming the original weights are A and B, one choice is to set BB1's
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007257 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
7258 // assumes that
7259 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
7260 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
7261 // TmpBB, but the math is more complicated.
7262 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00007263 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007264 uint64_t NewTrueWeight = TrueWeight;
7265 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
7266 scaleWeights(NewTrueWeight, NewFalseWeight);
7267 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
7268 .createBranchWeights(TrueWeight, FalseWeight));
7269
7270 NewTrueWeight = TrueWeight;
7271 NewFalseWeight = 2 * FalseWeight;
7272 scaleWeights(NewTrueWeight, NewFalseWeight);
7273 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
7274 .createBranchWeights(TrueWeight, FalseWeight));
7275 }
7276 } else {
7277 // Codegen X & Y as:
7278 // BB1:
7279 // jmp_if_X TmpBB
7280 // jmp FBB
7281 // TmpBB:
7282 // jmp_if_Y TBB
7283 // jmp FBB
7284 //
7285 // This requires creation of TmpBB after CurBB.
7286
7287 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
7288 // The requirement is that
7289 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00007290 // = FalseProb for original BB.
7291 // Assuming the original weights are A and B, one choice is to set BB1's
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007292 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
7293 // assumes that
7294 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
7295 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00007296 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007297 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
7298 uint64_t NewFalseWeight = FalseWeight;
7299 scaleWeights(NewTrueWeight, NewFalseWeight);
7300 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
7301 .createBranchWeights(TrueWeight, FalseWeight));
7302
7303 NewTrueWeight = 2 * TrueWeight;
7304 NewFalseWeight = FalseWeight;
7305 scaleWeights(NewTrueWeight, NewFalseWeight);
7306 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
7307 .createBranchWeights(TrueWeight, FalseWeight));
7308 }
7309 }
7310
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007311 ModifiedDT = true;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007312 MadeChange = true;
7313
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007314 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
7315 TmpBB->dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007316 }
7317 return MadeChange;
7318}