blob: 1b8d5b32930d7c533493c56c57c8053abb1f596b [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf2836d12007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
Eugene Zelenko900b6332017-08-29 22:32:07 +000016#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000019#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/STLExtras.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/Statistic.h"
Jun Bum Lim90b6b502016-12-16 20:38:39 +000024#include "llvm/Analysis/BlockFrequencyInfo.h"
25#include "llvm/Analysis/BranchProbabilityInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000026#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000028#include "llvm/Analysis/LoopInfo.h"
Zaara Syeda3a7578c2017-05-31 17:12:38 +000029#include "llvm/Analysis/MemoryBuiltins.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000030#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000031#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000032#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie2be39222018-03-21 22:34:23 +000033#include "llvm/Analysis/Utils/Local.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000034#include "llvm/Analysis/ValueTracking.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000035#include "llvm/CodeGen/Analysis.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000036#include "llvm/CodeGen/ISDOpcodes.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000037#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000038#include "llvm/CodeGen/TargetLowering.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000039#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000040#include "llvm/CodeGen/TargetSubtargetInfo.h"
Craig Topper2fa14362018-03-29 17:21:10 +000041#include "llvm/CodeGen/ValueTypes.h"
Nico Weber432a3882018-04-30 14:59:11 +000042#include "llvm/Config/llvm-config.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000043#include "llvm/IR/Argument.h"
44#include "llvm/IR/Attributes.h"
45#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000046#include "llvm/IR/CallSite.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000047#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000051#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000053#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000054#include "llvm/IR/GlobalValue.h"
55#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/IRBuilder.h"
57#include "llvm/IR/InlineAsm.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000058#include "llvm/IR/InstrTypes.h"
59#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000060#include "llvm/IR/Instructions.h"
61#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000062#include "llvm/IR/Intrinsics.h"
63#include "llvm/IR/LLVMContext.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000064#include "llvm/IR/MDBuilder.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000065#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000067#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000068#include "llvm/IR/Statepoint.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000069#include "llvm/IR/Type.h"
70#include "llvm/IR/Use.h"
71#include "llvm/IR/User.h"
72#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000073#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000074#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000075#include "llvm/Pass.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000076#include "llvm/Support/BlockFrequency.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000077#include "llvm/Support/BranchProbability.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000078#include "llvm/Support/Casting.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000079#include "llvm/Support/CommandLine.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000080#include "llvm/Support/Compiler.h"
Evan Chengd3d80172007-12-05 23:58:20 +000081#include "llvm/Support/Debug.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000082#include "llvm/Support/ErrorHandling.h"
David Blaikie13e77db2018-03-23 23:58:25 +000083#include "llvm/Support/MachineValueType.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000084#include "llvm/Support/MathExtras.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000085#include "llvm/Support/raw_ostream.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000086#include "llvm/Target/TargetMachine.h"
87#include "llvm/Target/TargetOptions.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000088#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000089#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000090#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000091#include <algorithm>
92#include <cassert>
93#include <cstdint>
94#include <iterator>
95#include <limits>
96#include <memory>
97#include <utility>
98#include <vector>
Zaara Syeda3a7578c2017-05-31 17:12:38 +000099
Chris Lattnerf2836d12007-03-31 04:06:36 +0000100using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +0000101using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000102
Chandler Carruth1b9dde02014-04-22 02:02:50 +0000103#define DEBUG_TYPE "codegenprepare"
104
Cameron Zwarichced753f2011-01-05 17:27:27 +0000105STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +0000106STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
107STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +0000108STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
109 "sunken Cmps");
110STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
111 "of sunken Casts");
112STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
113 "computations were sunk");
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000114STATISTIC(NumMemoryInstsPhiCreated,
115 "Number of phis created when address "
116 "computations were sunk to memory instructions");
117STATISTIC(NumMemoryInstsSelectCreated,
118 "Number of select created when address "
119 "computations were sunk to memory instructions");
Evan Cheng0663f232011-03-21 01:19:09 +0000120STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
121STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +0000122STATISTIC(NumAndsAdded,
123 "Number of and mask instructions added to form ext loads");
124STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +0000125STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +0000126STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000127STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +0000128STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +0000129
Cameron Zwarich338d3622011-03-11 21:52:04 +0000130static cl::opt<bool> DisableBranchOpts(
131 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
132 cl::desc("Disable branch optimizations in CodeGenPrepare"));
133
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000134static cl::opt<bool>
135 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
136 cl::desc("Disable GC optimizations in CodeGenPrepare"));
137
Benjamin Kramer3d38c172012-05-06 14:25:16 +0000138static cl::opt<bool> DisableSelectToBranch(
139 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
140 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000141
Hal Finkelc3998302014-04-12 00:59:48 +0000142static cl::opt<bool> AddrSinkUsingGEPs(
Eli Friedman5fba1e52017-04-06 22:42:18 +0000143 "addr-sink-using-gep", cl::Hidden, cl::init(true),
Hal Finkelc3998302014-04-12 00:59:48 +0000144 cl::desc("Address sinking in CGP using GEPs."));
145
Tim Northovercea0abb2014-03-29 08:22:29 +0000146static cl::opt<bool> EnableAndCmpSinking(
147 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
148 cl::desc("Enable sinkinig and/cmp into branches."));
149
Quentin Colombetc32615d2014-10-31 17:52:53 +0000150static cl::opt<bool> DisableStoreExtract(
151 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
152 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
153
154static cl::opt<bool> StressStoreExtract(
155 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
156 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
157
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000158static cl::opt<bool> DisableExtLdPromotion(
159 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
160 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
161 "CodeGenPrepare"));
162
163static cl::opt<bool> StressExtLdPromotion(
164 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
165 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
166 "optimization in CodeGenPrepare"));
167
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000168static cl::opt<bool> DisablePreheaderProtect(
169 "disable-preheader-prot", cl::Hidden, cl::init(false),
170 cl::desc("Disable protection against removing loop preheaders"));
171
Dehao Chen302b69c2016-10-18 20:42:47 +0000172static cl::opt<bool> ProfileGuidedSectionPrefix(
David Callahan5960d9b12017-06-14 20:35:33 +0000173 "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
Dehao Chen302b69c2016-10-18 20:42:47 +0000174 cl::desc("Use profile info to add section prefix for hot/cold functions"));
175
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000176static cl::opt<unsigned> FreqRatioToSkipMerge(
177 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
178 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
179 "(frequency of destination block) is greater than this ratio"));
180
Wei Mia2f0b592016-12-22 19:44:45 +0000181static cl::opt<bool> ForceSplitStore(
182 "force-split-store", cl::Hidden, cl::init(false),
183 cl::desc("Force store splitting no matter what the target query says."));
184
Jun Bum Limdee55652017-04-03 19:20:07 +0000185static cl::opt<bool>
186EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
187 cl::desc("Enable merging of redundant sexts when one is dominating"
188 " the other."), cl::init(true));
189
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000190static cl::opt<bool> DisableComplexAddrModes(
Serguei Katkovd4df7442017-11-29 09:48:50 +0000191 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000192 cl::desc("Disables combining addressing modes with different parts "
193 "in optimizeMemoryInst."));
194
195static cl::opt<bool>
196AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
197 cl::desc("Allow creation of Phis in Address sinking."));
198
199static cl::opt<bool>
Serguei Katkov9fe05242018-01-26 06:26:56 +0000200AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000201 cl::desc("Allow creation of selects in Address sinking."));
202
John Brawn70cdb5b2017-11-24 14:10:45 +0000203static cl::opt<bool> AddrSinkCombineBaseReg(
204 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
205 cl::desc("Allow combining of BaseReg field in Address sinking."));
206
207static cl::opt<bool> AddrSinkCombineBaseGV(
208 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
209 cl::desc("Allow combining of BaseGV field in Address sinking."));
210
211static cl::opt<bool> AddrSinkCombineBaseOffs(
212 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
213 cl::desc("Allow combining of BaseOffs field in Address sinking."));
214
215static cl::opt<bool> AddrSinkCombineScaledReg(
216 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
217 cl::desc("Allow combining of ScaledReg field in Address sinking."));
218
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000219static cl::opt<bool>
220 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
221 cl::init(true),
222 cl::desc("Enable splitting large offset of GEP."));
223
Eric Christopherc1ea1492008-09-24 05:32:41 +0000224namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000225
226using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
227using TypeIsSExt = PointerIntPair<Type *, 1, bool>;
228using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
229using SExts = SmallVector<Instruction *, 16>;
230using ValueToSExts = DenseMap<Value *, SExts>;
231
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000232class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000233
Chris Lattner2dd09db2009-09-02 06:11:42 +0000234 class CodeGenPrepare : public FunctionPass {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000235 const TargetMachine *TM = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000236 const TargetSubtargetInfo *SubtargetInfo;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000237 const TargetLowering *TLI = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000238 const TargetRegisterInfo *TRI;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000239 const TargetTransformInfo *TTI = nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000240 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000241 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000242 std::unique_ptr<BlockFrequencyInfo> BFI;
243 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000244
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000245 /// As we scan instructions optimizing them, this is the next instruction
246 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000247 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000248
Evan Cheng0663f232011-03-21 01:19:09 +0000249 /// Keeps track of non-local addresses that have been sunk into a block.
250 /// This allows us to avoid inserting duplicate code for blocks with
Simon Dardis230f4532017-11-24 16:45:28 +0000251 /// multiple load/stores of the same address. The usage of WeakTrackingVH
252 /// enables SunkAddrs to be treated as a cache whose entries can be
253 /// invalidated if a sunken address computation has been erased.
254 ValueMap<Value*, WeakTrackingVH> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000255
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000256 /// Keeps track of all instructions inserted for the current function.
257 SetOfInstrs InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000258
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000259 /// Keeps track of the type of the related instruction before their
260 /// promotion for the current function.
261 InstrToOrigTy PromotedInsts;
262
Jun Bum Limdee55652017-04-03 19:20:07 +0000263 /// Keep track of instructions removed during promotion.
264 SetOfInstrs RemovedInsts;
265
266 /// Keep track of sext chains based on their initial value.
267 DenseMap<Value *, Instruction *> SeenChainsForSExt;
268
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000269 /// Keep track of GEPs accessing the same data structures such as structs or
270 /// arrays that are candidates to be split later because of their large
271 /// size.
272 DenseMap<
273 AssertingVH<Value>,
274 SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
275 LargeOffsetGEPMap;
276
277 /// Keep track of new GEP base after splitting the GEPs having large offset.
278 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
279
280 /// Map serial numbers to Large offset GEPs.
281 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
282
Jun Bum Limdee55652017-04-03 19:20:07 +0000283 /// Keep track of SExt promoted.
284 ValueToSExts ValToSExtendedUses;
285
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000286 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000287 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000288
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000289 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000290 bool OptSize;
291
Mehdi Amini4fe37982015-07-07 18:45:17 +0000292 /// DataLayout for the Function being processed.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000293 const DataLayout *DL = nullptr;
Mehdi Amini4fe37982015-07-07 18:45:17 +0000294
Chris Lattnerf2836d12007-03-31 04:06:36 +0000295 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000296 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000297
298 CodeGenPrepare() : FunctionPass(ID) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000299 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
300 }
Eugene Zelenko900b6332017-08-29 22:32:07 +0000301
Craig Topper4584cd52014-03-07 09:26:03 +0000302 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000303
Mehdi Amini117296c2016-10-01 02:56:57 +0000304 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000305
Craig Topper4584cd52014-03-07 09:26:03 +0000306 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000307 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000308 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000309 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000310 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000311 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000312 }
313
Chris Lattnerf2836d12007-03-31 04:06:36 +0000314 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000315 bool eliminateFallThrough(Function &F);
316 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000317 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000318 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
319 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000320 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
321 bool isPreheader);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000322 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
323 bool optimizeInst(Instruction *I, bool &ModifiedDT);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000324 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000325 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000326 bool optimizeInlineAsmInst(CallInst *CS);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000327 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000328 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000329 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000330 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000331 bool optimizeSelectInst(SelectInst *SI);
332 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000333 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000334 bool optimizeExtractElementInst(Instruction *Inst);
335 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
336 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000337 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
338 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
339 bool tryToPromoteExts(TypePromotionTransaction &TPT,
340 const SmallVectorImpl<Instruction *> &Exts,
341 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
342 unsigned CreatedInstsCost = 0);
Jun Bum Limdee55652017-04-03 19:20:07 +0000343 bool mergeSExts(Function &F);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000344 bool splitLargeGEPOffsets();
Jun Bum Limdee55652017-04-03 19:20:07 +0000345 bool performAddressTypePromotion(
346 Instruction *&Inst,
347 bool AllowPromotionWithoutCommonHeader,
348 bool HasPromoted, TypePromotionTransaction &TPT,
349 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000350 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000351 bool simplifyOffsetableRelocate(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000352 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000353
354} // end anonymous namespace
Devang Patel09f162c2007-05-01 21:15:47 +0000355
Devang Patel8c78a0b2007-05-03 01:11:54 +0000356char CodeGenPrepare::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000357
Matthias Braun1527baa2017-05-25 21:26:32 +0000358INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000359 "Optimize for code generation", false, false)
Dehao Chen302b69c2016-10-18 20:42:47 +0000360INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000361INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000362 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000363
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000364FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000365
Chris Lattnerf2836d12007-03-31 04:06:36 +0000366bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000367 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000368 return false;
369
Mehdi Amini4fe37982015-07-07 18:45:17 +0000370 DL = &F.getParent()->getDataLayout();
371
Chris Lattnerf2836d12007-03-31 04:06:36 +0000372 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000373 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000374 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000375 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000376
Devang Patel8f606d72011-03-24 15:35:25 +0000377 ModifiedDT = false;
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000378 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
379 TM = &TPC->getTM<TargetMachine>();
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000380 SubtargetInfo = TM->getSubtargetImpl(F);
381 TLI = SubtargetInfo->getTargetLowering();
382 TRI = SubtargetInfo->getRegisterInfo();
383 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000384 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000385 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000386 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000387 BPI.reset(new BranchProbabilityInfo(F, *LI));
388 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000389 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000390
Easwaran Raman0d55b552017-11-14 19:31:51 +0000391 ProfileSummaryInfo *PSI =
392 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen302b69c2016-10-18 20:42:47 +0000393 if (ProfileGuidedSectionPrefix) {
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000394 if (PSI->isFunctionHotInCallGraph(&F, *BFI))
Dehao Chen302b69c2016-10-18 20:42:47 +0000395 F.setSectionPrefix(".hot");
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000396 else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
Teresa Johnson720d9b42017-05-09 01:43:24 +0000397 F.setSectionPrefix(".unlikely");
Dehao Chen302b69c2016-10-18 20:42:47 +0000398 }
399
Preston Gurdcdf540d2012-09-04 18:22:17 +0000400 /// This optimization identifies DIV instructions that can be
401 /// profitably bypassed and carried out with a shorter, faster divide.
Easwaran Raman0d55b552017-11-14 19:31:51 +0000402 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
403 TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000404 const DenseMap<unsigned int, unsigned int> &BypassWidths =
405 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000406 BasicBlock* BB = &*F.begin();
407 while (BB != nullptr) {
408 // bypassSlowDivision may create new BBs, but we don't want to reapply the
409 // optimization to those blocks.
410 BasicBlock* Next = BB->getNextNode();
411 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
412 BB = Next;
413 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000414 }
415
416 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000417 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000418 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000419
Devang Patel53771ba2011-08-18 00:50:51 +0000420 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000421 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000422 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000423 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000424
Geoff Berry5d534b62017-02-21 18:53:14 +0000425 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000426 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000427
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000428 // Split some critical edges where one of the sources is an indirect branch,
429 // to help generate sane code for PHIs involving such edges.
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000430 EverMadeChange |= SplitIndirectBrCriticalEdges(F);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000431
Chris Lattnerc3748562007-04-02 01:35:34 +0000432 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000433 while (MadeChange) {
434 MadeChange = false;
Jun Bum Limdee55652017-04-03 19:20:07 +0000435 SeenChainsForSExt.clear();
436 ValToSExtendedUses.clear();
437 RemovedInsts.clear();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000438 LargeOffsetGEPMap.clear();
439 LargeOffsetGEPID.clear();
Hans Wennborg02fbc712012-09-19 07:48:16 +0000440 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000441 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000442 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000443 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000444
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000445 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000446 if (ModifiedDTOnIteration)
447 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000448 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000449 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
450 MadeChange |= mergeSExts(F);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000451 if (!LargeOffsetGEPMap.empty())
452 MadeChange |= splitLargeGEPOffsets();
Jun Bum Limdee55652017-04-03 19:20:07 +0000453
454 // Really free removed instructions during promotion.
455 for (Instruction *I : RemovedInsts)
Reid Kleckner96ab8722017-05-18 17:24:10 +0000456 I->deleteValue();
Jun Bum Limdee55652017-04-03 19:20:07 +0000457
Chris Lattnerf2836d12007-03-31 04:06:36 +0000458 EverMadeChange |= MadeChange;
459 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000460
461 SunkAddrs.clear();
462
Cameron Zwarich338d3622011-03-11 21:52:04 +0000463 if (!DisableBranchOpts) {
464 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000465 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000466 for (BasicBlock &BB : F) {
467 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
468 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000469 if (!MadeChange) continue;
470
471 for (SmallVectorImpl<BasicBlock*>::iterator
472 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
473 if (pred_begin(*II) == pred_end(*II))
474 WorkList.insert(*II);
475 }
476
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000477 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000478 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000479 while (!WorkList.empty()) {
480 BasicBlock *BB = *WorkList.begin();
481 WorkList.erase(BB);
482 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
483
484 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000485
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000486 for (SmallVectorImpl<BasicBlock*>::iterator
487 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
488 if (pred_begin(*II) == pred_end(*II))
489 WorkList.insert(*II);
490 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000491
Nadav Rotem70409992012-08-14 05:19:07 +0000492 // Merge pairs of basic blocks with unconditional branches, connected by
493 // a single edge.
494 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000495 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000496
Cameron Zwarich338d3622011-03-11 21:52:04 +0000497 EverMadeChange |= MadeChange;
498 }
499
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000500 if (!DisableGCOpts) {
501 SmallVector<Instruction *, 2> Statepoints;
502 for (BasicBlock &BB : F)
503 for (Instruction &I : BB)
504 if (isStatepoint(I))
505 Statepoints.push_back(&I);
506 for (auto &I : Statepoints)
507 EverMadeChange |= simplifyOffsetableRelocate(*I);
508 }
509
Chris Lattnerf2836d12007-03-31 04:06:36 +0000510 return EverMadeChange;
511}
512
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000513/// Merge basic blocks which are connected by a single edge, where one of the
514/// basic blocks has a single successor pointing to the other basic block,
515/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000516bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000517 bool Changed = false;
518 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000519 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000520 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000521 // If the destination block has a single pred, then this is a trivial
522 // edge, just collapse it.
523 BasicBlock *SinglePred = BB->getSinglePredecessor();
524
Evan Cheng64a223a2012-09-28 23:58:57 +0000525 // Don't merge if BB's address is taken.
526 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000527
528 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
529 if (Term && !Term->isConditional()) {
530 Changed = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000531 LLVM_DEBUG(dbgs() << "To merge:\n" << *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000532 // Remember if SinglePred was the entry block of the function.
533 // If so, we will need to move BB back to the entry position.
534 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000535 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000536
537 if (isEntry && BB != &BB->getParent()->getEntryBlock())
538 BB->moveBefore(&BB->getParent()->getEntryBlock());
539
540 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000541 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000542 }
543 }
544 return Changed;
545}
546
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000547/// Find a destination block from BB if BB is mergeable empty block.
548BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
549 // If this block doesn't end with an uncond branch, ignore it.
550 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
551 if (!BI || !BI->isUnconditional())
552 return nullptr;
553
554 // If the instruction before the branch (skipping debug info) isn't a phi
555 // node, then other stuff is happening here.
556 BasicBlock::iterator BBI = BI->getIterator();
557 if (BBI != BB->begin()) {
558 --BBI;
559 while (isa<DbgInfoIntrinsic>(BBI)) {
560 if (BBI == BB->begin())
561 break;
562 --BBI;
563 }
564 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
565 return nullptr;
566 }
567
568 // Do not break infinite loops.
569 BasicBlock *DestBB = BI->getSuccessor(0);
570 if (DestBB == BB)
571 return nullptr;
572
573 if (!canMergeBlocks(BB, DestBB))
574 DestBB = nullptr;
575
576 return DestBB;
577}
578
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000579/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
580/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
581/// edges in ways that are non-optimal for isel. Start by eliminating these
582/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000583bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000584 SmallPtrSet<BasicBlock *, 16> Preheaders;
585 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
586 while (!LoopList.empty()) {
587 Loop *L = LoopList.pop_back_val();
588 LoopList.insert(LoopList.end(), L->begin(), L->end());
589 if (BasicBlock *Preheader = L->getLoopPreheader())
590 Preheaders.insert(Preheader);
591 }
592
Chris Lattnerc3748562007-04-02 01:35:34 +0000593 bool MadeChange = false;
594 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000595 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000596 BasicBlock *BB = &*I++;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000597 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
598 if (!DestBB ||
599 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000600 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000601
Sanjay Patelfc580a62015-09-21 23:03:16 +0000602 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000603 MadeChange = true;
604 }
605 return MadeChange;
606}
607
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000608bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
609 BasicBlock *DestBB,
610 bool isPreheader) {
611 // Do not delete loop preheaders if doing so would create a critical edge.
612 // Loop preheaders can be good locations to spill registers. If the
613 // preheader is deleted and we create a critical edge, registers may be
614 // spilled in the loop body instead.
615 if (!DisablePreheaderProtect && isPreheader &&
616 !(BB->getSinglePredecessor() &&
617 BB->getSinglePredecessor()->getSingleSuccessor()))
618 return false;
619
620 // Try to skip merging if the unique predecessor of BB is terminated by a
621 // switch or indirect branch instruction, and BB is used as an incoming block
622 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
623 // add COPY instructions in the predecessor of BB instead of BB (if it is not
624 // merged). Note that the critical edge created by merging such blocks wont be
625 // split in MachineSink because the jump table is not analyzable. By keeping
626 // such empty block (BB), ISel will place COPY instructions in BB, not in the
627 // predecessor of BB.
628 BasicBlock *Pred = BB->getUniquePredecessor();
629 if (!Pred ||
630 !(isa<SwitchInst>(Pred->getTerminator()) ||
631 isa<IndirectBrInst>(Pred->getTerminator())))
632 return true;
633
634 if (BB->getTerminator() != BB->getFirstNonPHI())
635 return true;
636
637 // We use a simple cost heuristic which determine skipping merging is
638 // profitable if the cost of skipping merging is less than the cost of
639 // merging : Cost(skipping merging) < Cost(merging BB), where the
640 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
641 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
642 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
643 // Freq(Pred) / Freq(BB) > 2.
644 // Note that if there are multiple empty blocks sharing the same incoming
645 // value for the PHIs in the DestBB, we consider them together. In such
646 // case, Cost(merging BB) will be the sum of their frequencies.
647
648 if (!isa<PHINode>(DestBB->begin()))
649 return true;
650
651 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
652
653 // Find all other incoming blocks from which incoming values of all PHIs in
654 // DestBB are the same as the ones from BB.
655 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
656 ++PI) {
657 BasicBlock *DestBBPred = *PI;
658 if (DestBBPred == BB)
659 continue;
660
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000661 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
662 return DestPN.getIncomingValueForBlock(BB) ==
663 DestPN.getIncomingValueForBlock(DestBBPred);
664 }))
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000665 SameIncomingValueBBs.insert(DestBBPred);
666 }
667
668 // See if all BB's incoming values are same as the value from Pred. In this
669 // case, no reason to skip merging because COPYs are expected to be place in
670 // Pred already.
671 if (SameIncomingValueBBs.count(Pred))
672 return true;
673
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000674 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
675 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
676
677 for (auto SameValueBB : SameIncomingValueBBs)
678 if (SameValueBB->getUniquePredecessor() == Pred &&
679 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
680 BBFreq += BFI->getBlockFreq(SameValueBB);
681
682 return PredFreq.getFrequency() <=
683 BBFreq.getFrequency() * FreqRatioToSkipMerge;
684}
685
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000686/// Return true if we can merge BB into DestBB if there is a single
687/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000688/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000689bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000690 const BasicBlock *DestBB) const {
691 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
692 // the successor. If there are more complex condition (e.g. preheaders),
693 // don't mess around with them.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000694 for (const PHINode &PN : BB->phis()) {
695 for (const User *U : PN.users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000696 const Instruction *UI = cast<Instruction>(U);
697 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000698 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000699 // If User is inside DestBB block and it is a PHINode then check
700 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000701 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000702 if (UI->getParent() == DestBB) {
703 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000704 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
705 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
706 if (Insn && Insn->getParent() == BB &&
707 Insn->getParent() != UPN->getIncomingBlock(I))
708 return false;
709 }
710 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000711 }
712 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000713
Chris Lattnerc3748562007-04-02 01:35:34 +0000714 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
715 // and DestBB may have conflicting incoming values for the block. If so, we
716 // can't merge the block.
717 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
718 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000719
Chris Lattnerc3748562007-04-02 01:35:34 +0000720 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000721 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000722 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
723 // It is faster to get preds from a PHI than with pred_iterator.
724 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
725 BBPreds.insert(BBPN->getIncomingBlock(i));
726 } else {
727 BBPreds.insert(pred_begin(BB), pred_end(BB));
728 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000729
Chris Lattnerc3748562007-04-02 01:35:34 +0000730 // Walk the preds of DestBB.
731 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
732 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
733 if (BBPreds.count(Pred)) { // Common predecessor?
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000734 for (const PHINode &PN : DestBB->phis()) {
735 const Value *V1 = PN.getIncomingValueForBlock(Pred);
736 const Value *V2 = PN.getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000737
Chris Lattnerc3748562007-04-02 01:35:34 +0000738 // If V2 is a phi node in BB, look up what the mapped value will be.
739 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
740 if (V2PN->getParent() == BB)
741 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000742
Chris Lattnerc3748562007-04-02 01:35:34 +0000743 // If there is a conflict, bail out.
744 if (V1 != V2) return false;
745 }
746 }
747 }
748
749 return true;
750}
751
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000752/// Eliminate a basic block that has only phi's and an unconditional branch in
753/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000754void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000755 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
756 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000757
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000758 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
759 << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000760
Chris Lattnerc3748562007-04-02 01:35:34 +0000761 // If the destination block has a single pred, then this is a trivial edge,
762 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000763 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000764 if (SinglePred != DestBB) {
765 // Remember if SinglePred was the entry block of the function. If so, we
766 // will need to move BB back to the entry position.
767 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Balaram Makam32bcb5d2017-10-27 00:35:18 +0000768 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000769
Chris Lattner8a172da2008-11-28 19:54:49 +0000770 if (isEntry && BB != &BB->getParent()->getEntryBlock())
771 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000772
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000773 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000774 return;
775 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000776 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000777
Chris Lattnerc3748562007-04-02 01:35:34 +0000778 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
779 // to handle the new incoming edges it is about to have.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000780 for (PHINode &PN : DestBB->phis()) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000781 // Remove the incoming value for BB, and remember it.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000782 Value *InVal = PN.removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000783
Chris Lattnerc3748562007-04-02 01:35:34 +0000784 // Two options: either the InVal is a phi node defined in BB or it is some
785 // value that dominates BB.
786 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
787 if (InValPhi && InValPhi->getParent() == BB) {
788 // Add all of the input values of the input PHI as inputs of this phi.
789 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000790 PN.addIncoming(InValPhi->getIncomingValue(i),
791 InValPhi->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000792 } else {
793 // Otherwise, add one instance of the dominating value for each edge that
794 // we will be adding.
795 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
796 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000797 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000798 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000799 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000800 PN.addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000801 }
802 }
803 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000804
Chris Lattnerc3748562007-04-02 01:35:34 +0000805 // The PHIs are now updated, change everything that refers to BB to use
806 // DestBB and remove BB.
807 BB->replaceAllUsesWith(DestBB);
808 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000809 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000810
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000811 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000812}
813
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000814// Computes a map of base pointer relocation instructions to corresponding
815// derived pointer relocation instructions given a vector of all relocate calls
816static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000817 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
818 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
819 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000820 // Collect information in two maps: one primarily for locating the base object
821 // while filling the second map; the second map is the final structure holding
822 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000823 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
824 for (auto *ThisRelocate : AllRelocateCalls) {
825 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
826 ThisRelocate->getDerivedPtrIndex());
827 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000828 }
829 for (auto &Item : RelocateIdxMap) {
830 std::pair<unsigned, unsigned> Key = Item.first;
831 if (Key.first == Key.second)
832 // Base relocation: nothing to insert
833 continue;
834
Manuel Jacob83eefa62016-01-05 04:03:00 +0000835 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000836 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000837
838 // We're iterating over RelocateIdxMap so we cannot modify it.
839 auto MaybeBase = RelocateIdxMap.find(BaseKey);
840 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000841 // TODO: We might want to insert a new base object relocate and gep off
842 // that, if there are enough derived object relocates.
843 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000844
845 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000846 }
847}
848
849// Accepts a GEP and extracts the operands into a vector provided they're all
850// small integer constants
851static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
852 SmallVectorImpl<Value *> &OffsetV) {
853 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
854 // Only accept small constant integer operands
855 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
856 if (!Op || Op->getZExtValue() > 20)
857 return false;
858 }
859
860 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
861 OffsetV.push_back(GEP->getOperand(i));
862 return true;
863}
864
865// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
866// replace, computes a replacement, and affects it.
867static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000868simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
869 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000870 bool MadeChange = false;
Serguei Katkov9e5604d2017-08-17 05:48:30 +0000871 // We must ensure the relocation of derived pointer is defined after
872 // relocation of base pointer. If we find a relocation corresponding to base
873 // defined earlier than relocation of base then we move relocation of base
874 // right before found relocation. We consider only relocation in the same
875 // basic block as relocation of base. Relocations from other basic block will
876 // be skipped by optimization and we do not care about them.
877 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
878 &*R != RelocatedBase; ++R)
879 if (auto RI = dyn_cast<GCRelocateInst>(R))
880 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
881 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
882 RelocatedBase->moveBefore(RI);
883 break;
884 }
885
Manuel Jacob83eefa62016-01-05 04:03:00 +0000886 for (GCRelocateInst *ToReplace : Targets) {
887 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000888 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000889 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000890 // A duplicate relocate call. TODO: coalesce duplicates.
891 continue;
892 }
893
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000894 if (RelocatedBase->getParent() != ToReplace->getParent()) {
895 // Base and derived relocates are in different basic blocks.
896 // In this case transform is only valid when base dominates derived
897 // relocate. However it would be too expensive to check dominance
898 // for each such relocate, so we skip the whole transformation.
899 continue;
900 }
901
Manuel Jacob83eefa62016-01-05 04:03:00 +0000902 Value *Base = ToReplace->getBasePtr();
903 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000904 if (!Derived || Derived->getPointerOperand() != Base)
905 continue;
906
907 SmallVector<Value *, 2> OffsetV;
908 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
909 continue;
910
911 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000912 assert(RelocatedBase->getNextNode() &&
913 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000914
915 // Insert after RelocatedBase
916 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000917 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000918
919 // If gc_relocate does not match the actual type, cast it to the right type.
920 // In theory, there must be a bitcast after gc_relocate if the type does not
921 // match, and we should reuse it to get the derived pointer. But it could be
922 // cases like this:
923 // bb1:
924 // ...
925 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
926 // br label %merge
927 //
928 // bb2:
929 // ...
930 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
931 // br label %merge
932 //
933 // merge:
934 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
935 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
936 //
937 // In this case, we can not find the bitcast any more. So we insert a new bitcast
938 // no matter there is already one or not. In this way, we can handle all cases, and
939 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000940 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000941 if (RelocatedBase->getType() != Base->getType()) {
942 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000943 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000944 }
David Blaikie68d535c2015-03-24 22:38:16 +0000945 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000946 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000947 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000948 // If the newly generated derived pointer's type does not match the original derived
949 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000950 Value *ActualReplacement = Replacement;
951 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000952 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000953 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000954 }
955 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000956 ToReplace->eraseFromParent();
957
958 MadeChange = true;
959 }
960 return MadeChange;
961}
962
963// Turns this:
964//
965// %base = ...
966// %ptr = gep %base + 15
967// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
968// %base' = relocate(%tok, i32 4, i32 4)
969// %ptr' = relocate(%tok, i32 4, i32 5)
970// %val = load %ptr'
971//
972// into this:
973//
974// %base = ...
975// %ptr = gep %base + 15
976// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
977// %base' = gc.relocate(%tok, i32 4, i32 4)
978// %ptr' = gep %base' + 15
979// %val = load %ptr'
980bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
981 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000982 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000983
984 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000985 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000986 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000987 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000988
989 // We need atleast one base pointer relocation + one derived pointer
990 // relocation to mangle
991 if (AllRelocateCalls.size() < 2)
992 return false;
993
994 // RelocateInstMap is a mapping from the base relocate instruction to the
995 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +0000996 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000997 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
998 if (RelocateInstMap.empty())
999 return false;
1000
1001 for (auto &Item : RelocateInstMap)
1002 // Item.first is the RelocatedBase to offset against
1003 // Item.second is the vector of Targets to replace
1004 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1005 return MadeChange;
1006}
1007
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001008/// SinkCast - Sink the specified cast instruction into its user blocks
1009static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001010 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001011
Chris Lattnerf2836d12007-03-31 04:06:36 +00001012 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001013 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001014
Chris Lattnerf2836d12007-03-31 04:06:36 +00001015 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001016 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001017 UI != E; ) {
1018 Use &TheUse = UI.getUse();
1019 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001020
Chris Lattnerf2836d12007-03-31 04:06:36 +00001021 // Figure out which BB this cast is used in. For PHI's this is the
1022 // appropriate predecessor block.
1023 BasicBlock *UserBB = User->getParent();
1024 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001025 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001026 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001027
Chris Lattnerf2836d12007-03-31 04:06:36 +00001028 // Preincrement use iterator so we don't invalidate it.
1029 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001030
David Majnemer0c80e2e2016-04-27 19:36:38 +00001031 // The first insertion point of a block containing an EH pad is after the
1032 // pad. If the pad is the user, we cannot sink the cast past the pad.
1033 if (User->isEHPad())
1034 continue;
1035
Andrew Kaylord0430e82015-11-23 19:16:15 +00001036 // If the block selected to receive the cast is an EH pad that does not
1037 // allow non-PHI instructions before the terminator, we can't sink the
1038 // cast.
1039 if (UserBB->getTerminator()->isEHPad())
1040 continue;
1041
Chris Lattnerf2836d12007-03-31 04:06:36 +00001042 // If this user is in the same block as the cast, don't change the cast.
1043 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001044
Chris Lattnerf2836d12007-03-31 04:06:36 +00001045 // If we have already inserted a cast into this block, use it.
1046 CastInst *&InsertedCast = InsertedCasts[UserBB];
1047
1048 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001049 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001050 assert(InsertPt != UserBB->end());
1051 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1052 CI->getType(), "", &*InsertPt);
Vedant Kumar9374c042018-05-23 22:03:48 +00001053 InsertedCast->setDebugLoc(CI->getDebugLoc());
Chris Lattnerf2836d12007-03-31 04:06:36 +00001054 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001055
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001056 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001057 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001058 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001059 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001060 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001061
Chris Lattnerf2836d12007-03-31 04:06:36 +00001062 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001063 if (CI->use_empty()) {
Adrian Prantl261ac8b2017-11-03 21:55:03 +00001064 salvageDebugInfo(*CI);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001065 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001066 MadeChange = true;
1067 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001068
Chris Lattnerf2836d12007-03-31 04:06:36 +00001069 return MadeChange;
1070}
1071
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001072/// If the specified cast instruction is a noop copy (e.g. it's casting from
1073/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1074/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001075///
1076/// Return true if any changes are made.
Mehdi Amini44ede332015-07-09 02:09:04 +00001077static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1078 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001079 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1080 // than sinking only nop casts, but is helpful on some platforms.
1081 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1082 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1083 ASC->getDestAddressSpace()))
1084 return false;
1085 }
1086
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001087 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001088 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1089 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001090
1091 // This is an fp<->int conversion?
1092 if (SrcVT.isInteger() != DstVT.isInteger())
1093 return false;
1094
1095 // If this is an extension, it will be a zero or sign extension, which
1096 // isn't a noop.
1097 if (SrcVT.bitsLT(DstVT)) return false;
1098
1099 // If these values will be promoted, find out what they will be promoted
1100 // to. This helps us consider truncates on PPC as noop copies when they
1101 // are.
1102 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1103 TargetLowering::TypePromoteInteger)
1104 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1105 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1106 TargetLowering::TypePromoteInteger)
1107 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1108
1109 // If, after promotion, these are the same types, this is a noop copy.
1110 if (SrcVT != DstVT)
1111 return false;
1112
1113 return SinkCast(CI);
1114}
1115
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001116/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1117/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001118///
1119/// Return true if any changes were made.
1120static bool CombineUAddWithOverflow(CmpInst *CI) {
1121 Value *A, *B;
1122 Instruction *AddI;
1123 if (!match(CI,
1124 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1125 return false;
1126
1127 Type *Ty = AddI->getType();
1128 if (!isa<IntegerType>(Ty))
1129 return false;
1130
1131 // We don't want to move around uses of condition values this late, so we we
1132 // check if it is legal to create the call to the intrinsic in the basic
1133 // block containing the icmp:
1134
1135 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1136 return false;
1137
1138#ifndef NDEBUG
1139 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1140 // for now:
1141 if (AddI->hasOneUse())
1142 assert(*AddI->user_begin() == CI && "expected!");
1143#endif
1144
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001145 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001146 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1147
1148 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1149
1150 auto *UAddWithOverflow =
1151 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1152 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1153 auto *Overflow =
1154 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1155
1156 CI->replaceAllUsesWith(Overflow);
1157 AddI->replaceAllUsesWith(UAdd);
1158 CI->eraseFromParent();
1159 AddI->eraseFromParent();
1160 return true;
1161}
1162
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001163/// Sink the given CmpInst into user blocks to reduce the number of virtual
1164/// registers that must be created and coalesced. This is a clear win except on
1165/// targets with multiple condition code registers (PowerPC), where it might
1166/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001167///
1168/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001169static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001170 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001171
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001172 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001173 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001174 return false;
1175
1176 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001177 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001178
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001179 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001180 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001181 UI != E; ) {
1182 Use &TheUse = UI.getUse();
1183 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001184
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001185 // Preincrement use iterator so we don't invalidate it.
1186 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001187
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001188 // Don't bother for PHI nodes.
1189 if (isa<PHINode>(User))
1190 continue;
1191
1192 // Figure out which BB this cmp is used in.
1193 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001194
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001195 // If this user is in the same block as the cmp, don't change the cmp.
1196 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001197
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001198 // If we have already inserted a cmp into this block, use it.
1199 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1200
1201 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001202 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001203 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001204 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001205 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1206 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001207 // Propagate the debug info.
1208 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001209 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001210
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001211 // Replace a use of the cmp with a use of the new cmp.
1212 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001213 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001214 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001215 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001216
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001217 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001218 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001219 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001220 MadeChange = true;
1221 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001222
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001223 return MadeChange;
1224}
1225
Peter Zotovf87e5502016-04-03 17:11:53 +00001226static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001227 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001228 return true;
1229
1230 if (CombineUAddWithOverflow(CI))
1231 return true;
1232
1233 return false;
1234}
1235
Geoff Berry5d534b62017-02-21 18:53:14 +00001236/// Duplicate and sink the given 'and' instruction into user blocks where it is
1237/// used in a compare to allow isel to generate better code for targets where
1238/// this operation can be combined.
1239///
1240/// Return true if any changes are made.
1241static bool sinkAndCmp0Expression(Instruction *AndI,
1242 const TargetLowering &TLI,
1243 SetOfInstrs &InsertedInsts) {
1244 // Double-check that we're not trying to optimize an instruction that was
1245 // already optimized by some other part of this pass.
1246 assert(!InsertedInsts.count(AndI) &&
1247 "Attempting to optimize already optimized and instruction");
1248 (void) InsertedInsts;
1249
1250 // Nothing to do for single use in same basic block.
1251 if (AndI->hasOneUse() &&
1252 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1253 return false;
1254
1255 // Try to avoid cases where sinking/duplicating is likely to increase register
1256 // pressure.
1257 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1258 !isa<ConstantInt>(AndI->getOperand(1)) &&
1259 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1260 return false;
1261
1262 for (auto *U : AndI->users()) {
1263 Instruction *User = cast<Instruction>(U);
1264
1265 // Only sink for and mask feeding icmp with 0.
1266 if (!isa<ICmpInst>(User))
1267 return false;
1268
1269 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1270 if (!CmpC || !CmpC->isZero())
1271 return false;
1272 }
1273
1274 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1275 return false;
1276
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001277 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1278 LLVM_DEBUG(AndI->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001279
1280 // Push the 'and' into the same block as the icmp 0. There should only be
1281 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1282 // others, so we don't need to keep track of which BBs we insert into.
1283 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1284 UI != E; ) {
1285 Use &TheUse = UI.getUse();
1286 Instruction *User = cast<Instruction>(*UI);
1287
1288 // Preincrement use iterator so we don't invalidate it.
1289 ++UI;
1290
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001291 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
Geoff Berry5d534b62017-02-21 18:53:14 +00001292
1293 // Keep the 'and' in the same place if the use is already in the same block.
1294 Instruction *InsertPt =
1295 User->getParent() == AndI->getParent() ? AndI : User;
1296 Instruction *InsertedAnd =
1297 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1298 AndI->getOperand(1), "", InsertPt);
1299 // Propagate the debug info.
1300 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1301
1302 // Replace a use of the 'and' with a use of the new 'and'.
1303 TheUse = InsertedAnd;
1304 ++NumAndUses;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001305 LLVM_DEBUG(User->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001306 }
1307
1308 // We removed all uses, nuke the and.
1309 AndI->eraseFromParent();
1310 return true;
1311}
1312
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001313/// Check if the candidates could be combined with a shift instruction, which
1314/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001315/// 1. Truncate instruction
1316/// 2. And instruction and the imm is a mask of the low bits:
1317/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001318static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001319 if (!isa<TruncInst>(User)) {
1320 if (User->getOpcode() != Instruction::And ||
1321 !isa<ConstantInt>(User->getOperand(1)))
1322 return false;
1323
Quentin Colombetd4f44692014-04-22 01:20:34 +00001324 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001325
Quentin Colombetd4f44692014-04-22 01:20:34 +00001326 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001327 return false;
1328 }
1329 return true;
1330}
1331
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001332/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001333static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001334SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1335 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001336 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001337 BasicBlock *UserBB = User->getParent();
1338 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1339 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1340 bool MadeChange = false;
1341
1342 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1343 TruncE = TruncI->user_end();
1344 TruncUI != TruncE;) {
1345
1346 Use &TruncTheUse = TruncUI.getUse();
1347 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1348 // Preincrement use iterator so we don't invalidate it.
1349
1350 ++TruncUI;
1351
1352 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1353 if (!ISDOpcode)
1354 continue;
1355
Tim Northovere2239ff2014-07-29 10:20:22 +00001356 // If the use is actually a legal node, there will not be an
1357 // implicit truncate.
1358 // FIXME: always querying the result type is just an
1359 // approximation; some nodes' legality is determined by the
1360 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001361 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001362 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001363 continue;
1364
1365 // Don't bother for PHI nodes.
1366 if (isa<PHINode>(TruncUser))
1367 continue;
1368
1369 BasicBlock *TruncUserBB = TruncUser->getParent();
1370
1371 if (UserBB == TruncUserBB)
1372 continue;
1373
1374 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1375 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1376
1377 if (!InsertedShift && !InsertedTrunc) {
1378 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001379 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001380 // Sink the shift
1381 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001382 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1383 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001384 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001385 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1386 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001387
1388 // Sink the trunc
1389 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1390 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001391 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001392
1393 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001394 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001395
1396 MadeChange = true;
1397
1398 TruncTheUse = InsertedTrunc;
1399 }
1400 }
1401 return MadeChange;
1402}
1403
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001404/// Sink the shift *right* instruction into user blocks if the uses could
1405/// potentially be combined with this shift instruction and generate BitExtract
1406/// instruction. It will only be applied if the architecture supports BitExtract
1407/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001408/// BB1:
1409/// %x.extract.shift = lshr i64 %arg1, 32
1410/// BB2:
1411/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1412/// ==>
1413///
1414/// BB2:
1415/// %x.extract.shift.1 = lshr i64 %arg1, 32
1416/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1417///
1418/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1419/// instruction.
1420/// Return true if any changes are made.
1421static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001422 const TargetLowering &TLI,
1423 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001424 BasicBlock *DefBB = ShiftI->getParent();
1425
1426 /// Only insert instructions in each block once.
1427 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1428
Mehdi Amini44ede332015-07-09 02:09:04 +00001429 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001430
1431 bool MadeChange = false;
1432 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1433 UI != E;) {
1434 Use &TheUse = UI.getUse();
1435 Instruction *User = cast<Instruction>(*UI);
1436 // Preincrement use iterator so we don't invalidate it.
1437 ++UI;
1438
1439 // Don't bother for PHI nodes.
1440 if (isa<PHINode>(User))
1441 continue;
1442
1443 if (!isExtractBitsCandidateUse(User))
1444 continue;
1445
1446 BasicBlock *UserBB = User->getParent();
1447
1448 if (UserBB == DefBB) {
1449 // If the shift and truncate instruction are in the same BB. The use of
1450 // the truncate(TruncUse) may still introduce another truncate if not
1451 // legal. In this case, we would like to sink both shift and truncate
1452 // instruction to the BB of TruncUse.
1453 // for example:
1454 // BB1:
1455 // i64 shift.result = lshr i64 opnd, imm
1456 // trunc.result = trunc shift.result to i16
1457 //
1458 // BB2:
1459 // ----> We will have an implicit truncate here if the architecture does
1460 // not have i16 compare.
1461 // cmp i16 trunc.result, opnd2
1462 //
1463 if (isa<TruncInst>(User) && shiftIsLegal
1464 // If the type of the truncate is legal, no trucate will be
1465 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001466 &&
1467 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001468 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001469 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001470
1471 continue;
1472 }
1473 // If we have already inserted a shift into this block, use it.
1474 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1475
1476 if (!InsertedShift) {
1477 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001478 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001479
1480 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001481 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1482 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001483 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001484 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1485 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001486
1487 MadeChange = true;
1488 }
1489
1490 // Replace a use of the shift with a use of the new shift.
1491 TheUse = InsertedShift;
1492 }
1493
1494 // If we removed all uses, nuke the shift.
1495 if (ShiftI->use_empty())
1496 ShiftI->eraseFromParent();
1497
1498 return MadeChange;
1499}
1500
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001501/// If counting leading or trailing zeros is an expensive operation and a zero
1502/// input is defined, add a check for zero to avoid calling the intrinsic.
1503///
1504/// We want to transform:
1505/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1506///
1507/// into:
1508/// entry:
1509/// %cmpz = icmp eq i64 %A, 0
1510/// br i1 %cmpz, label %cond.end, label %cond.false
1511/// cond.false:
1512/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1513/// br label %cond.end
1514/// cond.end:
1515/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1516///
1517/// If the transform is performed, return true and set ModifiedDT to true.
1518static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1519 const TargetLowering *TLI,
1520 const DataLayout *DL,
1521 bool &ModifiedDT) {
1522 if (!TLI || !DL)
1523 return false;
1524
1525 // If a zero input is undefined, it doesn't make sense to despeculate that.
1526 if (match(CountZeros->getOperand(1), m_One()))
1527 return false;
1528
1529 // If it's cheap to speculate, there's nothing to do.
1530 auto IntrinsicID = CountZeros->getIntrinsicID();
1531 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1532 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1533 return false;
1534
1535 // Only handle legal scalar cases. Anything else requires too much work.
1536 Type *Ty = CountZeros->getType();
1537 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001538 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001539 return false;
1540
1541 // The intrinsic will be sunk behind a compare against zero and branch.
1542 BasicBlock *StartBlock = CountZeros->getParent();
1543 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1544
1545 // Create another block after the count zero intrinsic. A PHI will be added
1546 // in this block to select the result of the intrinsic or the bit-width
1547 // constant if the input to the intrinsic is zero.
1548 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1549 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1550
1551 // Set up a builder to create a compare, conditional branch, and PHI.
1552 IRBuilder<> Builder(CountZeros->getContext());
1553 Builder.SetInsertPoint(StartBlock->getTerminator());
1554 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1555
1556 // Replace the unconditional branch that was created by the first split with
1557 // a compare against zero and a conditional branch.
1558 Value *Zero = Constant::getNullValue(Ty);
1559 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1560 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1561 StartBlock->getTerminator()->eraseFromParent();
1562
1563 // Create a PHI in the end block to select either the output of the intrinsic
1564 // or the bit width of the operand.
1565 Builder.SetInsertPoint(&EndBlock->front());
1566 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1567 CountZeros->replaceAllUsesWith(PN);
1568 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1569 PN->addIncoming(BitWidth, StartBlock);
1570 PN->addIncoming(CountZeros, CallBlock);
1571
1572 // We are explicitly handling the zero case, so we can set the intrinsic's
1573 // undefined zero argument to 'true'. This will also prevent reprocessing the
1574 // intrinsic; we only despeculate when a zero input is defined.
1575 CountZeros->setArgOperand(1, Builder.getTrue());
1576 ModifiedDT = true;
1577 return true;
1578}
1579
Sanjay Patel3b8974b2017-06-08 20:00:09 +00001580bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001581 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001582
Chris Lattner7a277142011-01-15 07:14:54 +00001583 // Lower inline assembly if we can.
1584 // If we found an inline asm expession, and if the target knows how to
1585 // lower it to normal LLVM code, do so now.
1586 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1587 if (TLI->ExpandInlineAsm(CI)) {
1588 // Avoid invalidating the iterator.
1589 CurInstIterator = BB->begin();
1590 // Avoid processing instructions out of order, which could cause
1591 // reuse before a value is defined.
1592 SunkAddrs.clear();
1593 return true;
1594 }
1595 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001596 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001597 return true;
1598 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001599
John Brawn0dbcd652015-03-18 12:01:59 +00001600 // Align the pointer arguments to this call if the target thinks it's a good
1601 // idea
1602 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001603 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001604 for (auto &Arg : CI->arg_operands()) {
1605 // We want to align both objects whose address is used directly and
1606 // objects whose address is used in casts and GEPs, though it only makes
1607 // sense for GEPs if the offset is a multiple of the desired alignment and
1608 // if size - offset meets the size threshold.
1609 if (!Arg->getType()->isPointerTy())
1610 continue;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001611 APInt Offset(DL->getIndexSizeInBits(
Mehdi Amini4fe37982015-07-07 18:45:17 +00001612 cast<PointerType>(Arg->getType())->getAddressSpace()),
1613 0);
1614 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001615 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001616 if ((Offset2 & (PrefAlign-1)) != 0)
1617 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001618 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001619 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1620 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001621 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001622 // Global variables can only be aligned if they are defined in this
1623 // object (i.e. they are uniquely initialized in this object), and
1624 // over-aligning global variables that have an explicit section is
1625 // forbidden.
1626 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001627 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001628 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001629 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001630 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001631 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001632 }
1633 // If this is a memcpy (or similar) then we may be able to improve the
1634 // alignment
1635 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Daniel Neilsonbe58a222018-01-31 17:24:53 +00001636 unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
1637 if (DestAlign > MI->getDestAlignment())
1638 MI->setDestAlignment(DestAlign);
1639 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1640 unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
1641 if (SrcAlign > MTI->getSourceAlignment())
1642 MTI->setSourceAlignment(SrcAlign);
1643 }
John Brawn0dbcd652015-03-18 12:01:59 +00001644 }
1645 }
1646
Philip Reamesac115ed2016-03-09 23:13:12 +00001647 // If we have a cold call site, try to sink addressing computation into the
1648 // cold block. This interacts with our handling for loads and stores to
1649 // ensure that we can fold all uses of a potential addressing computation
1650 // into their uses. TODO: generalize this to work over profiling data
1651 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1652 for (auto &Arg : CI->arg_operands()) {
1653 if (!Arg->getType()->isPointerTy())
1654 continue;
1655 unsigned AS = Arg->getType()->getPointerAddressSpace();
1656 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1657 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001658
Eric Christopher4b7948e2010-03-11 02:41:03 +00001659 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001660 if (II) {
1661 switch (II->getIntrinsicID()) {
1662 default: break;
1663 case Intrinsic::objectsize: {
1664 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00001665 ConstantInt *RetVal =
1666 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001667 // Substituting this can cause recursive simplifications, which can
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001668 // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case
1669 // this
Sanjoy Das2cbeb002017-04-26 16:37:05 +00001670 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001671 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001672 WeakTrackingVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001673
Sanjay Patel545a4562016-01-20 18:59:16 +00001674 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001675
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001676 // If the iterator instruction was recursively deleted, start over at the
1677 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001678 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001679 CurInstIterator = BB->begin();
1680 SunkAddrs.clear();
1681 }
1682 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001683 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001684 case Intrinsic::aarch64_stlxr:
1685 case Intrinsic::aarch64_stxr: {
1686 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1687 if (!ExtVal || !ExtVal->hasOneUse() ||
1688 ExtVal->getParent() == CI->getParent())
1689 return false;
1690 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1691 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001692 // Mark this instruction as "inserted by CGP", so that other
1693 // optimizations don't touch it.
1694 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001695 return true;
1696 }
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001697 case Intrinsic::launder_invariant_group:
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001698 II->replaceAllUsesWith(II->getArgOperand(0));
1699 II->eraseFromParent();
1700 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001701
1702 case Intrinsic::cttz:
1703 case Intrinsic::ctlz:
1704 // If counting zeros is expensive, try to avoid it.
1705 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001706 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001707
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001708 if (TLI) {
1709 SmallVector<Value*, 2> PtrOps;
1710 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001711 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1712 while (!PtrOps.empty()) {
1713 Value *PtrVal = PtrOps.pop_back_val();
1714 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1715 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001716 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001717 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001718 }
Pete Cooper615fd892012-03-13 20:59:56 +00001719 }
1720
Eric Christopher4b7948e2010-03-11 02:41:03 +00001721 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001722 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001723
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001724 // Lower all default uses of _chk calls. This is very similar
1725 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001726 // to fortified library functions (e.g. __memcpy_chk) that have the default
1727 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001728 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001729 if (Value *V = Simplifier.optimizeCall(CI)) {
1730 CI->replaceAllUsesWith(V);
1731 CI->eraseFromParent();
1732 return true;
1733 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001734
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001735 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001736}
Chris Lattner1b93be52011-01-15 07:25:29 +00001737
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001738/// Look for opportunities to duplicate return instructions to the predecessor
1739/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001740/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001741/// bb0:
1742/// %tmp0 = tail call i32 @f0()
1743/// br label %return
1744/// bb1:
1745/// %tmp1 = tail call i32 @f1()
1746/// br label %return
1747/// bb2:
1748/// %tmp2 = tail call i32 @f2()
1749/// br label %return
1750/// return:
1751/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1752/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001753/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001754///
1755/// =>
1756///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001757/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001758/// bb0:
1759/// %tmp0 = tail call i32 @f0()
1760/// ret i32 %tmp0
1761/// bb1:
1762/// %tmp1 = tail call i32 @f1()
1763/// ret i32 %tmp1
1764/// bb2:
1765/// %tmp2 = tail call i32 @f2()
1766/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001767/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001768bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001769 if (!TLI)
1770 return false;
1771
Michael Kuperstein71321562016-09-07 20:29:49 +00001772 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1773 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001774 return false;
1775
Craig Topperc0196b12014-04-14 00:51:57 +00001776 PHINode *PN = nullptr;
1777 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001778 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001779 if (V) {
1780 BCI = dyn_cast<BitCastInst>(V);
1781 if (BCI)
1782 V = BCI->getOperand(0);
1783
1784 PN = dyn_cast<PHINode>(V);
1785 if (!PN)
1786 return false;
1787 }
Evan Cheng0663f232011-03-21 01:19:09 +00001788
Cameron Zwarich4649f172011-03-24 04:52:10 +00001789 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001790 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001791
Cameron Zwarich4649f172011-03-24 04:52:10 +00001792 // Make sure there are no instructions between the PHI and return, or that the
1793 // return is the first instruction in the block.
1794 if (PN) {
1795 BasicBlock::iterator BI = BB->begin();
1796 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001797 if (&*BI == BCI)
1798 // Also skip over the bitcast.
1799 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001800 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001801 return false;
1802 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001803 BasicBlock::iterator BI = BB->begin();
1804 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001805 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001806 return false;
1807 }
Evan Cheng0663f232011-03-21 01:19:09 +00001808
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001809 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1810 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001811 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001812 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001813 if (PN) {
1814 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1815 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1816 // Make sure the phi value is indeed produced by the tail call.
1817 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001818 TLI->mayBeEmittedAsTailCall(CI) &&
1819 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001820 TailCalls.push_back(CI);
1821 }
1822 } else {
1823 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001824 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001825 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001826 continue;
1827
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001828 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001829 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1830 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001831 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1832 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001833 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001834
Cameron Zwarich4649f172011-03-24 04:52:10 +00001835 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001836 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1837 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001838 TailCalls.push_back(CI);
1839 }
Evan Cheng0663f232011-03-21 01:19:09 +00001840 }
1841
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001842 bool Changed = false;
1843 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1844 CallInst *CI = TailCalls[i];
1845 CallSite CS(CI);
1846
1847 // Conservatively require the attributes of the call to match those of the
1848 // return. Ignore noalias because it doesn't affect the call sequence.
Reid Klecknerb5180542017-03-21 16:57:19 +00001849 AttributeList CalleeAttrs = CS.getAttributes();
1850 if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1851 .removeAttribute(Attribute::NoAlias) !=
1852 AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1853 .removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001854 continue;
1855
1856 // Make sure the call instruction is followed by an unconditional branch to
1857 // the return block.
1858 BasicBlock *CallBB = CI->getParent();
1859 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1860 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1861 continue;
1862
1863 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00001864 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001865 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001866 ++NumRetsDup;
1867 }
1868
1869 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001870 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001871 BB->eraseFromParent();
1872
1873 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001874}
1875
Chris Lattner728f9022008-11-25 07:09:13 +00001876//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001877// Memory Optimization
1878//===----------------------------------------------------------------------===//
1879
Chandler Carruthc8925912013-01-05 02:09:22 +00001880namespace {
1881
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001882/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00001883/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001884struct ExtAddrMode : public TargetLowering::AddrMode {
Eugene Zelenko900b6332017-08-29 22:32:07 +00001885 Value *BaseReg = nullptr;
1886 Value *ScaledReg = nullptr;
John Brawn736bf002017-10-03 13:08:22 +00001887 Value *OriginalValue = nullptr;
1888
1889 enum FieldName {
1890 NoField = 0x00,
1891 BaseRegField = 0x01,
1892 BaseGVField = 0x02,
1893 BaseOffsField = 0x04,
1894 ScaledRegField = 0x08,
1895 ScaleField = 0x10,
1896 MultipleFields = 0xff
1897 };
Eugene Zelenko900b6332017-08-29 22:32:07 +00001898
1899 ExtAddrMode() = default;
1900
Chandler Carruthc8925912013-01-05 02:09:22 +00001901 void print(raw_ostream &OS) const;
1902 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001903
John Brawn736bf002017-10-03 13:08:22 +00001904 FieldName compare(const ExtAddrMode &other) {
1905 // First check that the types are the same on each field, as differing types
1906 // is something we can't cope with later on.
1907 if (BaseReg && other.BaseReg &&
1908 BaseReg->getType() != other.BaseReg->getType())
1909 return MultipleFields;
1910 if (BaseGV && other.BaseGV &&
1911 BaseGV->getType() != other.BaseGV->getType())
1912 return MultipleFields;
1913 if (ScaledReg && other.ScaledReg &&
1914 ScaledReg->getType() != other.ScaledReg->getType())
1915 return MultipleFields;
1916
1917 // Check each field to see if it differs.
1918 unsigned Result = NoField;
1919 if (BaseReg != other.BaseReg)
1920 Result |= BaseRegField;
1921 if (BaseGV != other.BaseGV)
1922 Result |= BaseGVField;
1923 if (BaseOffs != other.BaseOffs)
1924 Result |= BaseOffsField;
1925 if (ScaledReg != other.ScaledReg)
1926 Result |= ScaledRegField;
1927 // Don't count 0 as being a different scale, because that actually means
1928 // unscaled (which will already be counted by having no ScaledReg).
1929 if (Scale && other.Scale && Scale != other.Scale)
1930 Result |= ScaleField;
1931
1932 if (countPopulation(Result) > 1)
1933 return MultipleFields;
1934 else
1935 return static_cast<FieldName>(Result);
1936 }
1937
John Brawn4b476482017-11-27 11:29:15 +00001938 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
1939 // with no offset.
John Brawn736bf002017-10-03 13:08:22 +00001940 bool isTrivial() {
John Brawn4b476482017-11-27 11:29:15 +00001941 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
1942 // trivial if at most one of these terms is nonzero, except that BaseGV and
1943 // BaseReg both being zero actually means a null pointer value, which we
1944 // consider to be 'non-zero' here.
1945 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
Chandler Carruthc8925912013-01-05 02:09:22 +00001946 }
John Brawn70cdb5b2017-11-24 14:10:45 +00001947
1948 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
1949 switch (Field) {
1950 default:
1951 return nullptr;
1952 case BaseRegField:
1953 return BaseReg;
1954 case BaseGVField:
1955 return BaseGV;
1956 case ScaledRegField:
1957 return ScaledReg;
1958 case BaseOffsField:
1959 return ConstantInt::get(IntPtrTy, BaseOffs);
1960 }
1961 }
1962
1963 void SetCombinedField(FieldName Field, Value *V,
1964 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
1965 switch (Field) {
1966 default:
1967 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
1968 break;
1969 case ExtAddrMode::BaseRegField:
1970 BaseReg = V;
1971 break;
1972 case ExtAddrMode::BaseGVField:
1973 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
1974 // in the BaseReg field.
1975 assert(BaseReg == nullptr);
1976 BaseReg = V;
1977 BaseGV = nullptr;
1978 break;
1979 case ExtAddrMode::ScaledRegField:
1980 ScaledReg = V;
1981 // If we have a mix of scaled and unscaled addrmodes then we want scale
1982 // to be the scale and not zero.
1983 if (!Scale)
1984 for (const ExtAddrMode &AM : AddrModes)
1985 if (AM.Scale) {
1986 Scale = AM.Scale;
1987 break;
1988 }
1989 break;
1990 case ExtAddrMode::BaseOffsField:
1991 // The offset is no longer a constant, so it goes in ScaledReg with a
1992 // scale of 1.
1993 assert(ScaledReg == nullptr);
1994 ScaledReg = V;
1995 Scale = 1;
1996 BaseOffs = 0;
1997 break;
1998 }
1999 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002000};
2001
Eugene Zelenko900b6332017-08-29 22:32:07 +00002002} // end anonymous namespace
2003
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002004#ifndef NDEBUG
2005static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2006 AM.print(OS);
2007 return OS;
2008}
2009#endif
2010
Aaron Ballman615eb472017-10-15 14:32:27 +00002011#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthc8925912013-01-05 02:09:22 +00002012void ExtAddrMode::print(raw_ostream &OS) const {
2013 bool NeedPlus = false;
2014 OS << "[";
2015 if (BaseGV) {
2016 OS << (NeedPlus ? " + " : "")
2017 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002018 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002019 NeedPlus = true;
2020 }
2021
Richard Trieuc0f91212014-05-30 03:15:17 +00002022 if (BaseOffs) {
2023 OS << (NeedPlus ? " + " : "")
2024 << BaseOffs;
2025 NeedPlus = true;
2026 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002027
2028 if (BaseReg) {
2029 OS << (NeedPlus ? " + " : "")
2030 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002031 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002032 NeedPlus = true;
2033 }
2034 if (Scale) {
2035 OS << (NeedPlus ? " + " : "")
2036 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002037 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002038 }
2039
2040 OS << ']';
2041}
2042
Yaron Kereneb2a2542016-01-29 20:50:44 +00002043LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002044 print(dbgs());
2045 dbgs() << '\n';
2046}
2047#endif
2048
Eugene Zelenko900b6332017-08-29 22:32:07 +00002049namespace {
2050
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002051/// This class provides transaction based operation on the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002052/// Every change made through this class is recorded in the internal state and
2053/// can be undone (rollback) until commit is called.
2054class TypePromotionTransaction {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002055 /// This represents the common interface of the individual transaction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002056 /// Each class implements the logic for doing one specific modification on
2057 /// the IR via the TypePromotionTransaction.
2058 class TypePromotionAction {
2059 protected:
2060 /// The Instruction modified.
2061 Instruction *Inst;
2062
2063 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002064 /// Constructor of the action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002065 /// The constructor performs the related action on the IR.
2066 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2067
Eugene Zelenko900b6332017-08-29 22:32:07 +00002068 virtual ~TypePromotionAction() = default;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002069
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002070 /// Undo the modification done by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002071 /// When this method is called, the IR must be in the same state as it was
2072 /// before this action was applied.
2073 /// \pre Undoing the action works if and only if the IR is in the exact same
2074 /// state as it was directly after this action was applied.
2075 virtual void undo() = 0;
2076
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002077 /// Advocate every change made by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002078 /// When the results on the IR of the action are to be kept, it is important
2079 /// to call this function, otherwise hidden information may be kept forever.
2080 virtual void commit() {
2081 // Nothing to be done, this action is not doing anything.
2082 }
2083 };
2084
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002085 /// Utility to remember the position of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002086 class InsertionHandler {
2087 /// Position of an instruction.
2088 /// Either an instruction:
2089 /// - Is the first in a basic block: BB is used.
2090 /// - Has a previous instructon: PrevInst is used.
2091 union {
2092 Instruction *PrevInst;
2093 BasicBlock *BB;
2094 } Point;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002095
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002096 /// Remember whether or not the instruction had a previous instruction.
2097 bool HasPrevInstruction;
2098
2099 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002100 /// Record the position of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002101 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002102 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002103 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2104 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002105 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002106 else
2107 Point.BB = Inst->getParent();
2108 }
2109
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002110 /// Insert \p Inst at the recorded position.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002111 void insert(Instruction *Inst) {
2112 if (HasPrevInstruction) {
2113 if (Inst->getParent())
2114 Inst->removeFromParent();
2115 Inst->insertAfter(Point.PrevInst);
2116 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002117 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002118 if (Inst->getParent())
2119 Inst->moveBefore(Position);
2120 else
2121 Inst->insertBefore(Position);
2122 }
2123 }
2124 };
2125
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002126 /// Move an instruction before another.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002127 class InstructionMoveBefore : public TypePromotionAction {
2128 /// Original position of the instruction.
2129 InsertionHandler Position;
2130
2131 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002132 /// Move \p Inst before \p Before.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002133 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2134 : TypePromotionAction(Inst), Position(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002135 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
2136 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002137 Inst->moveBefore(Before);
2138 }
2139
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002140 /// Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002141 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002142 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002143 Position.insert(Inst);
2144 }
2145 };
2146
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002147 /// Set the operand of an instruction with a new value.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002148 class OperandSetter : public TypePromotionAction {
2149 /// Original operand of the instruction.
2150 Value *Origin;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002151
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002152 /// Index of the modified instruction.
2153 unsigned Idx;
2154
2155 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002156 /// Set \p Idx operand of \p Inst with \p NewVal.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002157 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2158 : TypePromotionAction(Inst), Idx(Idx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002159 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2160 << "for:" << *Inst << "\n"
2161 << "with:" << *NewVal << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002162 Origin = Inst->getOperand(Idx);
2163 Inst->setOperand(Idx, NewVal);
2164 }
2165
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002166 /// Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002167 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002168 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2169 << "for: " << *Inst << "\n"
2170 << "with: " << *Origin << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002171 Inst->setOperand(Idx, Origin);
2172 }
2173 };
2174
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002175 /// Hide the operands of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002176 /// Do as if this instruction was not using any of its operands.
2177 class OperandsHider : public TypePromotionAction {
2178 /// The list of original operands.
2179 SmallVector<Value *, 4> OriginalValues;
2180
2181 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002182 /// Remove \p Inst from the uses of the operands of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002183 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002184 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002185 unsigned NumOpnds = Inst->getNumOperands();
2186 OriginalValues.reserve(NumOpnds);
2187 for (unsigned It = 0; It < NumOpnds; ++It) {
2188 // Save the current operand.
2189 Value *Val = Inst->getOperand(It);
2190 OriginalValues.push_back(Val);
2191 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002192 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002193 // that we are not willing to pay.
2194 Inst->setOperand(It, UndefValue::get(Val->getType()));
2195 }
2196 }
2197
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002198 /// Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002199 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002200 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002201 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2202 Inst->setOperand(It, OriginalValues[It]);
2203 }
2204 };
2205
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002206 /// Build a truncate instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002207 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002208 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002209
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002210 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002211 /// Build a truncate instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002212 /// result.
2213 /// trunc Opnd to Ty.
2214 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2215 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002216 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002217 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002218 }
2219
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002220 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002221 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002222
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002223 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002224 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002225 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002226 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2227 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002228 }
2229 };
2230
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002231 /// Build a sign extension instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002232 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002233 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002234
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002235 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002236 /// Build a sign extension instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002237 /// result.
2238 /// sext Opnd to Ty.
2239 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002240 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002241 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002242 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002243 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002244 }
2245
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002246 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002247 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002248
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002249 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002250 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002251 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002252 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2253 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002254 }
2255 };
2256
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002257 /// Build a zero extension instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002258 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002259 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002260
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002261 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002262 /// Build a zero extension instruction of \p Opnd producing a \p Ty
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002263 /// result.
2264 /// zext Opnd to Ty.
2265 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002266 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002267 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002268 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002269 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002270 }
2271
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002272 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002273 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002274
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002275 /// Remove the built instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002276 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002277 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002278 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2279 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002280 }
2281 };
2282
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002283 /// Mutate an instruction to another type.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002284 class TypeMutator : public TypePromotionAction {
2285 /// Record the original type.
2286 Type *OrigTy;
2287
2288 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002289 /// Mutate the type of \p Inst into \p NewTy.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002290 TypeMutator(Instruction *Inst, Type *NewTy)
2291 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002292 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2293 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002294 Inst->mutateType(NewTy);
2295 }
2296
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002297 /// Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002298 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002299 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2300 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002301 Inst->mutateType(OrigTy);
2302 }
2303 };
2304
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002305 /// Replace the uses of an instruction by another instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002306 class UsesReplacer : public TypePromotionAction {
2307 /// Helper structure to keep track of the replaced uses.
2308 struct InstructionAndIdx {
2309 /// The instruction using the instruction.
2310 Instruction *Inst;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002311
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002312 /// The index where this instruction is used for Inst.
2313 unsigned Idx;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002314
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002315 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2316 : Inst(Inst), Idx(Idx) {}
2317 };
2318
2319 /// Keep track of the original uses (pair Instruction, Index).
2320 SmallVector<InstructionAndIdx, 4> OriginalUses;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002321
2322 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002323
2324 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002325 /// Replace all the use of \p Inst by \p New.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002326 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002327 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2328 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002329 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002330 for (Use &U : Inst->uses()) {
2331 Instruction *UserI = cast<Instruction>(U.getUser());
2332 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002333 }
2334 // Now, we can replace the uses.
2335 Inst->replaceAllUsesWith(New);
2336 }
2337
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002338 /// Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002339 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002340 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002341 for (use_iterator UseIt = OriginalUses.begin(),
2342 EndIt = OriginalUses.end();
2343 UseIt != EndIt; ++UseIt) {
2344 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2345 }
2346 }
2347 };
2348
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002349 /// Remove an instruction from the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002350 class InstructionRemover : public TypePromotionAction {
2351 /// Original position of the instruction.
2352 InsertionHandler Inserter;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002353
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002354 /// Helper structure to hide all the link to the instruction. In other
2355 /// words, this helps to do as if the instruction was removed.
2356 OperandsHider Hider;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002357
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002358 /// Keep track of the uses replaced, if any.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002359 UsesReplacer *Replacer = nullptr;
2360
Jun Bum Limdee55652017-04-03 19:20:07 +00002361 /// Keep track of instructions removed.
2362 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002363
2364 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002365 /// Remove all reference of \p Inst and optinally replace all its
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002366 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002367 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002368 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002369 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2370 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002371 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Eugene Zelenko900b6332017-08-29 22:32:07 +00002372 RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002373 if (New)
2374 Replacer = new UsesReplacer(Inst, New);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002375 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002376 RemovedInsts.insert(Inst);
2377 /// The instructions removed here will be freed after completing
2378 /// optimizeBlock() for all blocks as we need to keep track of the
2379 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002380 Inst->removeFromParent();
2381 }
2382
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002383 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002384
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002385 /// Resurrect the instruction and reassign it to the proper uses if
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002386 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002387 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002388 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002389 Inserter.insert(Inst);
2390 if (Replacer)
2391 Replacer->undo();
2392 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002393 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002394 }
2395 };
2396
2397public:
2398 /// Restoration point.
2399 /// The restoration point is a pointer to an action instead of an iterator
2400 /// because the iterator may be invalidated but not the pointer.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002401 using ConstRestorationPt = const TypePromotionAction *;
Jun Bum Limdee55652017-04-03 19:20:07 +00002402
2403 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2404 : RemovedInsts(RemovedInsts) {}
2405
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002406 /// Advocate every changes made in that transaction.
2407 void commit();
Eugene Zelenko900b6332017-08-29 22:32:07 +00002408
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002409 /// Undo all the changes made after the given point.
2410 void rollback(ConstRestorationPt Point);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002411
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002412 /// Get the current restoration point.
2413 ConstRestorationPt getRestorationPoint() const;
2414
2415 /// \name API for IR modification with state keeping to support rollback.
2416 /// @{
2417 /// Same as Instruction::setOperand.
2418 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002419
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002420 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002421 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002422
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002423 /// Same as Value::replaceAllUsesWith.
2424 void replaceAllUsesWith(Instruction *Inst, Value *New);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002425
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002426 /// Same as Value::mutateType.
2427 void mutateType(Instruction *Inst, Type *NewTy);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002428
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002429 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002430 Value *createTrunc(Instruction *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002431
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002432 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002433 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002434
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002435 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002436 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002437
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002438 /// Same as Instruction::moveBefore.
2439 void moveBefore(Instruction *Inst, Instruction *Before);
2440 /// @}
2441
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002442private:
2443 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002444 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002445
2446 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2447
Jun Bum Limdee55652017-04-03 19:20:07 +00002448 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002449};
2450
Eugene Zelenko900b6332017-08-29 22:32:07 +00002451} // end anonymous namespace
2452
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002453void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2454 Value *NewVal) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002455 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2456 Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002457}
2458
2459void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2460 Value *NewVal) {
2461 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002462 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2463 Inst, RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002464}
2465
2466void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2467 Value *New) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002468 Actions.push_back(
2469 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002470}
2471
2472void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002473 Actions.push_back(
2474 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002475}
2476
Quentin Colombetac55b152014-09-16 22:36:07 +00002477Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2478 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002479 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002480 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002481 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002482 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002483}
2484
Quentin Colombetac55b152014-09-16 22:36:07 +00002485Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2486 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002487 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002488 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002489 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002490 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002491}
2492
Quentin Colombetac55b152014-09-16 22:36:07 +00002493Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2494 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002495 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002496 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002497 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002498 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002499}
2500
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002501void TypePromotionTransaction::moveBefore(Instruction *Inst,
2502 Instruction *Before) {
2503 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002504 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2505 Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002506}
2507
2508TypePromotionTransaction::ConstRestorationPt
2509TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002510 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002511}
2512
2513void TypePromotionTransaction::commit() {
2514 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002515 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002516 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002517 Actions.clear();
2518}
2519
2520void TypePromotionTransaction::rollback(
2521 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002522 while (!Actions.empty() && Point != Actions.back().get()) {
2523 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002524 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002525 }
2526}
2527
Eugene Zelenko900b6332017-08-29 22:32:07 +00002528namespace {
2529
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002530/// A helper class for matching addressing modes.
Chandler Carruthc8925912013-01-05 02:09:22 +00002531///
2532/// This encapsulates the logic for matching the target-legal addressing modes.
2533class AddressingModeMatcher {
2534 SmallVectorImpl<Instruction*> &AddrModeInsts;
2535 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002536 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002537 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002538
2539 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2540 /// the memory instruction that we're computing this address for.
2541 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002542 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002543 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002544
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002545 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002546 /// part of the return value of this addressing mode matching stuff.
2547 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002548
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002549 /// The instructions inserted by other CodeGenPrepare optimizations.
2550 const SetOfInstrs &InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002551
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002552 /// A map from the instructions to their type before promotion.
2553 InstrToOrigTy &PromotedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002554
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002555 /// The ongoing transaction where every action should be registered.
2556 TypePromotionTransaction &TPT;
2557
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002558 // A GEP which has too large offset to be folded into the addressing mode.
2559 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
2560
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002561 /// This is set to true when we should not do profitability checks.
2562 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002563 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002564
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002565 AddressingModeMatcher(
2566 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
2567 const TargetRegisterInfo &TRI, Type *AT, unsigned AS, Instruction *MI,
2568 ExtAddrMode &AM, const SetOfInstrs &InsertedInsts,
2569 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
2570 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002571 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002572 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2573 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002574 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002575 IgnoreProfitability = false;
2576 }
Stephen Lin837bba12013-07-15 17:55:02 +00002577
Eugene Zelenko900b6332017-08-29 22:32:07 +00002578public:
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002579 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002580 /// give an access type of AccessTy. This returns a list of involved
2581 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002582 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002583 /// optimizations.
2584 /// \p PromotedInsts maps the instructions to their type before promotion.
2585 /// \p The ongoing transaction where every action should be registered.
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002586 static ExtAddrMode
2587 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
2588 SmallVectorImpl<Instruction *> &AddrModeInsts,
2589 const TargetLowering &TLI, const TargetRegisterInfo &TRI,
2590 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
2591 TypePromotionTransaction &TPT,
2592 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002593 ExtAddrMode Result;
2594
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002595 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002596 MemoryInst, Result, InsertedInsts,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002597 PromotedInsts, TPT, LargeOffsetGEP)
2598 .matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002599 (void)Success; assert(Success && "Couldn't select *anything*?");
2600 return Result;
2601 }
Eugene Zelenko900b6332017-08-29 22:32:07 +00002602
Chandler Carruthc8925912013-01-05 02:09:22 +00002603private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002604 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2605 bool matchAddr(Value *V, unsigned Depth);
2606 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002607 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002608 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002609 ExtAddrMode &AMBefore,
2610 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002611 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2612 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002613 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002614};
2615
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002616/// Keep track of simplification of Phi nodes.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002617/// Accept the set of all phi nodes and erase phi node from this set
2618/// if it is simplified.
2619class SimplificationTracker {
2620 DenseMap<Value *, Value *> Storage;
2621 const SimplifyQuery &SQ;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002622 // Tracks newly created Phi nodes. We use a SetVector to get deterministic
2623 // order when iterating over the set in MatchPhiSet.
2624 SmallSetVector<PHINode *, 32> AllPhiNodes;
2625 // Tracks newly created Select nodes.
2626 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002627
2628public:
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002629 SimplificationTracker(const SimplifyQuery &sq)
2630 : SQ(sq) {}
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002631
2632 Value *Get(Value *V) {
2633 do {
2634 auto SV = Storage.find(V);
2635 if (SV == Storage.end())
2636 return V;
2637 V = SV->second;
2638 } while (true);
2639 }
2640
2641 Value *Simplify(Value *Val) {
2642 SmallVector<Value *, 32> WorkList;
2643 SmallPtrSet<Value *, 32> Visited;
2644 WorkList.push_back(Val);
2645 while (!WorkList.empty()) {
2646 auto P = WorkList.pop_back_val();
2647 if (!Visited.insert(P).second)
2648 continue;
2649 if (auto *PI = dyn_cast<Instruction>(P))
2650 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
2651 for (auto *U : PI->users())
2652 WorkList.push_back(cast<Value>(U));
2653 Put(PI, V);
2654 PI->replaceAllUsesWith(V);
2655 if (auto *PHI = dyn_cast<PHINode>(PI))
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002656 AllPhiNodes.remove(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002657 if (auto *Select = dyn_cast<SelectInst>(PI))
2658 AllSelectNodes.erase(Select);
2659 PI->eraseFromParent();
2660 }
2661 }
2662 return Get(Val);
2663 }
2664
2665 void Put(Value *From, Value *To) {
2666 Storage.insert({ From, To });
2667 }
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002668
2669 void ReplacePhi(PHINode *From, PHINode *To) {
2670 Value* OldReplacement = Get(From);
2671 while (OldReplacement != From) {
2672 From = To;
2673 To = dyn_cast<PHINode>(OldReplacement);
2674 OldReplacement = Get(From);
2675 }
2676 assert(Get(To) == To && "Replacement PHI node is already replaced.");
2677 Put(From, To);
2678 From->replaceAllUsesWith(To);
2679 AllPhiNodes.remove(From);
2680 From->eraseFromParent();
2681 }
2682
2683 SmallSetVector<PHINode *, 32>& newPhiNodes() { return AllPhiNodes; }
2684
2685 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
2686
2687 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
2688
2689 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
2690
2691 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
2692
2693 void destroyNewNodes(Type *CommonType) {
2694 // For safe erasing, replace the uses with dummy value first.
2695 auto Dummy = UndefValue::get(CommonType);
2696 for (auto I : AllPhiNodes) {
2697 I->replaceAllUsesWith(Dummy);
2698 I->eraseFromParent();
2699 }
2700 AllPhiNodes.clear();
2701 for (auto I : AllSelectNodes) {
2702 I->replaceAllUsesWith(Dummy);
2703 I->eraseFromParent();
2704 }
2705 AllSelectNodes.clear();
2706 }
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002707};
2708
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002709/// A helper class for combining addressing modes.
John Brawn736bf002017-10-03 13:08:22 +00002710class AddressingModeCombiner {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002711 typedef std::pair<Value *, BasicBlock *> ValueInBB;
2712 typedef DenseMap<ValueInBB, Value *> FoldAddrToValueMapping;
2713 typedef std::pair<PHINode *, PHINode *> PHIPair;
2714
John Brawn736bf002017-10-03 13:08:22 +00002715private:
2716 /// The addressing modes we've collected.
2717 SmallVector<ExtAddrMode, 16> AddrModes;
2718
2719 /// The field in which the AddrModes differ, when we have more than one.
2720 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
2721
2722 /// Are the AddrModes that we have all just equal to their original values?
2723 bool AllAddrModesTrivial = true;
2724
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002725 /// Common Type for all different fields in addressing modes.
2726 Type *CommonType;
2727
2728 /// SimplifyQuery for simplifyInstruction utility.
2729 const SimplifyQuery &SQ;
2730
2731 /// Original Address.
2732 ValueInBB Original;
2733
John Brawn736bf002017-10-03 13:08:22 +00002734public:
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002735 AddressingModeCombiner(const SimplifyQuery &_SQ, ValueInBB OriginalValue)
2736 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
2737
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002738 /// Get the combined AddrMode
John Brawn736bf002017-10-03 13:08:22 +00002739 const ExtAddrMode &getAddrMode() const {
2740 return AddrModes[0];
2741 }
2742
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002743 /// Add a new AddrMode if it's compatible with the AddrModes we already
John Brawn736bf002017-10-03 13:08:22 +00002744 /// have.
2745 /// \return True iff we succeeded in doing so.
2746 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
2747 // Take note of if we have any non-trivial AddrModes, as we need to detect
2748 // when all AddrModes are trivial as then we would introduce a phi or select
2749 // which just duplicates what's already there.
2750 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
2751
2752 // If this is the first addrmode then everything is fine.
2753 if (AddrModes.empty()) {
2754 AddrModes.emplace_back(NewAddrMode);
2755 return true;
2756 }
2757
2758 // Figure out how different this is from the other address modes, which we
2759 // can do just by comparing against the first one given that we only care
2760 // about the cumulative difference.
2761 ExtAddrMode::FieldName ThisDifferentField =
2762 AddrModes[0].compare(NewAddrMode);
2763 if (DifferentField == ExtAddrMode::NoField)
2764 DifferentField = ThisDifferentField;
2765 else if (DifferentField != ThisDifferentField)
2766 DifferentField = ExtAddrMode::MultipleFields;
2767
Serguei Katkov17e57942018-01-23 12:07:49 +00002768 // If NewAddrMode differs in more than one dimension we cannot handle it.
2769 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
2770
2771 // If Scale Field is different then we reject.
2772 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
2773
Serguei Katkov4d1dd6b2018-01-09 04:37:06 +00002774 // We also must reject the case when base offset is different and
2775 // scale reg is not null, we cannot handle this case due to merge of
2776 // different offsets will be used as ScaleReg.
Serguei Katkov17e57942018-01-23 12:07:49 +00002777 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
2778 !NewAddrMode.ScaledReg);
John Brawn736bf002017-10-03 13:08:22 +00002779
Serguei Katkov17e57942018-01-23 12:07:49 +00002780 // We also must reject the case when GV is different and BaseReg installed
2781 // due to we want to use base reg as a merge of GV values.
2782 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
2783 !NewAddrMode.HasBaseReg);
2784
2785 // Even if NewAddMode is the same we still need to collect it due to
2786 // original value is different. And later we will need all original values
2787 // as anchors during finding the common Phi node.
2788 if (CanHandle)
2789 AddrModes.emplace_back(NewAddrMode);
2790 else
2791 AddrModes.clear();
2792
2793 return CanHandle;
John Brawn736bf002017-10-03 13:08:22 +00002794 }
2795
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002796 /// Combine the addressing modes we've collected into a single
John Brawn736bf002017-10-03 13:08:22 +00002797 /// addressing mode.
2798 /// \return True iff we successfully combined them or we only had one so
2799 /// didn't need to combine them anyway.
2800 bool combineAddrModes() {
2801 // If we have no AddrModes then they can't be combined.
2802 if (AddrModes.size() == 0)
2803 return false;
2804
2805 // A single AddrMode can trivially be combined.
Serguei Katkov505359f2017-11-20 05:42:36 +00002806 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
John Brawn736bf002017-10-03 13:08:22 +00002807 return true;
2808
2809 // If the AddrModes we collected are all just equal to the value they are
2810 // derived from then combining them wouldn't do anything useful.
2811 if (AllAddrModesTrivial)
2812 return false;
2813
John Brawn70cdb5b2017-11-24 14:10:45 +00002814 if (!addrModeCombiningAllowed())
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002815 return false;
2816
2817 // Build a map between <original value, basic block where we saw it> to
2818 // value of base register.
Serguei Katkov50364592017-11-29 05:51:26 +00002819 // Bail out if there is no common type.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002820 FoldAddrToValueMapping Map;
Serguei Katkov50364592017-11-29 05:51:26 +00002821 if (!initializeMap(Map))
2822 return false;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002823
2824 Value *CommonValue = findCommon(Map);
2825 if (CommonValue)
John Brawn70cdb5b2017-11-24 14:10:45 +00002826 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002827 return CommonValue != nullptr;
2828 }
2829
2830private:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002831 /// Initialize Map with anchor values. For address seen in some BB
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002832 /// we set the value of different field saw in this address.
2833 /// If address is not an instruction than basic block is set to null.
2834 /// At the same time we find a common type for different field we will
2835 /// use to create new Phi/Select nodes. Keep it in CommonType field.
Serguei Katkov50364592017-11-29 05:51:26 +00002836 /// Return false if there is no common type found.
2837 bool initializeMap(FoldAddrToValueMapping &Map) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002838 // Keep track of keys where the value is null. We will need to replace it
2839 // with constant null when we know the common type.
2840 SmallVector<ValueInBB, 2> NullValue;
John Brawn70cdb5b2017-11-24 14:10:45 +00002841 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002842 for (auto &AM : AddrModes) {
2843 BasicBlock *BB = nullptr;
2844 if (Instruction *I = dyn_cast<Instruction>(AM.OriginalValue))
2845 BB = I->getParent();
2846
John Brawn70cdb5b2017-11-24 14:10:45 +00002847 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002848 if (DV) {
Serguei Katkov50364592017-11-29 05:51:26 +00002849 auto *Type = DV->getType();
2850 if (CommonType && CommonType != Type)
2851 return false;
2852 CommonType = Type;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002853 Map[{ AM.OriginalValue, BB }] = DV;
2854 } else {
2855 NullValue.push_back({ AM.OriginalValue, BB });
2856 }
2857 }
2858 assert(CommonType && "At least one non-null value must be!");
2859 for (auto VIBB : NullValue)
2860 Map[VIBB] = Constant::getNullValue(CommonType);
Serguei Katkov50364592017-11-29 05:51:26 +00002861 return true;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002862 }
2863
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002864 /// We have mapping between value A and basic block where value A
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002865 /// seen to other value B where B was a field in addressing mode represented
2866 /// by A. Also we have an original value C representin an address in some
2867 /// basic block. Traversing from C through phi and selects we ended up with
2868 /// A's in a map. This utility function tries to find a value V which is a
2869 /// field in addressing mode C and traversing through phi nodes and selects
2870 /// we will end up in corresponded values B in a map.
2871 /// The utility will create a new Phi/Selects if needed.
2872 // The simple example looks as follows:
2873 // BB1:
2874 // p1 = b1 + 40
2875 // br cond BB2, BB3
2876 // BB2:
2877 // p2 = b2 + 40
2878 // br BB3
2879 // BB3:
2880 // p = phi [p1, BB1], [p2, BB2]
2881 // v = load p
2882 // Map is
2883 // <p1, BB1> -> b1
2884 // <p2, BB2> -> b2
2885 // Request is
2886 // <p, BB3> -> ?
2887 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3
2888 Value *findCommon(FoldAddrToValueMapping &Map) {
Eric Christopherd72f78e2018-01-09 23:25:38 +00002889 // Tracks the simplification of newly created phi nodes. The reason we use
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002890 // this mapping is because we will add new created Phi nodes in AddrToBase.
2891 // Simplification of Phi nodes is recursive, so some Phi node may
2892 // be simplified after we added it to AddrToBase.
2893 // Using this mapping we can find the current value in AddrToBase.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002894 SimplificationTracker ST(SQ);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002895
2896 // First step, DFS to create PHI nodes for all intermediate blocks.
2897 // Also fill traverse order for the second step.
2898 SmallVector<ValueInBB, 32> TraverseOrder;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002899 InsertPlaceholders(Map, TraverseOrder, ST);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002900
2901 // Second Step, fill new nodes by merged values and simplify if possible.
2902 FillPlaceholders(Map, TraverseOrder, ST);
2903
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002904 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
2905 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002906 return nullptr;
2907 }
2908
2909 // Now we'd like to match New Phi nodes to existed ones.
2910 unsigned PhiNotMatchedCount = 0;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002911 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
2912 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002913 return nullptr;
2914 }
2915
2916 auto *Result = ST.Get(Map.find(Original)->second);
2917 if (Result) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002918 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
2919 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002920 }
2921 return Result;
2922 }
2923
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002924 /// Try to match PHI node to Candidate.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002925 /// Matcher tracks the matched Phi nodes.
2926 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002927 SmallSetVector<PHIPair, 8> &Matcher,
2928 SmallSetVector<PHINode *, 32> &PhiNodesToMatch) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002929 SmallVector<PHIPair, 8> WorkList;
2930 Matcher.insert({ PHI, Candidate });
2931 WorkList.push_back({ PHI, Candidate });
2932 SmallSet<PHIPair, 8> Visited;
2933 while (!WorkList.empty()) {
2934 auto Item = WorkList.pop_back_val();
2935 if (!Visited.insert(Item).second)
2936 continue;
2937 // We iterate over all incoming values to Phi to compare them.
2938 // If values are different and both of them Phi and the first one is a
2939 // Phi we added (subject to match) and both of them is in the same basic
2940 // block then we can match our pair if values match. So we state that
2941 // these values match and add it to work list to verify that.
2942 for (auto B : Item.first->blocks()) {
2943 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
2944 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
2945 if (FirstValue == SecondValue)
2946 continue;
2947
2948 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
2949 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
2950
2951 // One of them is not Phi or
2952 // The first one is not Phi node from the set we'd like to match or
2953 // Phi nodes from different basic blocks then
2954 // we will not be able to match.
2955 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
2956 FirstPhi->getParent() != SecondPhi->getParent())
2957 return false;
2958
2959 // If we already matched them then continue.
2960 if (Matcher.count({ FirstPhi, SecondPhi }))
2961 continue;
2962 // So the values are different and does not match. So we need them to
2963 // match.
2964 Matcher.insert({ FirstPhi, SecondPhi });
2965 // But me must check it.
2966 WorkList.push_back({ FirstPhi, SecondPhi });
2967 }
2968 }
2969 return true;
2970 }
2971
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002972 /// For the given set of PHI nodes (in the SimplificationTracker) try
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002973 /// to find their equivalents.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002974 /// Returns false if this matching fails and creation of new Phi is disabled.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002975 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002976 unsigned &PhiNotMatchedCount) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002977 // Use a SetVector for Matched to make sure we do replacements (ReplacePhi)
2978 // in a deterministic order below.
2979 SmallSetVector<PHIPair, 8> Matched;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002980 SmallPtrSet<PHINode *, 8> WillNotMatch;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002981 SmallSetVector<PHINode *, 32> &PhiNodesToMatch = ST.newPhiNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002982 while (PhiNodesToMatch.size()) {
2983 PHINode *PHI = *PhiNodesToMatch.begin();
2984
2985 // Add us, if no Phi nodes in the basic block we do not match.
2986 WillNotMatch.clear();
2987 WillNotMatch.insert(PHI);
2988
2989 // Traverse all Phis until we found equivalent or fail to do that.
2990 bool IsMatched = false;
2991 for (auto &P : PHI->getParent()->phis()) {
2992 if (&P == PHI)
2993 continue;
2994 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
2995 break;
2996 // If it does not match, collect all Phi nodes from matcher.
2997 // if we end up with no match, them all these Phi nodes will not match
2998 // later.
2999 for (auto M : Matched)
3000 WillNotMatch.insert(M.first);
3001 Matched.clear();
3002 }
3003 if (IsMatched) {
Serguei Katkova20e05b2018-03-12 03:50:07 +00003004 // Replace all matched values and erase them.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003005 for (auto MV : Matched)
3006 ST.ReplacePhi(MV.first, MV.second);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003007 Matched.clear();
3008 continue;
3009 }
3010 // If we are not allowed to create new nodes then bail out.
3011 if (!AllowNewPhiNodes)
3012 return false;
3013 // Just remove all seen values in matcher. They will not match anything.
3014 PhiNotMatchedCount += WillNotMatch.size();
3015 for (auto *P : WillNotMatch)
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003016 PhiNodesToMatch.remove(P);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003017 }
3018 return true;
3019 }
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003020 /// Fill the placeholder with values from predecessors and simplify it.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003021 void FillPlaceholders(FoldAddrToValueMapping &Map,
3022 SmallVectorImpl<ValueInBB> &TraverseOrder,
3023 SimplificationTracker &ST) {
3024 while (!TraverseOrder.empty()) {
3025 auto Current = TraverseOrder.pop_back_val();
3026 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
3027 Value *CurrentValue = Current.first;
3028 BasicBlock *CurrentBlock = Current.second;
3029 Value *V = Map[Current];
3030
3031 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3032 // CurrentValue also must be Select.
3033 auto *CurrentSelect = cast<SelectInst>(CurrentValue);
3034 auto *TrueValue = CurrentSelect->getTrueValue();
3035 ValueInBB TrueItem = { TrueValue, isa<Instruction>(TrueValue)
3036 ? CurrentBlock
3037 : nullptr };
3038 assert(Map.find(TrueItem) != Map.end() && "No True Value!");
Serguei Katkovb0b67a82017-12-18 04:25:07 +00003039 Select->setTrueValue(ST.Get(Map[TrueItem]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003040 auto *FalseValue = CurrentSelect->getFalseValue();
3041 ValueInBB FalseItem = { FalseValue, isa<Instruction>(FalseValue)
3042 ? CurrentBlock
3043 : nullptr };
3044 assert(Map.find(FalseItem) != Map.end() && "No False Value!");
Serguei Katkovb0b67a82017-12-18 04:25:07 +00003045 Select->setFalseValue(ST.Get(Map[FalseItem]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003046 } else {
3047 // Must be a Phi node then.
3048 PHINode *PHI = cast<PHINode>(V);
3049 // Fill the Phi node with values from predecessors.
3050 bool IsDefinedInThisBB =
3051 cast<Instruction>(CurrentValue)->getParent() == CurrentBlock;
3052 auto *CurrentPhi = dyn_cast<PHINode>(CurrentValue);
3053 for (auto B : predecessors(CurrentBlock)) {
3054 Value *PV = IsDefinedInThisBB
3055 ? CurrentPhi->getIncomingValueForBlock(B)
3056 : CurrentValue;
3057 ValueInBB item = { PV, isa<Instruction>(PV) ? B : nullptr };
3058 assert(Map.find(item) != Map.end() && "No predecessor Value!");
3059 PHI->addIncoming(ST.Get(Map[item]), B);
3060 }
3061 }
3062 // Simplify if possible.
3063 Map[Current] = ST.Simplify(V);
3064 }
3065 }
3066
3067 /// Starting from value recursively iterates over predecessors up to known
3068 /// ending values represented in a map. For each traversed block inserts
3069 /// a placeholder Phi or Select.
3070 /// Reports all new created Phi/Select nodes by adding them to set.
3071 /// Also reports and order in what basic blocks have been traversed.
3072 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3073 SmallVectorImpl<ValueInBB> &TraverseOrder,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003074 SimplificationTracker &ST) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003075 SmallVector<ValueInBB, 32> Worklist;
3076 assert((isa<PHINode>(Original.first) || isa<SelectInst>(Original.first)) &&
3077 "Address must be a Phi or Select node");
3078 auto *Dummy = UndefValue::get(CommonType);
3079 Worklist.push_back(Original);
3080 while (!Worklist.empty()) {
3081 auto Current = Worklist.pop_back_val();
3082 // If value is not an instruction it is something global, constant,
3083 // parameter and we can say that this value is observable in any block.
3084 // Set block to null to denote it.
3085 // Also please take into account that it is how we build anchors.
3086 if (!isa<Instruction>(Current.first))
3087 Current.second = nullptr;
3088 // if it is already visited or it is an ending value then skip it.
3089 if (Map.find(Current) != Map.end())
3090 continue;
3091 TraverseOrder.push_back(Current);
3092
3093 Value *CurrentValue = Current.first;
3094 BasicBlock *CurrentBlock = Current.second;
3095 // CurrentValue must be a Phi node or select. All others must be covered
3096 // by anchors.
3097 Instruction *CurrentI = cast<Instruction>(CurrentValue);
3098 bool IsDefinedInThisBB = CurrentI->getParent() == CurrentBlock;
3099
Vedant Kumare0b5f862018-05-10 23:01:54 +00003100 unsigned PredCount = pred_size(CurrentBlock);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003101 // if Current Value is not defined in this basic block we are interested
3102 // in values in predecessors.
3103 if (!IsDefinedInThisBB) {
3104 assert(PredCount && "Unreachable block?!");
3105 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3106 &CurrentBlock->front());
3107 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003108 ST.insertNewPhi(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003109 // Add all predecessors in work list.
3110 for (auto B : predecessors(CurrentBlock))
3111 Worklist.push_back({ CurrentValue, B });
3112 continue;
3113 }
3114 // Value is defined in this basic block.
3115 if (SelectInst *OrigSelect = dyn_cast<SelectInst>(CurrentI)) {
3116 // Is it OK to get metadata from OrigSelect?!
3117 // Create a Select placeholder with dummy value.
3118 SelectInst *Select =
3119 SelectInst::Create(OrigSelect->getCondition(), Dummy, Dummy,
3120 OrigSelect->getName(), OrigSelect, OrigSelect);
3121 Map[Current] = Select;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003122 ST.insertNewSelect(Select);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003123 // We are interested in True and False value in this basic block.
3124 Worklist.push_back({ OrigSelect->getTrueValue(), CurrentBlock });
3125 Worklist.push_back({ OrigSelect->getFalseValue(), CurrentBlock });
3126 } else {
3127 // It must be a Phi node then.
3128 auto *CurrentPhi = cast<PHINode>(CurrentI);
3129 // Create new Phi node for merge of bases.
3130 assert(PredCount && "Unreachable block?!");
3131 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3132 &CurrentBlock->front());
3133 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003134 ST.insertNewPhi(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003135
3136 // Add all predecessors in work list.
3137 for (auto B : predecessors(CurrentBlock))
3138 Worklist.push_back({ CurrentPhi->getIncomingValueForBlock(B), B });
3139 }
3140 }
John Brawn736bf002017-10-03 13:08:22 +00003141 }
John Brawn70cdb5b2017-11-24 14:10:45 +00003142
3143 bool addrModeCombiningAllowed() {
3144 if (DisableComplexAddrModes)
3145 return false;
3146 switch (DifferentField) {
3147 default:
3148 return false;
3149 case ExtAddrMode::BaseRegField:
3150 return AddrSinkCombineBaseReg;
3151 case ExtAddrMode::BaseGVField:
3152 return AddrSinkCombineBaseGV;
3153 case ExtAddrMode::BaseOffsField:
3154 return AddrSinkCombineBaseOffs;
3155 case ExtAddrMode::ScaledRegField:
3156 return AddrSinkCombineScaledReg;
3157 }
3158 }
John Brawn736bf002017-10-03 13:08:22 +00003159};
Eugene Zelenko900b6332017-08-29 22:32:07 +00003160} // end anonymous namespace
3161
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003162/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003163/// Return true and update AddrMode if this addr mode is legal for the target,
3164/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003165bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003166 unsigned Depth) {
3167 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3168 // mode. Just process that directly.
3169 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003170 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003171
Chandler Carruthc8925912013-01-05 02:09:22 +00003172 // If the scale is 0, it takes nothing to add this.
3173 if (Scale == 0)
3174 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003175
Chandler Carruthc8925912013-01-05 02:09:22 +00003176 // If we already have a scale of this value, we can add to it, otherwise, we
3177 // need an available scale field.
3178 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3179 return false;
3180
3181 ExtAddrMode TestAddrMode = AddrMode;
3182
3183 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3184 // [A+B + A*7] -> [B+A*8].
3185 TestAddrMode.Scale += Scale;
3186 TestAddrMode.ScaledReg = ScaleReg;
3187
3188 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003189 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003190 return false;
3191
3192 // It was legal, so commit it.
3193 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003194
Chandler Carruthc8925912013-01-05 02:09:22 +00003195 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3196 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3197 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003198 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003199 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3200 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3201 TestAddrMode.ScaledReg = AddLHS;
3202 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003203
Chandler Carruthc8925912013-01-05 02:09:22 +00003204 // If this addressing mode is legal, commit it and remember that we folded
3205 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003206 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003207 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3208 AddrMode = TestAddrMode;
3209 return true;
3210 }
3211 }
3212
3213 // Otherwise, not (x+c)*scale, just return what we have.
3214 return true;
3215}
3216
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003217/// This is a little filter, which returns true if an addressing computation
3218/// involving I might be folded into a load/store accessing it.
3219/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003220/// the set of instructions that MatchOperationAddr can.
3221static bool MightBeFoldableInst(Instruction *I) {
3222 switch (I->getOpcode()) {
3223 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003224 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003225 // Don't touch identity bitcasts.
3226 if (I->getType() == I->getOperand(0)->getType())
3227 return false;
3228 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3229 case Instruction::PtrToInt:
3230 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3231 return true;
3232 case Instruction::IntToPtr:
3233 // We know the input is intptr_t, so this is foldable.
3234 return true;
3235 case Instruction::Add:
3236 return true;
3237 case Instruction::Mul:
3238 case Instruction::Shl:
3239 // Can only handle X*C and X << C.
3240 return isa<ConstantInt>(I->getOperand(1));
3241 case Instruction::GetElementPtr:
3242 return true;
3243 default:
3244 return false;
3245 }
3246}
3247
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003248/// Check whether or not \p Val is a legal instruction for \p TLI.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003249/// \note \p Val is assumed to be the product of some type promotion.
3250/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3251/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003252static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3253 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003254 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3255 if (!PromotedInst)
3256 return false;
3257 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3258 // If the ISDOpcode is undefined, it was undefined before the promotion.
3259 if (!ISDOpcode)
3260 return true;
3261 // Otherwise, check if the promoted instruction is legal or not.
3262 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003263 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003264}
3265
Eugene Zelenko900b6332017-08-29 22:32:07 +00003266namespace {
3267
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003268/// Hepler class to perform type promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003269class TypePromotionHelper {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003270 /// Utility function to check whether or not a sign or zero extension
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003271 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3272 /// either using the operands of \p Inst or promoting \p Inst.
3273 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003274 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003275 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003276 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003277 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003278 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003279 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003280 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003281 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3282 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003283
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003284 /// Utility function to determine if \p OpIdx should be promoted when
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003285 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003286 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003287 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003288 }
3289
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003290 /// Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003291 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003292 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003293 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003294 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003295 /// Newly added extensions are inserted in \p Exts.
3296 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003297 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003298 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003299 static Value *promoteOperandForTruncAndAnyExt(
3300 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003301 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003302 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003303 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003304
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003305 /// Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003306 /// operand is promotable and is not a supported trunc or sext.
3307 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003308 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003309 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003310 /// Newly added extensions are inserted in \p Exts.
3311 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003312 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003313 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003314 static Value *promoteOperandForOther(Instruction *Ext,
3315 TypePromotionTransaction &TPT,
3316 InstrToOrigTy &PromotedInsts,
3317 unsigned &CreatedInstsCost,
3318 SmallVectorImpl<Instruction *> *Exts,
3319 SmallVectorImpl<Instruction *> *Truncs,
3320 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003321
3322 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003323 static Value *signExtendOperandForOther(
3324 Instruction *Ext, TypePromotionTransaction &TPT,
3325 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3326 SmallVectorImpl<Instruction *> *Exts,
3327 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3328 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3329 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003330 }
3331
3332 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003333 static Value *zeroExtendOperandForOther(
3334 Instruction *Ext, TypePromotionTransaction &TPT,
3335 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3336 SmallVectorImpl<Instruction *> *Exts,
3337 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3338 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3339 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003340 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003341
3342public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003343 /// Type for the utility function that promotes the operand of Ext.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003344 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3345 InstrToOrigTy &PromotedInsts,
3346 unsigned &CreatedInstsCost,
3347 SmallVectorImpl<Instruction *> *Exts,
3348 SmallVectorImpl<Instruction *> *Truncs,
3349 const TargetLowering &TLI);
3350
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003351 /// Given a sign/zero extend instruction \p Ext, return the approriate
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003352 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003353 /// \return NULL if no promotable action is possible with the current
3354 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003355 /// \p InsertedInsts keeps track of all the instructions inserted by the
3356 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003357 /// because we do not want to promote these instructions as CodeGenPrepare
3358 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3359 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003360 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003361 const TargetLowering &TLI,
3362 const InstrToOrigTy &PromotedInsts);
3363};
3364
Eugene Zelenko900b6332017-08-29 22:32:07 +00003365} // end anonymous namespace
3366
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003367bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003368 Type *ConsideredExtType,
3369 const InstrToOrigTy &PromotedInsts,
3370 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003371 // The promotion helper does not know how to deal with vector types yet.
3372 // To be able to fix that, we would need to fix the places where we
3373 // statically extend, e.g., constants and such.
3374 if (Inst->getType()->isVectorTy())
3375 return false;
3376
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003377 // We can always get through zext.
3378 if (isa<ZExtInst>(Inst))
3379 return true;
3380
3381 // sext(sext) is ok too.
3382 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003383 return true;
3384
3385 // We can get through binary operator, if it is legal. In other words, the
3386 // binary operator must have a nuw or nsw flag.
3387 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3388 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003389 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3390 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003391 return true;
3392
Guozhi Wei1aea95a2018-05-08 17:58:32 +00003393 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
3394 if ((Inst->getOpcode() == Instruction::And ||
3395 Inst->getOpcode() == Instruction::Or))
3396 return true;
3397
3398 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
3399 if (Inst->getOpcode() == Instruction::Xor) {
3400 const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1));
3401 // Make sure it is not a NOT.
3402 if (Cst && !Cst->getValue().isAllOnesValue())
3403 return true;
3404 }
3405
3406 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
3407 // It may change a poisoned value into a regular value, like
3408 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
3409 // poisoned value regular value
3410 // It should be OK since undef covers valid value.
3411 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
3412 return true;
3413
3414 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
3415 // It may change a poisoned value into a regular value, like
3416 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
3417 // poisoned value regular value
3418 // It should be OK since undef covers valid value.
3419 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
3420 const Instruction *ExtInst =
3421 dyn_cast<const Instruction>(*Inst->user_begin());
3422 if (ExtInst->hasOneUse()) {
3423 const Instruction *AndInst =
3424 dyn_cast<const Instruction>(*ExtInst->user_begin());
3425 if (AndInst && AndInst->getOpcode() == Instruction::And) {
3426 const ConstantInt *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
3427 if (Cst &&
3428 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
3429 return true;
3430 }
3431 }
3432 }
3433
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003434 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003435 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003436 if (!isa<TruncInst>(Inst))
3437 return false;
3438
3439 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003440 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003441 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003442 if (!OpndVal->getType()->isIntegerTy() ||
3443 OpndVal->getType()->getIntegerBitWidth() >
3444 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003445 return false;
3446
3447 // If the operand of the truncate is not an instruction, we will not have
3448 // any information on the dropped bits.
3449 // (Actually we could for constant but it is not worth the extra logic).
3450 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3451 if (!Opnd)
3452 return false;
3453
3454 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003455 // I.e., check that trunc just drops extended bits of the same kind of
3456 // the extension.
3457 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003458 const Type *OpndType;
3459 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003460 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3461 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003462 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3463 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003464 else
3465 return false;
3466
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003467 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003468 return Inst->getType()->getIntegerBitWidth() >=
3469 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003470}
3471
3472TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003473 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003474 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003475 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3476 "Unexpected instruction type");
3477 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3478 Type *ExtTy = Ext->getType();
3479 bool IsSExt = isa<SExtInst>(Ext);
3480 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003481 // get through.
3482 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003483 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003484 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003485
3486 // Do not promote if the operand has been added by codegenprepare.
3487 // Otherwise, it means we are undoing an optimization that is likely to be
3488 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003489 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003490 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003491
3492 // SExt or Trunc instructions.
3493 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003494 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3495 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003496 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003497
3498 // Regular instruction.
3499 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003500 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003501 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003502 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003503}
3504
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003505Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003506 Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003507 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003508 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003509 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003510 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3511 // get through it and this method should not be called.
3512 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003513 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003514 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003515 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003516 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003517 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003518 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003519 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003520 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3521 TPT.replaceAllUsesWith(SExt, ZExt);
3522 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003523 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003524 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003525 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3526 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003527 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3528 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003529 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003530
3531 // Remove dead code.
3532 if (SExtOpnd->use_empty())
3533 TPT.eraseInstruction(SExtOpnd);
3534
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003535 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003536 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003537 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003538 if (ExtInst) {
3539 if (Exts)
3540 Exts->push_back(ExtInst);
3541 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3542 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003543 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003544 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003545
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003546 // At this point we have: ext ty opnd to ty.
3547 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3548 Value *NextVal = ExtInst->getOperand(0);
3549 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003550 return NextVal;
3551}
3552
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003553Value *TypePromotionHelper::promoteOperandForOther(
3554 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003555 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003556 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003557 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3558 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003559 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003560 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003561 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003562 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003563 if (!ExtOpnd->hasOneUse()) {
3564 // ExtOpnd will be promoted.
3565 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003566 // promoted version.
3567 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003568 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003569 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
Quentin Colombetac55b152014-09-16 22:36:07 +00003570 // Insert it just after the definition.
Sanjay Patel674d2c22017-08-29 14:07:48 +00003571 ITrunc->moveAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003572 if (Truncs)
3573 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003574 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003575
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003576 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003577 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003578 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003579 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003580 }
3581
3582 // Get through the Instruction:
3583 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003584 // 2. Replace the uses of Ext by Inst.
3585 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003586
3587 // Remember the original type of the instruction before promotion.
3588 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003589 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3590 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003591 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003592 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003593 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003594 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003595 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003596 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003597
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003598 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003599 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003600 ++OpIdx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003601 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003602 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3603 !shouldExtOperand(ExtOpnd, OpIdx)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003604 LLVM_DEBUG(dbgs() << "No need to propagate\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003605 continue;
3606 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003607 // Check if we can statically extend the operand.
3608 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003609 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003610 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003611 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3612 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3613 : Cst->getValue().zext(BitWidth);
3614 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003615 continue;
3616 }
3617 // UndefValue are typed, so we have to statically sign extend them.
3618 if (isa<UndefValue>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003619 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003620 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003621 continue;
3622 }
3623
3624 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003625 // Check if Ext was reused to extend an operand.
3626 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003627 // If yes, create a new one.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003628 LLVM_DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003629 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3630 : TPT.createZExt(Ext, Opnd, Ext->getType());
3631 if (!isa<Instruction>(ValForExtOpnd)) {
3632 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3633 continue;
3634 }
3635 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003636 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003637 if (Exts)
3638 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003639 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003640
3641 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003642 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3643 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003644 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003645 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003646 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003647 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003648 if (ExtForOpnd == Ext) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003649 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003650 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003651 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003652 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003653}
3654
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003655/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003656/// \p NewCost gives the cost of extension instructions created by the
3657/// promotion.
3658/// \p OldCost gives the cost of extension instructions before the promotion
3659/// plus the number of instructions that have been
3660/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003661/// \p PromotedOperand is the value that has been promoted.
3662/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003663bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003664 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003665 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
3666 << '\n');
Quentin Colombet1b274f92015-03-10 21:48:15 +00003667 // The cost of the new extensions is greater than the cost of the
3668 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003669 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003670 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003671 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003672 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003673 return true;
3674 // The promotion is neutral but it may help folding the sign extension in
3675 // loads for instance.
3676 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003677 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003678}
3679
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003680/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003681/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003682/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003683/// If \p MovedAway is not NULL, it contains the information of whether or
3684/// not AddrInst has to be folded into the addressing mode on success.
3685/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3686/// because it has been moved away.
3687/// Thus AddrInst must not be added in the matched instructions.
3688/// This state can happen when AddrInst is a sext, since it may be moved away.
3689/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3690/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003691bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003692 unsigned Depth,
3693 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003694 // Avoid exponential behavior on extremely deep expression trees.
3695 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003696
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003697 // By default, all matched instructions stay in place.
3698 if (MovedAway)
3699 *MovedAway = false;
3700
Chandler Carruthc8925912013-01-05 02:09:22 +00003701 switch (Opcode) {
3702 case Instruction::PtrToInt:
3703 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003704 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003705 case Instruction::IntToPtr: {
3706 auto AS = AddrInst->getType()->getPointerAddressSpace();
3707 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003708 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003709 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003710 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003711 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003712 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003713 case Instruction::BitCast:
3714 // BitCast is always a noop, and we can handle it as long as it is
3715 // int->int or pointer->pointer (we don't want int<->fp or something).
3716 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3717 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3718 // Don't touch identity bitcasts. These were probably put here by LSR,
3719 // and we don't want to mess around with them. Assume it knows what it
3720 // is doing.
3721 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003722 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003723 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003724 case Instruction::AddrSpaceCast: {
3725 unsigned SrcAS
3726 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3727 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3728 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003729 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003730 return false;
3731 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003732 case Instruction::Add: {
3733 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3734 ExtAddrMode BackupAddrMode = AddrMode;
3735 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003736 // Start a transaction at this point.
3737 // The LHS may match but not the RHS.
3738 // Therefore, we need a higher level restoration point to undo partially
3739 // matched operation.
3740 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3741 TPT.getRestorationPoint();
3742
Sanjay Patelfc580a62015-09-21 23:03:16 +00003743 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3744 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003745 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003746
Chandler Carruthc8925912013-01-05 02:09:22 +00003747 // Restore the old addr mode info.
3748 AddrMode = BackupAddrMode;
3749 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003750 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003751
Chandler Carruthc8925912013-01-05 02:09:22 +00003752 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003753 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3754 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003755 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003756
Chandler Carruthc8925912013-01-05 02:09:22 +00003757 // Otherwise we definitely can't merge the ADD in.
3758 AddrMode = BackupAddrMode;
3759 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003760 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003761 break;
3762 }
3763 //case Instruction::Or:
3764 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3765 //break;
3766 case Instruction::Mul:
3767 case Instruction::Shl: {
3768 // Can only handle X*C and X << C.
3769 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Philip Reames9c3cbee2017-10-30 23:59:51 +00003770 if (!RHS || RHS->getBitWidth() > 64)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003771 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003772 int64_t Scale = RHS->getSExtValue();
3773 if (Opcode == Instruction::Shl)
3774 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003775
Sanjay Patelfc580a62015-09-21 23:03:16 +00003776 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003777 }
3778 case Instruction::GetElementPtr: {
3779 // Scan the GEP. We check it if it contains constant offsets and at most
3780 // one variable offset.
3781 int VariableOperand = -1;
3782 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003783
Chandler Carruthc8925912013-01-05 02:09:22 +00003784 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003785 gep_type_iterator GTI = gep_type_begin(AddrInst);
3786 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003787 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003788 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003789 unsigned Idx =
3790 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3791 ConstantOffset += SL->getElementOffset(Idx);
3792 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003793 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003794 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
Haicheng Wu0be88252017-12-19 20:53:32 +00003795 ConstantOffset += CI->getSExtValue() * TypeSize;
Chandler Carruthc8925912013-01-05 02:09:22 +00003796 } else if (TypeSize) { // Scales of zero don't do anything.
3797 // We only allow one variable index at the moment.
3798 if (VariableOperand != -1)
3799 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003800
Chandler Carruthc8925912013-01-05 02:09:22 +00003801 // Remember the variable index.
3802 VariableOperand = i;
3803 VariableScale = TypeSize;
3804 }
3805 }
3806 }
Stephen Lin837bba12013-07-15 17:55:02 +00003807
Chandler Carruthc8925912013-01-05 02:09:22 +00003808 // A common case is for the GEP to only do a constant offset. In this case,
3809 // just add it to the disp field and check validity.
3810 if (VariableOperand == -1) {
3811 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003812 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003813 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003814 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003815 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003816 return true;
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00003817 } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
3818 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
3819 ConstantOffset > 0) {
3820 // Record GEPs with non-zero offsets as candidates for splitting in the
3821 // event that the offset cannot fit into the r+i addressing mode.
3822 // Simple and common case that only one GEP is used in calculating the
3823 // address for the memory access.
3824 Value *Base = AddrInst->getOperand(0);
3825 auto *BaseI = dyn_cast<Instruction>(Base);
3826 auto *GEP = cast<GetElementPtrInst>(AddrInst);
3827 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
3828 (BaseI && !isa<CastInst>(BaseI) &&
3829 !isa<GetElementPtrInst>(BaseI))) {
3830 // If the base is an instruction, make sure the GEP is not in the same
3831 // basic block as the base. If the base is an argument or global
3832 // value, make sure the GEP is not in the entry block. Otherwise,
3833 // instruction selection can undo the split. Also make sure the
3834 // parent block allows inserting non-PHI instructions before the
3835 // terminator.
3836 BasicBlock *Parent =
3837 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
3838 if (GEP->getParent() != Parent && !Parent->getTerminator()->isEHPad())
3839 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
3840 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003841 }
3842 AddrMode.BaseOffs -= ConstantOffset;
3843 return false;
3844 }
3845
3846 // Save the valid addressing mode in case we can't match.
3847 ExtAddrMode BackupAddrMode = AddrMode;
3848 unsigned OldSize = AddrModeInsts.size();
3849
3850 // See if the scale and offset amount is valid for this target.
3851 AddrMode.BaseOffs += ConstantOffset;
3852
3853 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003854 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003855 // If it couldn't be matched, just stuff the value in a register.
3856 if (AddrMode.HasBaseReg) {
3857 AddrMode = BackupAddrMode;
3858 AddrModeInsts.resize(OldSize);
3859 return false;
3860 }
3861 AddrMode.HasBaseReg = true;
3862 AddrMode.BaseReg = AddrInst->getOperand(0);
3863 }
3864
3865 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003866 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003867 Depth)) {
3868 // If it couldn't be matched, try stuffing the base into a register
3869 // instead of matching it, and retrying the match of the scale.
3870 AddrMode = BackupAddrMode;
3871 AddrModeInsts.resize(OldSize);
3872 if (AddrMode.HasBaseReg)
3873 return false;
3874 AddrMode.HasBaseReg = true;
3875 AddrMode.BaseReg = AddrInst->getOperand(0);
3876 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003877 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003878 VariableScale, Depth)) {
3879 // If even that didn't work, bail.
3880 AddrMode = BackupAddrMode;
3881 AddrModeInsts.resize(OldSize);
3882 return false;
3883 }
3884 }
3885
3886 return true;
3887 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003888 case Instruction::SExt:
3889 case Instruction::ZExt: {
3890 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3891 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003892 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003893
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003894 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003895 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003896 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003897 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003898 if (!TPH)
3899 return false;
3900
3901 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3902 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003903 unsigned CreatedInstsCost = 0;
3904 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003905 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003906 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003907 // SExt has been moved away.
3908 // Thus either it will be rematched later in the recursive calls or it is
3909 // gone. Anyway, we must not fold it into the addressing mode at this point.
3910 // E.g.,
3911 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003912 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003913 // addr = gep base, idx
3914 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003915 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003916 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3917 // addr = gep base, op <- match
3918 if (MovedAway)
3919 *MovedAway = true;
3920
3921 assert(PromotedOperand &&
3922 "TypePromotionHelper should have filtered out those cases");
3923
3924 ExtAddrMode BackupAddrMode = AddrMode;
3925 unsigned OldSize = AddrModeInsts.size();
3926
Sanjay Patelfc580a62015-09-21 23:03:16 +00003927 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003928 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003929 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003930 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003931 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003932 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003933 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003934 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003935 AddrMode = BackupAddrMode;
3936 AddrModeInsts.resize(OldSize);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003937 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003938 TPT.rollback(LastKnownGood);
3939 return false;
3940 }
3941 return true;
3942 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003943 }
3944 return false;
3945}
3946
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003947/// If we can, try to add the value of 'Addr' into the current addressing mode.
3948/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3949/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3950/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003951///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003952bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003953 // Start a transaction at this point that we will rollback if the matching
3954 // fails.
3955 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3956 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003957 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3958 // Fold in immediates if legal for the target.
3959 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003960 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003961 return true;
3962 AddrMode.BaseOffs -= CI->getSExtValue();
3963 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3964 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003965 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003966 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003967 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003968 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003969 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003970 }
3971 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3972 ExtAddrMode BackupAddrMode = AddrMode;
3973 unsigned OldSize = AddrModeInsts.size();
3974
3975 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003976 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003977 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003978 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003979 // to check here.
3980 if (MovedAway)
3981 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003982 // Okay, it's possible to fold this. Check to see if it is actually
3983 // *profitable* to do so. We use a simple cost model to avoid increasing
3984 // register pressure too much.
3985 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003986 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003987 AddrModeInsts.push_back(I);
3988 return true;
3989 }
Stephen Lin837bba12013-07-15 17:55:02 +00003990
Chandler Carruthc8925912013-01-05 02:09:22 +00003991 // It isn't profitable to do this, roll back.
3992 //cerr << "NOT FOLDING: " << *I;
3993 AddrMode = BackupAddrMode;
3994 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003995 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003996 }
3997 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003998 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003999 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004000 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004001 } else if (isa<ConstantPointerNull>(Addr)) {
4002 // Null pointer gets folded without affecting the addressing mode.
4003 return true;
4004 }
4005
4006 // Worse case, the target should support [reg] addressing modes. :)
4007 if (!AddrMode.HasBaseReg) {
4008 AddrMode.HasBaseReg = true;
4009 AddrMode.BaseReg = Addr;
4010 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004011 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004012 return true;
4013 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00004014 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004015 }
4016
4017 // If the base register is already taken, see if we can do [r+r].
4018 if (AddrMode.Scale == 0) {
4019 AddrMode.Scale = 1;
4020 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004021 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004022 return true;
4023 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00004024 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004025 }
4026 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004027 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004028 return false;
4029}
4030
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004031/// Check to see if all uses of OpVal by the specified inline asm call are due
4032/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00004033static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004034 const TargetLowering &TLI,
4035 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00004036 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00004037 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004038 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004039 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004040
Chandler Carruthc8925912013-01-05 02:09:22 +00004041 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4042 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00004043
Chandler Carruthc8925912013-01-05 02:09:22 +00004044 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004045 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00004046
4047 // If this asm operand is our Value*, and if it isn't an indirect memory
4048 // operand, we can't fold it!
4049 if (OpInfo.CallOperandVal == OpVal &&
4050 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4051 !OpInfo.isIndirect))
4052 return false;
4053 }
4054
4055 return true;
4056}
4057
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004058// Max number of memory uses to look at before aborting the search to conserve
4059// compile time.
4060static constexpr int MaxMemoryUsesToScan = 20;
4061
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004062/// Recursively walk all the uses of I until we find a memory use.
4063/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00004064/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00004065static bool FindAllMemoryUses(
4066 Instruction *I,
4067 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004068 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4069 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004070 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00004071 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00004072 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004073
Chandler Carruthc8925912013-01-05 02:09:22 +00004074 // If this is an obviously unfoldable instruction, bail out.
4075 if (!MightBeFoldableInst(I))
4076 return true;
4077
Philip Reamesac115ed2016-03-09 23:13:12 +00004078 const bool OptSize = I->getFunction()->optForSize();
4079
Chandler Carruthc8925912013-01-05 02:09:22 +00004080 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004081 for (Use &U : I->uses()) {
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004082 // Conservatively return true if we're seeing a large number or a deep chain
4083 // of users. This avoids excessive compilation times in pathological cases.
4084 if (SeenInsts++ >= MaxMemoryUsesToScan)
4085 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004086
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004087 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthcdf47882014-03-09 03:16:01 +00004088 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4089 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00004090 continue;
4091 }
Stephen Lin837bba12013-07-15 17:55:02 +00004092
Chandler Carruthcdf47882014-03-09 03:16:01 +00004093 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4094 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00004095 if (opNo != StoreInst::getPointerOperandIndex())
4096 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00004097 MemoryUses.push_back(std::make_pair(SI, opNo));
4098 continue;
4099 }
Stephen Lin837bba12013-07-15 17:55:02 +00004100
Matt Arsenault02d915b2017-03-15 22:35:20 +00004101 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4102 unsigned opNo = U.getOperandNo();
4103 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4104 return true; // Storing addr, not into addr.
4105 MemoryUses.push_back(std::make_pair(RMW, opNo));
4106 continue;
4107 }
4108
4109 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4110 unsigned opNo = U.getOperandNo();
4111 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4112 return true; // Storing addr, not into addr.
4113 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4114 continue;
4115 }
4116
Chandler Carruthcdf47882014-03-09 03:16:01 +00004117 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004118 // If this is a cold call, we can sink the addressing calculation into
4119 // the cold path. See optimizeCallInst
4120 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4121 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004122
Chandler Carruthc8925912013-01-05 02:09:22 +00004123 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4124 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004125
Chandler Carruthc8925912013-01-05 02:09:22 +00004126 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004127 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004128 return true;
4129 continue;
4130 }
Stephen Lin837bba12013-07-15 17:55:02 +00004131
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004132 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4133 SeenInsts))
Chandler Carruthc8925912013-01-05 02:09:22 +00004134 return true;
4135 }
4136
4137 return false;
4138}
4139
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004140/// Return true if Val is already known to be live at the use site that we're
4141/// folding it into. If so, there is no cost to include it in the addressing
4142/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4143/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004144bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004145 Value *KnownLive2) {
4146 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004147 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004148 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004149
Chandler Carruthc8925912013-01-05 02:09:22 +00004150 // All values other than instructions and arguments (e.g. constants) are live.
4151 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004152
Chandler Carruthc8925912013-01-05 02:09:22 +00004153 // If Val is a constant sized alloca in the entry block, it is live, this is
4154 // true because it is just a reference to the stack/frame pointer, which is
4155 // live for the whole function.
4156 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4157 if (AI->isStaticAlloca())
4158 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004159
Chandler Carruthc8925912013-01-05 02:09:22 +00004160 // Check to see if this value is already used in the memory instruction's
4161 // block. If so, it's already live into the block at the very least, so we
4162 // can reasonably fold it.
4163 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4164}
4165
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004166/// It is possible for the addressing mode of the machine to fold the specified
4167/// instruction into a load or store that ultimately uses it.
4168/// However, the specified instruction has multiple uses.
4169/// Given this, it may actually increase register pressure to fold it
4170/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004171///
4172/// X = ...
4173/// Y = X+1
4174/// use(Y) -> nonload/store
4175/// Z = Y+1
4176/// load Z
4177///
4178/// In this case, Y has multiple uses, and can be folded into the load of Z
4179/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4180/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4181/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4182/// number of computations either.
4183///
4184/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4185/// X was live across 'load Z' for other reasons, we actually *would* want to
4186/// fold the addressing mode in the Z case. This would make Y die earlier.
4187bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004188isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004189 ExtAddrMode &AMAfter) {
4190 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004191
Chandler Carruthc8925912013-01-05 02:09:22 +00004192 // AMBefore is the addressing mode before this instruction was folded into it,
4193 // and AMAfter is the addressing mode after the instruction was folded. Get
4194 // the set of registers referenced by AMAfter and subtract out those
4195 // referenced by AMBefore: this is the set of values which folding in this
4196 // address extends the lifetime of.
4197 //
4198 // Note that there are only two potential values being referenced here,
4199 // BaseReg and ScaleReg (global addresses are always available, as are any
4200 // folded immediates).
4201 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004202
Chandler Carruthc8925912013-01-05 02:09:22 +00004203 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4204 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004205 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004206 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004207 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004208 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004209
4210 // If folding this instruction (and it's subexprs) didn't extend any live
4211 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004212 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004213 return true;
4214
Philip Reamesac115ed2016-03-09 23:13:12 +00004215 // If all uses of this instruction can have the address mode sunk into them,
4216 // we can remove the addressing mode and effectively trade one live register
4217 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004218 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004219 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4220 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004221 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004222 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004223
Chandler Carruthc8925912013-01-05 02:09:22 +00004224 // Now that we know that all uses of this instruction are part of a chain of
4225 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004226 // into a memory use, loop over each of these memory operation uses and see
4227 // if they could *actually* fold the instruction. The assumption is that
4228 // addressing modes are cheap and that duplicating the computation involved
4229 // many times is worthwhile, even on a fastpath. For sinking candidates
4230 // (i.e. cold call sites), this serves as a way to prevent excessive code
4231 // growth since most architectures have some reasonable small and fast way to
4232 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004233 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4234 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4235 Instruction *User = MemoryUses[i].first;
4236 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004237
Chandler Carruthc8925912013-01-05 02:09:22 +00004238 // Get the access type of this use. If the use isn't a pointer, we don't
4239 // know what it accesses.
4240 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004241 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4242 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004243 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004244 Type *AddressAccessTy = AddrTy->getElementType();
4245 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004246
Chandler Carruthc8925912013-01-05 02:09:22 +00004247 // Do a match against the root of this address, ignoring profitability. This
4248 // will tell us if the addressing mode for the memory operation will
4249 // *actually* cover the shared instruction.
4250 ExtAddrMode Result;
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004251 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4252 0);
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004253 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4254 TPT.getRestorationPoint();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004255 AddressingModeMatcher Matcher(
4256 MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result,
4257 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Chandler Carruthc8925912013-01-05 02:09:22 +00004258 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004259 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004260 (void)Success; assert(Success && "Couldn't select *anything*?");
4261
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004262 // The match was to check the profitability, the changes made are not
4263 // part of the original matcher. Therefore, they should be dropped
4264 // otherwise the original matcher will not present the right state.
4265 TPT.rollback(LastKnownGood);
4266
Chandler Carruthc8925912013-01-05 02:09:22 +00004267 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004268 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004269 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004270
Chandler Carruthc8925912013-01-05 02:09:22 +00004271 MatchedAddrModeInsts.clear();
4272 }
Stephen Lin837bba12013-07-15 17:55:02 +00004273
Chandler Carruthc8925912013-01-05 02:09:22 +00004274 return true;
4275}
4276
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004277/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004278/// different basic block than BB.
4279static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4280 if (Instruction *I = dyn_cast<Instruction>(V))
4281 return I->getParent() != BB;
4282 return false;
4283}
4284
Philip Reamesac115ed2016-03-09 23:13:12 +00004285/// Sink addressing mode computation immediate before MemoryInst if doing so
4286/// can be done without increasing register pressure. The need for the
4287/// register pressure constraint means this can end up being an all or nothing
4288/// decision for all uses of the same addressing computation.
4289///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004290/// Load and Store Instructions often have addressing modes that can do
4291/// significant amounts of computation. As such, instruction selection will try
4292/// to get the load or store to do as much computation as possible for the
4293/// program. The problem is that isel can only see within a single block. As
4294/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004295///
4296/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004297/// operands. It's also used to sink addressing computations feeding into cold
4298/// call sites into their (cold) basic block.
4299///
4300/// The motivation for handling sinking into cold blocks is that doing so can
4301/// both enable other address mode sinking (by satisfying the register pressure
4302/// constraint above), and reduce register pressure globally (by removing the
4303/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004304bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004305 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004306 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004307
4308 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004309 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004310 SmallVector<Value*, 8> worklist;
4311 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004312 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004313
John Brawneb83c752017-10-03 13:04:15 +00004314 // Use a worklist to iteratively look through PHI and select nodes, and
4315 // ensure that the addressing mode obtained from the non-PHI/select roots of
John Brawn736bf002017-10-03 13:08:22 +00004316 // the graph are compatible.
John Brawneb83c752017-10-03 13:04:15 +00004317 bool PhiOrSelectSeen = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004318 SmallVector<Instruction*, 16> AddrModeInsts;
Serguei Katkovaee63752017-11-05 07:59:02 +00004319 const SimplifyQuery SQ(*DL, TLInfo);
4320 AddressingModeCombiner AddrModes(SQ, { Addr, MemoryInst->getParent() });
Jun Bum Limdee55652017-04-03 19:20:07 +00004321 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004322 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4323 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004324 while (!worklist.empty()) {
4325 Value *V = worklist.back();
4326 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004327
Serguei Katkov4ea855e2017-07-19 04:49:17 +00004328 // We allow traversing cyclic Phi nodes.
4329 // In case of success after this loop we ensure that traversing through
4330 // Phi nodes ends up with all cases to compute address of the form
4331 // BaseGV + Base + Scale * Index + Offset
4332 // where Scale and Offset are constans and BaseGV, Base and Index
4333 // are exactly the same Values in all cases.
4334 // It means that BaseGV, Scale and Offset dominate our memory instruction
4335 // and have the same value as they had in address computation represented
4336 // as Phi. So we can safely sink address computation to memory instruction.
4337 if (!Visited.insert(V).second)
4338 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00004339
Owen Anderson8ba5f392010-11-27 08:15:55 +00004340 // For a PHI node, push all of its incoming values.
4341 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004342 for (Value *IncValue : P->incoming_values())
4343 worklist.push_back(IncValue);
John Brawneb83c752017-10-03 13:04:15 +00004344 PhiOrSelectSeen = true;
4345 continue;
4346 }
4347 // Similar for select.
4348 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4349 worklist.push_back(SI->getFalseValue());
4350 worklist.push_back(SI->getTrueValue());
4351 PhiOrSelectSeen = true;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004352 continue;
4353 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004354
Philip Reamesac115ed2016-03-09 23:13:12 +00004355 // For non-PHIs, determine the addressing mode being computed. Note that
4356 // the result may differ depending on what other uses our candidate
4357 // addressing instructions might have.
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004358 AddrModeInsts.clear();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004359 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4360 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004361 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004362 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004363 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004364
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004365 GetElementPtrInst *GEP = LargeOffsetGEP.first;
4366 if (GEP && GEP->getParent() != MemoryInst->getParent() &&
4367 !NewGEPBases.count(GEP)) {
4368 // If splitting the underlying data structure can reduce the offset of a
4369 // GEP, collect the GEP. Skip the GEPs that are the new bases of
4370 // previously split data structures.
4371 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
4372 if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
4373 LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
4374 }
4375
4376 NewAddrMode.OriginalValue = V;
John Brawn736bf002017-10-03 13:08:22 +00004377 if (!AddrModes.addNewAddrMode(NewAddrMode))
4378 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004379 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004380
John Brawn736bf002017-10-03 13:08:22 +00004381 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4382 // or we have multiple but either couldn't combine them or combining them
4383 // wouldn't do anything useful, bail out now.
4384 if (!AddrModes.combineAddrModes()) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004385 TPT.rollback(LastKnownGood);
4386 return false;
4387 }
4388 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004389
John Brawn736bf002017-10-03 13:08:22 +00004390 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4391 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4392
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004393 // If all the instructions matched are already in this BB, don't do anything.
John Brawneb83c752017-10-03 13:04:15 +00004394 // If we saw a Phi node then it is not local definitely, and if we saw a select
4395 // then we want to push the address calculation past it even if it's already
4396 // in this BB.
4397 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
Justin Lebar838c7f52016-11-21 22:49:11 +00004398 return IsNonLocalValue(V, MemoryInst->getParent());
Serguei Katkov0b7b59a2017-07-11 06:24:44 +00004399 })) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004400 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
4401 << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004402 return false;
4403 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004404
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004405 // Insert this computation right after this user. Since our caller is
4406 // scanning from the top of the BB to the bottom, reuse of the expr are
4407 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004408 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004409
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004410 // Now that we determined the addressing expression we want to use and know
4411 // that we have to sink it into this block. Check to see if we have already
Simon Dardis230f4532017-11-24 16:45:28 +00004412 // done this for some other load/store instr in this block. If so, reuse
4413 // the computation. Before attempting reuse, check if the address is valid
4414 // as it may have been erased.
4415
4416 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
4417
4418 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004419 if (SunkAddr) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004420 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
4421 << " for " << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004422 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004423 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004424 } else if (AddrSinkUsingGEPs ||
David Blaikie8ad9a972018-03-28 22:28:50 +00004425 (!AddrSinkUsingGEPs.getNumOccurrences() && TM && TTI->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004426 // By default, we use the GEP-based method when AA is used later. This
4427 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004428 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4429 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004430 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004431 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004432
4433 // First, find the pointer.
4434 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4435 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004436 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004437 }
4438
4439 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4440 // We can't add more than one pointer together, nor can we scale a
4441 // pointer (both of which seem meaningless).
4442 if (ResultPtr || AddrMode.Scale != 1)
4443 return false;
4444
4445 ResultPtr = AddrMode.ScaledReg;
4446 AddrMode.Scale = 0;
4447 }
4448
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004449 // It is only safe to sign extend the BaseReg if we know that the math
4450 // required to create it did not overflow before we extend it. Since
4451 // the original IR value was tossed in favor of a constant back when
4452 // the AddrMode was created we need to bail out gracefully if widths
4453 // do not match instead of extending it.
4454 //
4455 // (See below for code to add the scale.)
4456 if (AddrMode.Scale) {
4457 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4458 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4459 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4460 return false;
4461 }
4462
Hal Finkelc3998302014-04-12 00:59:48 +00004463 if (AddrMode.BaseGV) {
4464 if (ResultPtr)
4465 return false;
4466
4467 ResultPtr = AddrMode.BaseGV;
4468 }
4469
4470 // If the real base value actually came from an inttoptr, then the matcher
4471 // will look through it and provide only the integer value. In that case,
4472 // use it here.
Keno Fischer05e4ac22017-06-29 20:28:59 +00004473 if (!DL->isNonIntegralPointerType(Addr->getType())) {
4474 if (!ResultPtr && AddrMode.BaseReg) {
4475 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4476 "sunkaddr");
4477 AddrMode.BaseReg = nullptr;
4478 } else if (!ResultPtr && AddrMode.Scale == 1) {
4479 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4480 "sunkaddr");
4481 AddrMode.Scale = 0;
4482 }
Hal Finkelc3998302014-04-12 00:59:48 +00004483 }
4484
4485 if (!ResultPtr &&
4486 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4487 SunkAddr = Constant::getNullValue(Addr->getType());
4488 } else if (!ResultPtr) {
4489 return false;
4490 } else {
4491 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004492 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4493 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004494
4495 // Start with the base register. Do this first so that subsequent address
4496 // matching finds it last, which will prevent it from trying to match it
4497 // as the scaled value in case it happens to be a mul. That would be
4498 // problematic if we've sunk a different mul for the scale, because then
4499 // we'd end up sinking both muls.
4500 if (AddrMode.BaseReg) {
4501 Value *V = AddrMode.BaseReg;
4502 if (V->getType() != IntPtrTy)
4503 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4504
4505 ResultIndex = V;
4506 }
4507
4508 // Add the scale value.
4509 if (AddrMode.Scale) {
4510 Value *V = AddrMode.ScaledReg;
4511 if (V->getType() == IntPtrTy) {
4512 // done.
Hal Finkelc3998302014-04-12 00:59:48 +00004513 } else {
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004514 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4515 cast<IntegerType>(V->getType())->getBitWidth() &&
4516 "We can't transform if ScaledReg is too narrow");
4517 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004518 }
4519
4520 if (AddrMode.Scale != 1)
4521 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4522 "sunkaddr");
4523 if (ResultIndex)
4524 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4525 else
4526 ResultIndex = V;
4527 }
4528
4529 // Add in the Base Offset if present.
4530 if (AddrMode.BaseOffs) {
4531 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4532 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004533 // We need to add this separately from the scale above to help with
4534 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004535 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004536 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004537 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004538 }
4539
4540 ResultIndex = V;
4541 }
4542
4543 if (!ResultIndex) {
4544 SunkAddr = ResultPtr;
4545 } else {
4546 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004547 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004548 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004549 }
4550
4551 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004552 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004553 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004554 } else {
Keno Fischer05e4ac22017-06-29 20:28:59 +00004555 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4556 // non-integral pointers, so in that case bail out now.
4557 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4558 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4559 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4560 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4561 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4562 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4563 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4564 (AddrMode.BaseGV &&
4565 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4566 return false;
4567
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004568 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4569 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004570 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004571 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004572
4573 // Start with the base register. Do this first so that subsequent address
4574 // matching finds it last, which will prevent it from trying to match it
4575 // as the scaled value in case it happens to be a mul. That would be
4576 // problematic if we've sunk a different mul for the scale, because then
4577 // we'd end up sinking both muls.
4578 if (AddrMode.BaseReg) {
4579 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004580 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004581 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004582 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004583 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004584 Result = V;
4585 }
4586
4587 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004588 if (AddrMode.Scale) {
4589 Value *V = AddrMode.ScaledReg;
4590 if (V->getType() == IntPtrTy) {
4591 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004592 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004593 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004594 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4595 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004596 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004597 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004598 // It is only safe to sign extend the BaseReg if we know that the math
4599 // required to create it did not overflow before we extend it. Since
4600 // the original IR value was tossed in favor of a constant back when
4601 // the AddrMode was created we need to bail out gracefully if widths
4602 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004603 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004604 if (I && (Result != AddrMode.BaseReg))
4605 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004606 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004607 }
4608 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004609 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4610 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004611 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004612 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004613 else
4614 Result = V;
4615 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004616
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004617 // Add in the BaseGV if present.
4618 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004619 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004620 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004621 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004622 else
4623 Result = V;
4624 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004625
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004626 // Add in the Base Offset if present.
4627 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004628 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004629 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004630 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004631 else
4632 Result = V;
4633 }
4634
Craig Topperc0196b12014-04-14 00:51:57 +00004635 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004636 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004637 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004638 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004639 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004640
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004641 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Simon Dardis230f4532017-11-24 16:45:28 +00004642 // Store the newly computed address into the cache. In the case we reused a
4643 // value, this should be idempotent.
4644 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004645
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004646 // If we have no uses, recursively delete the value and all dead instructions
4647 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004648 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004649 // This can cause recursive deletion, which can invalidate our iterator.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004650 // Use a WeakTrackingVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004651 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004652 WeakTrackingVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004653 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004654
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004655 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004656
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004657 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004658 // If the iterator instruction was recursively deleted, start over at the
4659 // start of the block.
4660 CurInstIterator = BB->begin();
4661 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004662 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004663 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004664 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004665 return true;
4666}
4667
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004668/// If there are any memory operands, use OptimizeMemoryInst to sink their
4669/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004670bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004671 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004672
Eric Christopher11e4df72015-02-26 22:38:43 +00004673 const TargetRegisterInfo *TRI =
Sanjay Patel4137d512017-06-07 14:29:52 +00004674 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004675 TargetLowering::AsmOperandInfoVector TargetConstraints =
4676 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004677 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004678 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4679 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004680
Evan Cheng1da25002008-02-26 02:42:37 +00004681 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004682 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004683
Eli Friedman666bbe32008-02-26 18:37:49 +00004684 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4685 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004686 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004687 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004688 } else if (OpInfo.Type == InlineAsm::isInput)
4689 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004690 }
4691
4692 return MadeChange;
4693}
4694
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004695/// Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004696/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00004697static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4698 assert(!Val->use_empty() && "Input must have at least one use");
4699 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004700 bool IsSExt = isa<SExtInst>(FirstUser);
4701 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00004702 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004703 const Instruction *UI = cast<Instruction>(U);
4704 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4705 return false;
4706 Type *CurTy = UI->getType();
4707 // Same input and output types: Same instruction after CSE.
4708 if (CurTy == ExtTy)
4709 continue;
4710
4711 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00004712 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004713 // b = sext ty1 a to ty2
4714 // c = sext ty1 a to ty3
4715 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00004716 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004717 // b = sext ty1 a to ty2
4718 // c = sext ty2 b to ty3
4719 // However, the last sext is not free.
4720 if (IsSExt)
4721 return false;
4722
4723 // This is a ZExt, maybe this is free to extend from one type to another.
4724 // In that case, we would not account for a different use.
4725 Type *NarrowTy;
4726 Type *LargeTy;
4727 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4728 CurTy->getScalarType()->getIntegerBitWidth()) {
4729 NarrowTy = CurTy;
4730 LargeTy = ExtTy;
4731 } else {
4732 NarrowTy = ExtTy;
4733 LargeTy = CurTy;
4734 }
4735
4736 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4737 return false;
4738 }
4739 // All uses are the same or can be derived from one another for free.
4740 return true;
4741}
4742
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004743/// Try to speculatively promote extensions in \p Exts and continue
Jun Bum Lim42301012017-03-17 19:05:21 +00004744/// promoting through newly promoted operands recursively as far as doing so is
4745/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4746/// When some promotion happened, \p TPT contains the proper state to revert
4747/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004748///
Jun Bum Lim42301012017-03-17 19:05:21 +00004749/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00004750bool CodeGenPrepare::tryToPromoteExts(
4751 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4752 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4753 unsigned CreatedInstsCost) {
4754 bool Promoted = false;
4755
4756 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004757 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004758 // Early check if we directly have ext(load).
4759 if (isa<LoadInst>(I->getOperand(0))) {
4760 ProfitablyMovedExts.push_back(I);
4761 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004762 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004763
4764 // Check whether or not we want to do any promotion. The reason we have
4765 // this check inside the for loop is to catch the case where an extension
4766 // is directly fed by a load because in such case the extension can be moved
4767 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004768 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00004769 return false;
4770
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004771 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00004772 TypePromotionHelper::Action TPH =
4773 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004774 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00004775 if (!TPH) {
4776 // Save the current extension as we cannot move up through its operand.
4777 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004778 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00004779 }
4780
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004781 // Save the current state.
4782 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4783 TPT.getRestorationPoint();
4784 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004785 unsigned NewCreatedInstsCost = 0;
4786 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004787 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004788 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4789 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004790 assert(PromotedVal &&
4791 "TypePromotionHelper should have filtered out those cases");
4792
4793 // We would be able to merge only one extension in a load.
4794 // Therefore, if we have more than 1 new extension we heuristically
4795 // cut this search path, because it means we degrade the code quality.
4796 // With exactly 2, the transformation is neutral, because we will merge
4797 // one extension but leave one. However, we optimistically keep going,
4798 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004799 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004800 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00004801 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004802 TotalCreatedInstsCost =
4803 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004804 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004805 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004806 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004807 // This promotion is not profitable, rollback to the previous state, and
4808 // save the current extension in ProfitablyMovedExts as the latest
4809 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004810 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00004811 ProfitablyMovedExts.push_back(I);
4812 continue;
4813 }
4814 // Continue promoting NewExts as far as doing so is profitable.
4815 SmallVector<Instruction *, 2> NewlyMovedExts;
4816 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4817 bool NewPromoted = false;
4818 for (auto ExtInst : NewlyMovedExts) {
4819 Instruction *MovedExt = cast<Instruction>(ExtInst);
4820 Value *ExtOperand = MovedExt->getOperand(0);
4821 // If we have reached to a load, we need this extra profitability check
4822 // as it could potentially be merged into an ext(load).
4823 if (isa<LoadInst>(ExtOperand) &&
4824 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4825 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
4826 continue;
4827
4828 ProfitablyMovedExts.push_back(MovedExt);
4829 NewPromoted = true;
4830 }
4831
4832 // If none of speculative promotions for NewExts is profitable, rollback
4833 // and save the current extension (I) as the last profitable extension.
4834 if (!NewPromoted) {
4835 TPT.rollback(LastKnownGood);
4836 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004837 continue;
4838 }
4839 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00004840 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004841 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004842 return Promoted;
4843}
4844
Jun Bum Limdee55652017-04-03 19:20:07 +00004845/// Merging redundant sexts when one is dominating the other.
4846bool CodeGenPrepare::mergeSExts(Function &F) {
4847 DominatorTree DT(F);
4848 bool Changed = false;
4849 for (auto &Entry : ValToSExtendedUses) {
4850 SExts &Insts = Entry.second;
4851 SExts CurPts;
4852 for (Instruction *Inst : Insts) {
4853 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
4854 Inst->getOperand(0) != Entry.first)
4855 continue;
4856 bool inserted = false;
4857 for (auto &Pt : CurPts) {
4858 if (DT.dominates(Inst, Pt)) {
4859 Pt->replaceAllUsesWith(Inst);
4860 RemovedInsts.insert(Pt);
4861 Pt->removeFromParent();
4862 Pt = Inst;
4863 inserted = true;
4864 Changed = true;
4865 break;
4866 }
4867 if (!DT.dominates(Pt, Inst))
4868 // Give up if we need to merge in a common dominator as the
4869 // expermients show it is not profitable.
4870 continue;
4871 Inst->replaceAllUsesWith(Pt);
4872 RemovedInsts.insert(Inst);
4873 Inst->removeFromParent();
4874 inserted = true;
4875 Changed = true;
4876 break;
4877 }
4878 if (!inserted)
4879 CurPts.push_back(Inst);
4880 }
4881 }
4882 return Changed;
4883}
4884
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004885// Spliting large data structures so that the GEPs accessing them can have
4886// smaller offsets so that they can be sunk to the same blocks as their users.
4887// For example, a large struct starting from %base is splitted into two parts
4888// where the second part starts from %new_base.
4889//
4890// Before:
4891// BB0:
4892// %base =
4893//
4894// BB1:
4895// %gep0 = gep %base, off0
4896// %gep1 = gep %base, off1
4897// %gep2 = gep %base, off2
4898//
4899// BB2:
4900// %load1 = load %gep0
4901// %load2 = load %gep1
4902// %load3 = load %gep2
4903//
4904// After:
4905// BB0:
4906// %base =
4907// %new_base = gep %base, off0
4908//
4909// BB1:
4910// %new_gep0 = %new_base
4911// %new_gep1 = gep %new_base, off1 - off0
4912// %new_gep2 = gep %new_base, off2 - off0
4913//
4914// BB2:
4915// %load1 = load i32, i32* %new_gep0
4916// %load2 = load i32, i32* %new_gep1
4917// %load3 = load i32, i32* %new_gep2
4918//
4919// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
4920// their offsets are smaller enough to fit into the addressing mode.
4921bool CodeGenPrepare::splitLargeGEPOffsets() {
4922 bool Changed = false;
4923 for (auto &Entry : LargeOffsetGEPMap) {
4924 Value *OldBase = Entry.first;
4925 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
4926 &LargeOffsetGEPs = Entry.second;
4927 auto compareGEPOffset =
4928 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
4929 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
4930 if (LHS.first == RHS.first)
4931 return false;
4932 if (LHS.second != RHS.second)
4933 return LHS.second < RHS.second;
4934 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
4935 };
4936 // Sorting all the GEPs of the same data structures based on the offsets.
4937 llvm::sort(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end(),
4938 compareGEPOffset);
4939 LargeOffsetGEPs.erase(
4940 std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()),
4941 LargeOffsetGEPs.end());
4942 // Skip if all the GEPs have the same offsets.
4943 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
4944 continue;
4945 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
4946 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
4947 Value *NewBaseGEP = nullptr;
4948
4949 auto LargeOffsetGEP = LargeOffsetGEPs.begin();
4950 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
4951 GetElementPtrInst *GEP = LargeOffsetGEP->first;
4952 int64_t Offset = LargeOffsetGEP->second;
4953 if (Offset != BaseOffset) {
4954 TargetLowering::AddrMode AddrMode;
4955 AddrMode.BaseOffs = Offset - BaseOffset;
4956 // The result type of the GEP might not be the type of the memory
4957 // access.
4958 if (!TLI->isLegalAddressingMode(*DL, AddrMode,
4959 GEP->getResultElementType(),
4960 GEP->getAddressSpace())) {
4961 // We need to create a new base if the offset to the current base is
4962 // too large to fit into the addressing mode. So, a very large struct
4963 // may be splitted into several parts.
4964 BaseGEP = GEP;
4965 BaseOffset = Offset;
4966 NewBaseGEP = nullptr;
4967 }
4968 }
4969
4970 // Generate a new GEP to replace the current one.
4971 IRBuilder<> Builder(GEP);
4972 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
4973 Type *I8PtrTy =
4974 Builder.getInt8PtrTy(GEP->getType()->getPointerAddressSpace());
4975 Type *I8Ty = Builder.getInt8Ty();
4976
4977 if (!NewBaseGEP) {
4978 // Create a new base if we don't have one yet. Find the insertion
4979 // pointer for the new base first.
4980 BasicBlock::iterator NewBaseInsertPt;
4981 BasicBlock *NewBaseInsertBB;
4982 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
4983 // If the base of the struct is an instruction, the new base will be
4984 // inserted close to it.
4985 NewBaseInsertBB = BaseI->getParent();
4986 if (isa<PHINode>(BaseI))
4987 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
4988 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
4989 NewBaseInsertBB =
4990 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
4991 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
4992 } else
4993 NewBaseInsertPt = std::next(BaseI->getIterator());
4994 } else {
4995 // If the current base is an argument or global value, the new base
4996 // will be inserted to the entry block.
4997 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
4998 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
4999 }
5000 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
5001 // Create a new base.
5002 Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset);
5003 NewBaseGEP = OldBase;
5004 if (NewBaseGEP->getType() != I8PtrTy)
5005 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
5006 NewBaseGEP =
5007 NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep");
5008 NewGEPBases.insert(NewBaseGEP);
5009 }
5010
5011 Value *NewGEP = NewBaseGEP;
5012 if (Offset == BaseOffset) {
5013 if (GEP->getType() != I8PtrTy)
5014 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5015 } else {
5016 // Calculate the new offset for the new GEP.
5017 Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset);
5018 NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index);
5019
5020 if (GEP->getType() != I8PtrTy)
5021 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5022 }
5023 GEP->replaceAllUsesWith(NewGEP);
5024 LargeOffsetGEPID.erase(GEP);
5025 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
5026 GEP->eraseFromParent();
5027 Changed = true;
5028 }
5029 }
5030 return Changed;
5031}
5032
Jun Bum Lim42301012017-03-17 19:05:21 +00005033/// Return true, if an ext(load) can be formed from an extension in
5034/// \p MovedExts.
5035bool CodeGenPrepare::canFormExtLd(
5036 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
5037 Instruction *&Inst, bool HasPromoted) {
5038 for (auto *MovedExtInst : MovedExts) {
5039 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
5040 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
5041 Inst = MovedExtInst;
5042 break;
5043 }
5044 }
5045 if (!LI)
5046 return false;
5047
5048 // If they're already in the same block, there's nothing to do.
5049 // Make the cheap checks first if we did not promote.
5050 // If we promoted, we need to check if it is indeed profitable.
5051 if (!HasPromoted && LI->getParent() == Inst->getParent())
5052 return false;
5053
Haicheng Wuabdef9e2017-07-15 02:12:16 +00005054 return TLI->isExtLoad(LI, Inst, *DL);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005055}
5056
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005057/// Move a zext or sext fed by a load into the same basic block as the load,
5058/// unless conditions are unfavorable. This allows SelectionDAG to fold the
5059/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00005060///
Jun Bum Limdee55652017-04-03 19:20:07 +00005061/// E.g.,
5062/// \code
5063/// %ld = load i32* %addr
5064/// %add = add nuw i32 %ld, 4
5065/// %zext = zext i32 %add to i64
5066// \endcode
5067/// =>
5068/// \code
5069/// %ld = load i32* %addr
5070/// %zext = zext i32 %ld to i64
5071/// %add = add nuw i64 %zext, 4
5072/// \encode
5073/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
5074/// allow us to match zext(load i32*) to i64.
5075///
5076/// Also, try to promote the computations used to obtain a sign extended
5077/// value used into memory accesses.
5078/// E.g.,
5079/// \code
5080/// a = add nsw i32 b, 3
5081/// d = sext i32 a to i64
5082/// e = getelementptr ..., i64 d
5083/// \endcode
5084/// =>
5085/// \code
5086/// f = sext i32 b to i64
5087/// a = add nsw i64 f, 3
5088/// e = getelementptr ..., i64 a
5089/// \endcode
5090///
5091/// \p Inst[in/out] the extension may be modified during the process if some
5092/// promotions apply.
5093bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
5094 // ExtLoad formation and address type promotion infrastructure requires TLI to
5095 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00005096 if (!TLI)
5097 return false;
5098
Jun Bum Limdee55652017-04-03 19:20:07 +00005099 bool AllowPromotionWithoutCommonHeader = false;
5100 /// See if it is an interesting sext operations for the address type
5101 /// promotion before trying to promote it, e.g., the ones with the right
5102 /// type and used in memory accesses.
5103 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
5104 *Inst, AllowPromotionWithoutCommonHeader);
5105 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005106 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00005107 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005108 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00005109 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
5110 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00005111
Jun Bum Limdee55652017-04-03 19:20:07 +00005112 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00005113
Dan Gohman99429a02009-10-16 20:59:35 +00005114 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005115 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00005116 Instruction *ExtFedByLoad;
5117
5118 // Try to promote a chain of computation if it allows to form an extended
5119 // load.
5120 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
5121 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
5122 TPT.commit();
5123 // Move the extend into the same block as the load
Sanjay Patel674d2c22017-08-29 14:07:48 +00005124 ExtFedByLoad->moveAfter(LI);
Jun Bum Limdee55652017-04-03 19:20:07 +00005125 // CGP does not check if the zext would be speculatively executed when moved
5126 // to the same basic block as the load. Preserving its original location
5127 // would pessimize the debugging experience, as well as negatively impact
5128 // the quality of sample pgo. We don't want to use "line 0" as that has a
5129 // size cost in the line-table section and logically the zext can be seen as
5130 // part of the load. Therefore we conservatively reuse the same debug
5131 // location for the load and the zext.
5132 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
5133 ++NumExtsMoved;
5134 Inst = ExtFedByLoad;
5135 return true;
5136 }
5137
5138 // Continue promoting SExts if known as considerable depending on targets.
5139 if (ATPConsiderable &&
5140 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
5141 HasPromoted, TPT, SpeculativelyMovedExts))
5142 return true;
5143
5144 TPT.rollback(LastKnownGood);
5145 return false;
5146}
5147
5148// Perform address type promotion if doing so is profitable.
5149// If AllowPromotionWithoutCommonHeader == false, we should find other sext
5150// instructions that sign extended the same initial value. However, if
5151// AllowPromotionWithoutCommonHeader == true, we expect promoting the
5152// extension is just profitable.
5153bool CodeGenPrepare::performAddressTypePromotion(
5154 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
5155 bool HasPromoted, TypePromotionTransaction &TPT,
5156 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
5157 bool Promoted = false;
5158 SmallPtrSet<Instruction *, 1> UnhandledExts;
5159 bool AllSeenFirst = true;
5160 for (auto I : SpeculativelyMovedExts) {
5161 Value *HeadOfChain = I->getOperand(0);
5162 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
5163 SeenChainsForSExt.find(HeadOfChain);
5164 // If there is an unhandled SExt which has the same header, try to promote
5165 // it as well.
5166 if (AlreadySeen != SeenChainsForSExt.end()) {
5167 if (AlreadySeen->second != nullptr)
5168 UnhandledExts.insert(AlreadySeen->second);
5169 AllSeenFirst = false;
5170 }
5171 }
5172
5173 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
5174 SpeculativelyMovedExts.size() == 1)) {
5175 TPT.commit();
5176 if (HasPromoted)
5177 Promoted = true;
5178 for (auto I : SpeculativelyMovedExts) {
5179 Value *HeadOfChain = I->getOperand(0);
5180 SeenChainsForSExt[HeadOfChain] = nullptr;
5181 ValToSExtendedUses[HeadOfChain].push_back(I);
5182 }
5183 // Update Inst as promotion happen.
5184 Inst = SpeculativelyMovedExts.pop_back_val();
5185 } else {
5186 // This is the first chain visited from the header, keep the current chain
5187 // as unhandled. Defer to promote this until we encounter another SExt
5188 // chain derived from the same header.
5189 for (auto I : SpeculativelyMovedExts) {
5190 Value *HeadOfChain = I->getOperand(0);
5191 SeenChainsForSExt[HeadOfChain] = Inst;
5192 }
Dan Gohman99429a02009-10-16 20:59:35 +00005193 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005194 }
Dan Gohman99429a02009-10-16 20:59:35 +00005195
Jun Bum Limdee55652017-04-03 19:20:07 +00005196 if (!AllSeenFirst && !UnhandledExts.empty())
5197 for (auto VisitedSExt : UnhandledExts) {
5198 if (RemovedInsts.count(VisitedSExt))
5199 continue;
5200 TypePromotionTransaction TPT(RemovedInsts);
5201 SmallVector<Instruction *, 1> Exts;
5202 SmallVector<Instruction *, 2> Chains;
5203 Exts.push_back(VisitedSExt);
5204 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
5205 TPT.commit();
5206 if (HasPromoted)
5207 Promoted = true;
5208 for (auto I : Chains) {
5209 Value *HeadOfChain = I->getOperand(0);
5210 // Mark this as handled.
5211 SeenChainsForSExt[HeadOfChain] = nullptr;
5212 ValToSExtendedUses[HeadOfChain].push_back(I);
5213 }
5214 }
5215 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00005216}
5217
Sanjay Patelfc580a62015-09-21 23:03:16 +00005218bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00005219 BasicBlock *DefBB = I->getParent();
5220
Bob Wilsonff714f92010-09-21 21:44:14 +00005221 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00005222 // other uses of the source with result of extension.
5223 Value *Src = I->getOperand(0);
5224 if (Src->hasOneUse())
5225 return false;
5226
Evan Cheng2011df42007-12-13 07:50:36 +00005227 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00005228 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00005229 return false;
5230
Evan Cheng7bc89422007-12-12 00:51:06 +00005231 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00005232 // this block.
5233 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00005234 return false;
5235
Evan Chengd3d80172007-12-05 23:58:20 +00005236 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005237 for (User *U : I->users()) {
5238 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00005239
5240 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005241 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00005242 if (UserBB == DefBB) continue;
5243 DefIsLiveOut = true;
5244 break;
5245 }
5246 if (!DefIsLiveOut)
5247 return false;
5248
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00005249 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005250 for (User *U : Src->users()) {
5251 Instruction *UI = cast<Instruction>(U);
5252 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00005253 if (UserBB == DefBB) continue;
5254 // Be conservative. We don't want this xform to end up introducing
5255 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005256 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00005257 return false;
5258 }
5259
Evan Chengd3d80172007-12-05 23:58:20 +00005260 // InsertedTruncs - Only insert one trunc in each block once.
5261 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5262
5263 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005264 for (Use &U : Src->uses()) {
5265 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00005266
5267 // Figure out which BB this ext is used in.
5268 BasicBlock *UserBB = User->getParent();
5269 if (UserBB == DefBB) continue;
5270
5271 // Both src and def are live in this block. Rewrite the use.
5272 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5273
5274 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00005275 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005276 assert(InsertPt != UserBB->end());
5277 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005278 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00005279 }
5280
5281 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005282 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00005283 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00005284 MadeChange = true;
5285 }
5286
5287 return MadeChange;
5288}
5289
Geoff Berry5256fca2015-11-20 22:34:39 +00005290// Find loads whose uses only use some of the loaded value's bits. Add an "and"
5291// just after the load if the target can fold this into one extload instruction,
5292// with the hope of eliminating some of the other later "and" instructions using
5293// the loaded value. "and"s that are made trivially redundant by the insertion
5294// of the new "and" are removed by this function, while others (e.g. those whose
5295// path from the load goes through a phi) are left for isel to potentially
5296// remove.
5297//
5298// For example:
5299//
5300// b0:
5301// x = load i32
5302// ...
5303// b1:
5304// y = and x, 0xff
5305// z = use y
5306//
5307// becomes:
5308//
5309// b0:
5310// x = load i32
5311// x' = and x, 0xff
5312// ...
5313// b1:
5314// z = use x'
5315//
5316// whereas:
5317//
5318// b0:
5319// x1 = load i32
5320// ...
5321// b1:
5322// x2 = load i32
5323// ...
5324// b2:
5325// x = phi x1, x2
5326// y = and x, 0xff
5327//
5328// becomes (after a call to optimizeLoadExt for each load):
5329//
5330// b0:
5331// x1 = load i32
5332// x1' = and x1, 0xff
5333// ...
5334// b1:
5335// x2 = load i32
5336// x2' = and x2, 0xff
5337// ...
5338// b2:
5339// x = phi x1', x2'
5340// y = and x, 0xff
Geoff Berry5256fca2015-11-20 22:34:39 +00005341bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005342 if (!Load->isSimple() ||
5343 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5344 return false;
5345
Geoff Berry5d534b62017-02-21 18:53:14 +00005346 // Skip loads we've already transformed.
5347 if (Load->hasOneUse() &&
5348 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5349 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005350
5351 // Look at all uses of Load, looking through phis, to determine how many bits
5352 // of the loaded value are needed.
5353 SmallVector<Instruction *, 8> WorkList;
5354 SmallPtrSet<Instruction *, 16> Visited;
5355 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5356 for (auto *U : Load->users())
5357 WorkList.push_back(cast<Instruction>(U));
5358
5359 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5360 unsigned BitWidth = LoadResultVT.getSizeInBits();
5361 APInt DemandBits(BitWidth, 0);
5362 APInt WidestAndBits(BitWidth, 0);
5363
5364 while (!WorkList.empty()) {
5365 Instruction *I = WorkList.back();
5366 WorkList.pop_back();
5367
5368 // Break use-def graph loops.
5369 if (!Visited.insert(I).second)
5370 continue;
5371
5372 // For a PHI node, push all of its users.
5373 if (auto *Phi = dyn_cast<PHINode>(I)) {
5374 for (auto *U : Phi->users())
5375 WorkList.push_back(cast<Instruction>(U));
5376 continue;
5377 }
5378
5379 switch (I->getOpcode()) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005380 case Instruction::And: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005381 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5382 if (!AndC)
5383 return false;
5384 APInt AndBits = AndC->getValue();
5385 DemandBits |= AndBits;
5386 // Keep track of the widest and mask we see.
5387 if (AndBits.ugt(WidestAndBits))
5388 WidestAndBits = AndBits;
5389 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5390 AndsToMaybeRemove.push_back(I);
5391 break;
5392 }
5393
Eugene Zelenko900b6332017-08-29 22:32:07 +00005394 case Instruction::Shl: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005395 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5396 if (!ShlC)
5397 return false;
5398 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00005399 DemandBits.setLowBits(BitWidth - ShiftAmt);
Geoff Berry5256fca2015-11-20 22:34:39 +00005400 break;
5401 }
5402
Eugene Zelenko900b6332017-08-29 22:32:07 +00005403 case Instruction::Trunc: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005404 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5405 unsigned TruncBitWidth = TruncVT.getSizeInBits();
Craig Topperfc947bc2017-04-18 17:14:21 +00005406 DemandBits.setLowBits(TruncBitWidth);
Geoff Berry5256fca2015-11-20 22:34:39 +00005407 break;
5408 }
5409
5410 default:
5411 return false;
5412 }
5413 }
5414
5415 uint32_t ActiveBits = DemandBits.getActiveBits();
5416 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5417 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5418 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5419 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5420 // followed by an AND.
5421 // TODO: Look into removing this restriction by fixing backends to either
5422 // return false for isLoadExtLegal for i1 or have them select this pattern to
5423 // a single instruction.
5424 //
5425 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5426 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005427 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005428 WidestAndBits != DemandBits)
5429 return false;
5430
5431 LLVMContext &Ctx = Load->getType()->getContext();
5432 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5433 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5434
5435 // Reject cases that won't be matched as extloads.
5436 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5437 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5438 return false;
5439
5440 IRBuilder<> Builder(Load->getNextNode());
5441 auto *NewAnd = dyn_cast<Instruction>(
5442 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005443 // Mark this instruction as "inserted by CGP", so that other
5444 // optimizations don't touch it.
5445 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005446
5447 // Replace all uses of load with new and (except for the use of load in the
5448 // new and itself).
5449 Load->replaceAllUsesWith(NewAnd);
5450 NewAnd->setOperand(0, Load);
5451
5452 // Remove any and instructions that are now redundant.
5453 for (auto *And : AndsToMaybeRemove)
5454 // Check that the and mask is the same as the one we decided to put on the
5455 // new and.
5456 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5457 And->replaceAllUsesWith(NewAnd);
5458 if (&*CurInstIterator == And)
5459 CurInstIterator = std::next(And->getIterator());
5460 And->eraseFromParent();
5461 ++NumAndUses;
5462 }
5463
5464 ++NumAndsAdded;
5465 return true;
5466}
5467
Sanjay Patel69a50a12015-10-19 21:59:12 +00005468/// Check if V (an operand of a select instruction) is an expensive instruction
5469/// that is only used once.
5470static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5471 auto *I = dyn_cast<Instruction>(V);
5472 // If it's safe to speculatively execute, then it should not have side
5473 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005474 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5475 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005476}
5477
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005478/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005479static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005480 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005481 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005482 // If even a predictable select is cheap, then a branch can't be cheaper.
5483 if (!TLI->isPredictableSelectExpensive())
5484 return false;
5485
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005486 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005487 // whether a select is better represented as a branch.
5488
5489 // If metadata tells us that the select condition is obviously predictable,
5490 // then we want to replace the select with a branch.
5491 uint64_t TrueWeight, FalseWeight;
5492 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5493 uint64_t Max = std::max(TrueWeight, FalseWeight);
5494 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005495 if (Sum != 0) {
5496 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5497 if (Probability > TLI->getPredictableBranchThreshold())
5498 return true;
5499 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005500 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005501
5502 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5503
Sanjay Patel4e652762015-09-28 22:14:51 +00005504 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5505 // comparison condition. If the compare has more than one use, there's
5506 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005507 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005508 return false;
5509
Sanjay Patel69a50a12015-10-19 21:59:12 +00005510 // If either operand of the select is expensive and only needed on one side
5511 // of the select, we should form a branch.
5512 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5513 sinkSelectOperand(TTI, SI->getFalseValue()))
5514 return true;
5515
5516 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005517}
5518
Dehao Chen9bbb9412016-09-12 20:23:28 +00005519/// If \p isTrue is true, return the true value of \p SI, otherwise return
5520/// false value of \p SI. If the true/false value of \p SI is defined by any
5521/// select instructions in \p Selects, look through the defining select
5522/// instruction until the true/false value is not defined in \p Selects.
5523static Value *getTrueOrFalseValue(
5524 SelectInst *SI, bool isTrue,
5525 const SmallPtrSet<const Instruction *, 2> &Selects) {
5526 Value *V;
5527
5528 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5529 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005530 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005531 "The condition of DefSI does not match with SI");
5532 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5533 }
5534 return V;
5535}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005536
Nadav Rotem9d832022012-09-02 12:10:19 +00005537/// If we have a SelectInst that will likely profit from branch prediction,
5538/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005539bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00005540 // Find all consecutive select instructions that share the same condition.
5541 SmallVector<SelectInst *, 2> ASI;
5542 ASI.push_back(SI);
5543 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5544 It != SI->getParent()->end(); ++It) {
5545 SelectInst *I = dyn_cast<SelectInst>(&*It);
5546 if (I && SI->getCondition() == I->getCondition()) {
5547 ASI.push_back(I);
5548 } else {
5549 break;
5550 }
5551 }
5552
5553 SelectInst *LastSI = ASI.back();
5554 // Increment the current iterator to skip all the rest of select instructions
5555 // because they will be either "not lowered" or "all lowered" to branch.
5556 CurInstIterator = std::next(LastSI->getIterator());
5557
Nadav Rotem9d832022012-09-02 12:10:19 +00005558 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5559
5560 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00005561 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
5562 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005563 return false;
5564
Nadav Rotem9d832022012-09-02 12:10:19 +00005565 TargetLowering::SelectSupportKind SelectKind;
5566 if (VectorCond)
5567 SelectKind = TargetLowering::VectorMaskSelect;
5568 else if (SI->getType()->isVectorTy())
5569 SelectKind = TargetLowering::ScalarCondVectorVal;
5570 else
5571 SelectKind = TargetLowering::ScalarValSelect;
5572
Sanjay Pateld66607b2016-04-26 17:11:17 +00005573 if (TLI->isSelectSupported(SelectKind) &&
5574 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5575 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005576
5577 ModifiedDT = true;
5578
Sanjay Patel69a50a12015-10-19 21:59:12 +00005579 // Transform a sequence like this:
5580 // start:
5581 // %cmp = cmp uge i32 %a, %b
5582 // %sel = select i1 %cmp, i32 %c, i32 %d
5583 //
5584 // Into:
5585 // start:
5586 // %cmp = cmp uge i32 %a, %b
5587 // br i1 %cmp, label %select.true, label %select.false
5588 // select.true:
5589 // br label %select.end
5590 // select.false:
5591 // br label %select.end
5592 // select.end:
5593 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5594 //
5595 // In addition, we may sink instructions that produce %c or %d from
5596 // the entry block into the destination(s) of the new branch.
5597 // If the true or false blocks do not contain a sunken instruction, that
5598 // block and its branch may be optimized away. In that case, one side of the
5599 // first branch will point directly to select.end, and the corresponding PHI
5600 // predecessor block will be the start block.
5601
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005602 // First, we split the block containing the select into 2 blocks.
5603 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005604 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005605 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005606
Sanjay Patel69a50a12015-10-19 21:59:12 +00005607 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005608 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005609
5610 // These are the new basic blocks for the conditional branch.
5611 // At least one will become an actual new basic block.
5612 BasicBlock *TrueBlock = nullptr;
5613 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005614 BranchInst *TrueBranch = nullptr;
5615 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005616
5617 // Sink expensive instructions into the conditional blocks to avoid executing
5618 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005619 for (SelectInst *SI : ASI) {
5620 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5621 if (TrueBlock == nullptr) {
5622 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5623 EndBlock->getParent(), EndBlock);
5624 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5625 }
5626 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5627 TrueInst->moveBefore(TrueBranch);
5628 }
5629 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5630 if (FalseBlock == nullptr) {
5631 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5632 EndBlock->getParent(), EndBlock);
5633 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5634 }
5635 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5636 FalseInst->moveBefore(FalseBranch);
5637 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005638 }
5639
5640 // If there was nothing to sink, then arbitrarily choose the 'false' side
5641 // for a new input value to the PHI.
5642 if (TrueBlock == FalseBlock) {
5643 assert(TrueBlock == nullptr &&
5644 "Unexpected basic block transform while optimizing select");
5645
5646 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5647 EndBlock->getParent(), EndBlock);
5648 BranchInst::Create(EndBlock, FalseBlock);
5649 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005650
5651 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005652 // If we did not create a new block for one of the 'true' or 'false' paths
5653 // of the condition, it means that side of the branch goes to the end block
5654 // directly and the path originates from the start block from the point of
5655 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005656 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005657 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005658 TT = EndBlock;
5659 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005660 TrueBlock = StartBlock;
5661 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005662 TT = TrueBlock;
5663 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005664 FalseBlock = StartBlock;
5665 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005666 TT = TrueBlock;
5667 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005668 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005669 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005670
Dehao Chen9bbb9412016-09-12 20:23:28 +00005671 SmallPtrSet<const Instruction *, 2> INS;
5672 INS.insert(ASI.begin(), ASI.end());
5673 // Use reverse iterator because later select may use the value of the
5674 // earlier select, and we need to propagate value through earlier select
5675 // to get the PHI operand.
5676 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5677 SelectInst *SI = *It;
5678 // The select itself is replaced with a PHI Node.
5679 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5680 PN->takeName(SI);
5681 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5682 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00005683
Dehao Chen9bbb9412016-09-12 20:23:28 +00005684 SI->replaceAllUsesWith(PN);
5685 SI->eraseFromParent();
5686 INS.erase(SI);
5687 ++NumSelectsExpanded;
5688 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005689
5690 // Instruct OptimizeBlock to skip to the next block.
5691 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005692 return true;
5693}
5694
Benjamin Kramer573ff362014-03-01 17:24:40 +00005695static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005696 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5697 int SplatElem = -1;
5698 for (unsigned i = 0; i < Mask.size(); ++i) {
5699 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5700 return false;
5701 SplatElem = Mask[i];
5702 }
5703
5704 return true;
5705}
5706
5707/// Some targets have expensive vector shifts if the lanes aren't all the same
5708/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5709/// it's often worth sinking a shufflevector splat down to its use so that
5710/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005711bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005712 BasicBlock *DefBB = SVI->getParent();
5713
5714 // Only do this xform if variable vector shifts are particularly expensive.
5715 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5716 return false;
5717
5718 // We only expect better codegen by sinking a shuffle if we can recognise a
5719 // constant splat.
5720 if (!isBroadcastShuffle(SVI))
5721 return false;
5722
5723 // InsertedShuffles - Only insert a shuffle in each block once.
5724 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5725
5726 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005727 for (User *U : SVI->users()) {
5728 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005729
5730 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005731 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005732 if (UserBB == DefBB) continue;
5733
5734 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005735 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005736
5737 // Everything checks out, sink the shuffle if the user's block doesn't
5738 // already have a copy.
5739 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5740
5741 if (!InsertedShuffle) {
5742 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005743 assert(InsertPt != UserBB->end());
5744 InsertedShuffle =
5745 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5746 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005747 }
5748
Chandler Carruthcdf47882014-03-09 03:16:01 +00005749 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005750 MadeChange = true;
5751 }
5752
5753 // If we removed all uses, nuke the shuffle.
5754 if (SVI->use_empty()) {
5755 SVI->eraseFromParent();
5756 MadeChange = true;
5757 }
5758
5759 return MadeChange;
5760}
5761
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005762bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5763 if (!TLI || !DL)
5764 return false;
5765
5766 Value *Cond = SI->getCondition();
5767 Type *OldType = Cond->getType();
5768 LLVMContext &Context = Cond->getContext();
5769 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5770 unsigned RegWidth = RegType.getSizeInBits();
5771
5772 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5773 return false;
5774
5775 // If the register width is greater than the type width, expand the condition
5776 // of the switch instruction and each case constant to the width of the
5777 // register. By widening the type of the switch condition, subsequent
5778 // comparisons (for case comparisons) will not need to be extended to the
5779 // preferred register width, so we will potentially eliminate N-1 extends,
5780 // where N is the number of cases in the switch.
5781 auto *NewType = Type::getIntNTy(Context, RegWidth);
5782
5783 // Zero-extend the switch condition and case constants unless the switch
5784 // condition is a function argument that is already being sign-extended.
5785 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5786 // everything instead.
5787 Instruction::CastOps ExtType = Instruction::ZExt;
5788 if (auto *Arg = dyn_cast<Argument>(Cond))
5789 if (Arg->hasSExtAttr())
5790 ExtType = Instruction::SExt;
5791
5792 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5793 ExtInst->insertBefore(SI);
5794 SI->setCondition(ExtInst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00005795 for (auto Case : SI->cases()) {
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005796 APInt NarrowConst = Case.getCaseValue()->getValue();
5797 APInt WideConst = (ExtType == Instruction::ZExt) ?
5798 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5799 Case.setValue(ConstantInt::get(Context, WideConst));
5800 }
5801
5802 return true;
5803}
5804
Zaara Syeda3a7578c2017-05-31 17:12:38 +00005805
Quentin Colombetc32615d2014-10-31 17:52:53 +00005806namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005807
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005808/// Helper class to promote a scalar operation to a vector one.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005809/// This class is used to move downward extractelement transition.
5810/// E.g.,
5811/// a = vector_op <2 x i32>
5812/// b = extractelement <2 x i32> a, i32 0
5813/// c = scalar_op b
5814/// store c
5815///
5816/// =>
5817/// a = vector_op <2 x i32>
5818/// c = vector_op a (equivalent to scalar_op on the related lane)
5819/// * d = extractelement <2 x i32> c, i32 0
5820/// * store d
5821/// Assuming both extractelement and store can be combine, we get rid of the
5822/// transition.
5823class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005824 /// DataLayout associated with the current module.
5825 const DataLayout &DL;
5826
Quentin Colombetc32615d2014-10-31 17:52:53 +00005827 /// Used to perform some checks on the legality of vector operations.
5828 const TargetLowering &TLI;
5829
5830 /// Used to estimated the cost of the promoted chain.
5831 const TargetTransformInfo &TTI;
5832
5833 /// The transition being moved downwards.
5834 Instruction *Transition;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005835
Quentin Colombetc32615d2014-10-31 17:52:53 +00005836 /// The sequence of instructions to be promoted.
5837 SmallVector<Instruction *, 4> InstsToBePromoted;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005838
Quentin Colombetc32615d2014-10-31 17:52:53 +00005839 /// Cost of combining a store and an extract.
5840 unsigned StoreExtractCombineCost;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005841
Quentin Colombetc32615d2014-10-31 17:52:53 +00005842 /// Instruction that will be combined with the transition.
Eugene Zelenko900b6332017-08-29 22:32:07 +00005843 Instruction *CombineInst = nullptr;
Quentin Colombetc32615d2014-10-31 17:52:53 +00005844
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005845 /// The instruction that represents the current end of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005846 /// Since we are faking the promotion until we reach the end of the chain
5847 /// of computation, we need a way to get the current end of the transition.
5848 Instruction *getEndOfTransition() const {
5849 if (InstsToBePromoted.empty())
5850 return Transition;
5851 return InstsToBePromoted.back();
5852 }
5853
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005854 /// Return the index of the original value in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005855 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5856 /// c, is at index 0.
5857 unsigned getTransitionOriginalValueIdx() const {
5858 assert(isa<ExtractElementInst>(Transition) &&
5859 "Other kind of transitions are not supported yet");
5860 return 0;
5861 }
5862
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005863 /// Return the index of the index in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005864 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5865 /// is at index 1.
5866 unsigned getTransitionIdx() const {
5867 assert(isa<ExtractElementInst>(Transition) &&
5868 "Other kind of transitions are not supported yet");
5869 return 1;
5870 }
5871
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005872 /// Get the type of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005873 /// This is the type of the original value.
5874 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5875 /// transition is <2 x i32>.
5876 Type *getTransitionType() const {
5877 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5878 }
5879
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005880 /// Promote \p ToBePromoted by moving \p Def downward through.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005881 /// I.e., we have the following sequence:
5882 /// Def = Transition <ty1> a to <ty2>
5883 /// b = ToBePromoted <ty2> Def, ...
5884 /// =>
5885 /// b = ToBePromoted <ty1> a, ...
5886 /// Def = Transition <ty1> ToBePromoted to <ty2>
5887 void promoteImpl(Instruction *ToBePromoted);
5888
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005889 /// Check whether or not it is profitable to promote all the
Quentin Colombetc32615d2014-10-31 17:52:53 +00005890 /// instructions enqueued to be promoted.
5891 bool isProfitableToPromote() {
5892 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5893 unsigned Index = isa<ConstantInt>(ValIdx)
5894 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5895 : -1;
5896 Type *PromotedType = getTransitionType();
5897
5898 StoreInst *ST = cast<StoreInst>(CombineInst);
5899 unsigned AS = ST->getPointerAddressSpace();
5900 unsigned Align = ST->getAlignment();
5901 // Check if this store is supported.
5902 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005903 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5904 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005905 // If this is not supported, there is no way we can combine
5906 // the extract with the store.
5907 return false;
5908 }
5909
5910 // The scalar chain of computation has to pay for the transition
5911 // scalar to vector.
5912 // The vector chain has to account for the combining cost.
5913 uint64_t ScalarCost =
5914 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5915 uint64_t VectorCost = StoreExtractCombineCost;
5916 for (const auto &Inst : InstsToBePromoted) {
5917 // Compute the cost.
5918 // By construction, all instructions being promoted are arithmetic ones.
5919 // Moreover, one argument is a constant that can be viewed as a splat
5920 // constant.
5921 Value *Arg0 = Inst->getOperand(0);
5922 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5923 isa<ConstantFP>(Arg0);
5924 TargetTransformInfo::OperandValueKind Arg0OVK =
5925 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5926 : TargetTransformInfo::OK_AnyValue;
5927 TargetTransformInfo::OperandValueKind Arg1OVK =
5928 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5929 : TargetTransformInfo::OK_AnyValue;
5930 ScalarCost += TTI.getArithmeticInstrCost(
5931 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5932 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5933 Arg0OVK, Arg1OVK);
5934 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005935 LLVM_DEBUG(
5936 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5937 << ScalarCost << "\nVector: " << VectorCost << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00005938 return ScalarCost > VectorCost;
5939 }
5940
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005941 /// Generate a constant vector with \p Val with the same
Quentin Colombetc32615d2014-10-31 17:52:53 +00005942 /// number of elements as the transition.
5943 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005944 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005945 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5946 /// otherwise we generate a vector with as many undef as possible:
5947 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5948 /// used at the index of the extract.
5949 Value *getConstantVector(Constant *Val, bool UseSplat) const {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005950 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00005951 if (!UseSplat) {
5952 // If we cannot determine where the constant must be, we have to
5953 // use a splat constant.
5954 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5955 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5956 ExtractIdx = CstVal->getSExtValue();
5957 else
5958 UseSplat = true;
5959 }
5960
5961 unsigned End = getTransitionType()->getVectorNumElements();
5962 if (UseSplat)
5963 return ConstantVector::getSplat(End, Val);
5964
5965 SmallVector<Constant *, 4> ConstVec;
5966 UndefValue *UndefVal = UndefValue::get(Val->getType());
5967 for (unsigned Idx = 0; Idx != End; ++Idx) {
5968 if (Idx == ExtractIdx)
5969 ConstVec.push_back(Val);
5970 else
5971 ConstVec.push_back(UndefVal);
5972 }
5973 return ConstantVector::get(ConstVec);
5974 }
5975
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005976 /// Check if promoting to a vector type an operand at \p OperandIdx
Quentin Colombetc32615d2014-10-31 17:52:53 +00005977 /// in \p Use can trigger undefined behavior.
5978 static bool canCauseUndefinedBehavior(const Instruction *Use,
5979 unsigned OperandIdx) {
5980 // This is not safe to introduce undef when the operand is on
5981 // the right hand side of a division-like instruction.
5982 if (OperandIdx != 1)
5983 return false;
5984 switch (Use->getOpcode()) {
5985 default:
5986 return false;
5987 case Instruction::SDiv:
5988 case Instruction::UDiv:
5989 case Instruction::SRem:
5990 case Instruction::URem:
5991 return true;
5992 case Instruction::FDiv:
5993 case Instruction::FRem:
5994 return !Use->hasNoNaNs();
5995 }
5996 llvm_unreachable(nullptr);
5997 }
5998
5999public:
Mehdi Amini44ede332015-07-09 02:09:04 +00006000 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
6001 const TargetTransformInfo &TTI, Instruction *Transition,
6002 unsigned CombineCost)
6003 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Eugene Zelenko900b6332017-08-29 22:32:07 +00006004 StoreExtractCombineCost(CombineCost) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00006005 assert(Transition && "Do not know how to promote null");
6006 }
6007
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006008 /// Check if we can promote \p ToBePromoted to \p Type.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006009 bool canPromote(const Instruction *ToBePromoted) const {
6010 // We could support CastInst too.
6011 return isa<BinaryOperator>(ToBePromoted);
6012 }
6013
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006014 /// Check if it is profitable to promote \p ToBePromoted
Quentin Colombetc32615d2014-10-31 17:52:53 +00006015 /// by moving downward the transition through.
6016 bool shouldPromote(const Instruction *ToBePromoted) const {
6017 // Promote only if all the operands can be statically expanded.
6018 // Indeed, we do not want to introduce any new kind of transitions.
6019 for (const Use &U : ToBePromoted->operands()) {
6020 const Value *Val = U.get();
6021 if (Val == getEndOfTransition()) {
6022 // If the use is a division and the transition is on the rhs,
6023 // we cannot promote the operation, otherwise we may create a
6024 // division by zero.
6025 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
6026 return false;
6027 continue;
6028 }
6029 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
6030 !isa<ConstantFP>(Val))
6031 return false;
6032 }
6033 // Check that the resulting operation is legal.
6034 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
6035 if (!ISDOpcode)
6036 return false;
6037 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00006038 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00006039 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00006040 }
6041
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006042 /// Check whether or not \p Use can be combined
Quentin Colombetc32615d2014-10-31 17:52:53 +00006043 /// with the transition.
6044 /// I.e., is it possible to do Use(Transition) => AnotherUse?
6045 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
6046
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006047 /// Record \p ToBePromoted as part of the chain to be promoted.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006048 void enqueueForPromotion(Instruction *ToBePromoted) {
6049 InstsToBePromoted.push_back(ToBePromoted);
6050 }
6051
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006052 /// Set the instruction that will be combined with the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006053 void recordCombineInstruction(Instruction *ToBeCombined) {
6054 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
6055 CombineInst = ToBeCombined;
6056 }
6057
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006058 /// Promote all the instructions enqueued for promotion if it is
Quentin Colombetc32615d2014-10-31 17:52:53 +00006059 /// is profitable.
6060 /// \return True if the promotion happened, false otherwise.
6061 bool promote() {
6062 // Check if there is something to promote.
6063 // Right now, if we do not have anything to combine with,
6064 // we assume the promotion is not profitable.
6065 if (InstsToBePromoted.empty() || !CombineInst)
6066 return false;
6067
6068 // Check cost.
6069 if (!StressStoreExtract && !isProfitableToPromote())
6070 return false;
6071
6072 // Promote.
6073 for (auto &ToBePromoted : InstsToBePromoted)
6074 promoteImpl(ToBePromoted);
6075 InstsToBePromoted.clear();
6076 return true;
6077 }
6078};
Eugene Zelenko900b6332017-08-29 22:32:07 +00006079
6080} // end anonymous namespace
Quentin Colombetc32615d2014-10-31 17:52:53 +00006081
6082void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
6083 // At this point, we know that all the operands of ToBePromoted but Def
6084 // can be statically promoted.
6085 // For Def, we need to use its parameter in ToBePromoted:
6086 // b = ToBePromoted ty1 a
6087 // Def = Transition ty1 b to ty2
6088 // Move the transition down.
6089 // 1. Replace all uses of the promoted operation by the transition.
6090 // = ... b => = ... Def.
6091 assert(ToBePromoted->getType() == Transition->getType() &&
6092 "The type of the result of the transition does not match "
6093 "the final type");
6094 ToBePromoted->replaceAllUsesWith(Transition);
6095 // 2. Update the type of the uses.
6096 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
6097 Type *TransitionTy = getTransitionType();
6098 ToBePromoted->mutateType(TransitionTy);
6099 // 3. Update all the operands of the promoted operation with promoted
6100 // operands.
6101 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
6102 for (Use &U : ToBePromoted->operands()) {
6103 Value *Val = U.get();
6104 Value *NewVal = nullptr;
6105 if (Val == Transition)
6106 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
6107 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
6108 isa<ConstantFP>(Val)) {
6109 // Use a splat constant if it is not safe to use undef.
6110 NewVal = getConstantVector(
6111 cast<Constant>(Val),
6112 isa<UndefValue>(Val) ||
6113 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
6114 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00006115 llvm_unreachable("Did you modified shouldPromote and forgot to update "
6116 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006117 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
6118 }
Sanjay Patel674d2c22017-08-29 14:07:48 +00006119 Transition->moveAfter(ToBePromoted);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006120 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6121}
6122
6123/// Some targets can do store(extractelement) with one instruction.
6124/// Try to push the extractelement towards the stores when the target
6125/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006126bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006127 unsigned CombineCost = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006128 if (DisableStoreExtract || !TLI ||
6129 (!StressStoreExtract &&
6130 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
6131 Inst->getOperand(1), CombineCost)))
6132 return false;
6133
6134 // At this point we know that Inst is a vector to scalar transition.
6135 // Try to move it down the def-use chain, until:
6136 // - We can combine the transition with its single use
6137 // => we got rid of the transition.
6138 // - We escape the current basic block
6139 // => we would need to check that we are moving it at a cheaper place and
6140 // we do not do that for now.
6141 BasicBlock *Parent = Inst->getParent();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006142 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00006143 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006144 // If the transition has more than one use, assume this is not going to be
6145 // beneficial.
6146 while (Inst->hasOneUse()) {
6147 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006148 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006149
6150 if (ToBePromoted->getParent() != Parent) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006151 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
6152 << ToBePromoted->getParent()->getName()
6153 << ") than the transition (" << Parent->getName()
6154 << ").\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006155 return false;
6156 }
6157
6158 if (VPH.canCombine(ToBePromoted)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006159 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
6160 << "will be combined with: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006161 VPH.recordCombineInstruction(ToBePromoted);
6162 bool Changed = VPH.promote();
6163 NumStoreExtractExposed += Changed;
6164 return Changed;
6165 }
6166
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006167 LLVM_DEBUG(dbgs() << "Try promoting.\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006168 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6169 return false;
6170
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006171 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006172
6173 VPH.enqueueForPromotion(ToBePromoted);
6174 Inst = ToBePromoted;
6175 }
6176 return false;
6177}
6178
Wei Mia2f0b592016-12-22 19:44:45 +00006179/// For the instruction sequence of store below, F and I values
6180/// are bundled together as an i64 value before being stored into memory.
6181/// Sometimes it is more efficent to generate separate stores for F and I,
6182/// which can remove the bitwise instructions or sink them to colder places.
6183///
6184/// (store (or (zext (bitcast F to i32) to i64),
6185/// (shl (zext I to i64), 32)), addr) -->
6186/// (store F, addr) and (store I, addr+4)
6187///
6188/// Similarly, splitting for other merged store can also be beneficial, like:
6189/// For pair of {i32, i32}, i64 store --> two i32 stores.
6190/// For pair of {i32, i16}, i64 store --> two i32 stores.
6191/// For pair of {i16, i16}, i32 store --> two i16 stores.
6192/// For pair of {i16, i8}, i32 store --> two i16 stores.
6193/// For pair of {i8, i8}, i16 store --> two i8 stores.
6194///
6195/// We allow each target to determine specifically which kind of splitting is
6196/// supported.
6197///
6198/// The store patterns are commonly seen from the simple code snippet below
6199/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
6200/// void goo(const std::pair<int, float> &);
6201/// hoo() {
6202/// ...
6203/// goo(std::make_pair(tmp, ftmp));
6204/// ...
6205/// }
6206///
6207/// Although we already have similar splitting in DAG Combine, we duplicate
6208/// it in CodeGenPrepare to catch the case in which pattern is across
6209/// multiple BBs. The logic in DAG Combine is kept to catch case generated
6210/// during code expansion.
6211static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
6212 const TargetLowering &TLI) {
6213 // Handle simple but common cases only.
6214 Type *StoreType = SI.getValueOperand()->getType();
6215 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6216 DL.getTypeSizeInBits(StoreType) == 0)
6217 return false;
6218
6219 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6220 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6221 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6222 DL.getTypeSizeInBits(SplitStoreType))
6223 return false;
6224
6225 // Match the following patterns:
6226 // (store (or (zext LValue to i64),
6227 // (shl (zext HValue to i64), 32)), HalfValBitSize)
6228 // or
6229 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6230 // (zext LValue to i64),
6231 // Expect both operands of OR and the first operand of SHL have only
6232 // one use.
6233 Value *LValue, *HValue;
6234 if (!match(SI.getValueOperand(),
6235 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6236 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6237 m_SpecificInt(HalfValBitSize))))))
6238 return false;
6239
6240 // Check LValue and HValue are int with size less or equal than 32.
6241 if (!LValue->getType()->isIntegerTy() ||
6242 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6243 !HValue->getType()->isIntegerTy() ||
6244 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6245 return false;
6246
6247 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6248 // as the input of target query.
6249 auto *LBC = dyn_cast<BitCastInst>(LValue);
6250 auto *HBC = dyn_cast<BitCastInst>(HValue);
6251 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6252 : EVT::getEVT(LValue->getType());
6253 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6254 : EVT::getEVT(HValue->getType());
6255 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6256 return false;
6257
6258 // Start to split store.
6259 IRBuilder<> Builder(SI.getContext());
6260 Builder.SetInsertPoint(&SI);
6261
6262 // If LValue/HValue is a bitcast in another BB, create a new one in current
6263 // BB so it may be merged with the splitted stores by dag combiner.
6264 if (LBC && LBC->getParent() != SI.getParent())
6265 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6266 if (HBC && HBC->getParent() != SI.getParent())
6267 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6268
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006269 bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
Wei Mia2f0b592016-12-22 19:44:45 +00006270 auto CreateSplitStore = [&](Value *V, bool Upper) {
6271 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6272 Value *Addr = Builder.CreateBitCast(
6273 SI.getOperand(1),
6274 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006275 if ((IsLE && Upper) || (!IsLE && !Upper))
Wei Mia2f0b592016-12-22 19:44:45 +00006276 Addr = Builder.CreateGEP(
6277 SplitStoreType, Addr,
6278 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6279 Builder.CreateAlignedStore(
6280 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6281 };
6282
6283 CreateSplitStore(LValue, false);
6284 CreateSplitStore(HValue, true);
6285
6286 // Delete the old store.
6287 SI.eraseFromParent();
6288 return true;
6289}
6290
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006291// Return true if the GEP has two operands, the first operand is of a sequential
6292// type, and the second operand is a constant.
6293static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6294 gep_type_iterator I = gep_type_begin(*GEP);
6295 return GEP->getNumOperands() == 2 &&
6296 I.isSequential() &&
6297 isa<ConstantInt>(GEP->getOperand(1));
6298}
6299
6300// Try unmerging GEPs to reduce liveness interference (register pressure) across
6301// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6302// reducing liveness interference across those edges benefits global register
6303// allocation. Currently handles only certain cases.
6304//
6305// For example, unmerge %GEPI and %UGEPI as below.
6306//
6307// ---------- BEFORE ----------
6308// SrcBlock:
6309// ...
6310// %GEPIOp = ...
6311// ...
6312// %GEPI = gep %GEPIOp, Idx
6313// ...
6314// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6315// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6316// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6317// %UGEPI)
6318//
6319// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6320// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6321// ...
6322//
6323// DstBi:
6324// ...
6325// %UGEPI = gep %GEPIOp, UIdx
6326// ...
6327// ---------------------------
6328//
6329// ---------- AFTER ----------
6330// SrcBlock:
6331// ... (same as above)
6332// (* %GEPI is still alive on the indirectbr edges)
6333// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6334// unmerging)
6335// ...
6336//
6337// DstBi:
6338// ...
6339// %UGEPI = gep %GEPI, (UIdx-Idx)
6340// ...
6341// ---------------------------
6342//
6343// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6344// no longer alive on them.
6345//
6346// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6347// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6348// not to disable further simplications and optimizations as a result of GEP
6349// merging.
6350//
6351// Note this unmerging may increase the length of the data flow critical path
6352// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6353// between the register pressure and the length of data-flow critical
6354// path. Restricting this to the uncommon IndirectBr case would minimize the
6355// impact of potentially longer critical path, if any, and the impact on compile
6356// time.
6357static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6358 const TargetTransformInfo *TTI) {
6359 BasicBlock *SrcBlock = GEPI->getParent();
6360 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6361 // (non-IndirectBr) cases exit early here.
6362 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6363 return false;
6364 // Check that GEPI is a simple gep with a single constant index.
6365 if (!GEPSequentialConstIndexed(GEPI))
6366 return false;
6367 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6368 // Check that GEPI is a cheap one.
6369 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6370 > TargetTransformInfo::TCC_Basic)
6371 return false;
6372 Value *GEPIOp = GEPI->getOperand(0);
6373 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6374 if (!isa<Instruction>(GEPIOp))
6375 return false;
6376 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6377 if (GEPIOpI->getParent() != SrcBlock)
6378 return false;
6379 // Check that GEP is used outside the block, meaning it's alive on the
6380 // IndirectBr edge(s).
6381 if (find_if(GEPI->users(), [&](User *Usr) {
6382 if (auto *I = dyn_cast<Instruction>(Usr)) {
6383 if (I->getParent() != SrcBlock) {
6384 return true;
6385 }
6386 }
6387 return false;
6388 }) == GEPI->users().end())
6389 return false;
6390 // The second elements of the GEP chains to be unmerged.
6391 std::vector<GetElementPtrInst *> UGEPIs;
6392 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6393 // on IndirectBr edges.
6394 for (User *Usr : GEPIOp->users()) {
6395 if (Usr == GEPI) continue;
6396 // Check if Usr is an Instruction. If not, give up.
6397 if (!isa<Instruction>(Usr))
6398 return false;
6399 auto *UI = cast<Instruction>(Usr);
6400 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6401 if (UI->getParent() == SrcBlock)
6402 continue;
6403 // Check if Usr is a GEP. If not, give up.
6404 if (!isa<GetElementPtrInst>(Usr))
6405 return false;
6406 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6407 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6408 // the pointer operand to it. If so, record it in the vector. If not, give
6409 // up.
6410 if (!GEPSequentialConstIndexed(UGEPI))
6411 return false;
6412 if (UGEPI->getOperand(0) != GEPIOp)
6413 return false;
6414 if (GEPIIdx->getType() !=
6415 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6416 return false;
6417 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6418 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6419 > TargetTransformInfo::TCC_Basic)
6420 return false;
6421 UGEPIs.push_back(UGEPI);
6422 }
6423 if (UGEPIs.size() == 0)
6424 return false;
6425 // Check the materializing cost of (Uidx-Idx).
6426 for (GetElementPtrInst *UGEPI : UGEPIs) {
6427 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6428 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6429 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6430 if (ImmCost > TargetTransformInfo::TCC_Basic)
6431 return false;
6432 }
6433 // Now unmerge between GEPI and UGEPIs.
6434 for (GetElementPtrInst *UGEPI : UGEPIs) {
6435 UGEPI->setOperand(0, GEPI);
6436 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6437 Constant *NewUGEPIIdx =
6438 ConstantInt::get(GEPIIdx->getType(),
6439 UGEPIIdx->getValue() - GEPIIdx->getValue());
6440 UGEPI->setOperand(1, NewUGEPIIdx);
6441 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6442 // inbounds to avoid UB.
6443 if (!GEPI->isInBounds()) {
6444 UGEPI->setIsInBounds(false);
6445 }
6446 }
6447 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6448 // alive on IndirectBr edges).
6449 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6450 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6451 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6452 return true;
6453}
6454
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006455bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00006456 // Bail out if we inserted the instruction to prevent optimizations from
6457 // stepping on each other's toes.
6458 if (InsertedInsts.count(I))
6459 return false;
6460
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006461 if (PHINode *P = dyn_cast<PHINode>(I)) {
6462 // It is possible for very late stage optimizations (such as SimplifyCFG)
6463 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6464 // trivial PHI, go ahead and zap it here.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00006465 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006466 P->replaceAllUsesWith(V);
6467 P->eraseFromParent();
6468 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00006469 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006470 }
Chris Lattneree588de2011-01-15 07:29:01 +00006471 return false;
6472 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006473
Chris Lattneree588de2011-01-15 07:29:01 +00006474 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006475 // If the source of the cast is a constant, then this should have
6476 // already been constant folded. The only reason NOT to constant fold
6477 // it is if something (e.g. LSR) was careful to place the constant
6478 // evaluation in a block other than then one that uses it (e.g. to hoist
6479 // the address of globals out of a loop). If this is the case, we don't
6480 // want to forward-subst the cast.
6481 if (isa<Constant>(CI->getOperand(0)))
6482 return false;
6483
Mehdi Amini44ede332015-07-09 02:09:04 +00006484 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00006485 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006486
Chris Lattneree588de2011-01-15 07:29:01 +00006487 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006488 /// Sink a zext or sext into its user blocks if the target type doesn't
6489 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00006490 if (TLI &&
6491 TLI->getTypeAction(CI->getContext(),
6492 TLI->getValueType(*DL, CI->getType())) ==
6493 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006494 return SinkCast(CI);
6495 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00006496 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00006497 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006498 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006499 }
Chris Lattneree588de2011-01-15 07:29:01 +00006500 return false;
6501 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006502
Chris Lattneree588de2011-01-15 07:29:01 +00006503 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00006504 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00006505 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00006506
Chris Lattneree588de2011-01-15 07:29:01 +00006507 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006508 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006509 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006510 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006511 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006512 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6513 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006514 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006515 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006516 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006517
Chris Lattneree588de2011-01-15 07:29:01 +00006518 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006519 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6520 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006521 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006522 if (TLI) {
6523 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006524 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006525 SI->getOperand(0)->getType(), AS);
6526 }
Chris Lattneree588de2011-01-15 07:29:01 +00006527 return false;
6528 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006529
Matt Arsenault02d915b2017-03-15 22:35:20 +00006530 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6531 unsigned AS = RMW->getPointerAddressSpace();
6532 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6533 RMW->getType(), AS);
6534 }
6535
6536 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6537 unsigned AS = CmpX->getPointerAddressSpace();
6538 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6539 CmpX->getCompareOperand()->getType(), AS);
6540 }
6541
Yi Jiangd069f632014-04-21 19:34:27 +00006542 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6543
Geoff Berry5d534b62017-02-21 18:53:14 +00006544 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6545 EnableAndCmpSinking && TLI)
6546 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6547
Yi Jiangd069f632014-04-21 19:34:27 +00006548 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6549 BinOp->getOpcode() == Instruction::LShr)) {
6550 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6551 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006552 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006553
6554 return false;
6555 }
6556
Chris Lattneree588de2011-01-15 07:29:01 +00006557 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006558 if (GEPI->hasAllZeroIndices()) {
6559 /// The GEP operand must be a pointer, so must its result -> BitCast
6560 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6561 GEPI->getName(), GEPI);
6562 GEPI->replaceAllUsesWith(NC);
6563 GEPI->eraseFromParent();
6564 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00006565 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00006566 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006567 }
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006568 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
6569 return true;
6570 }
Chris Lattneree588de2011-01-15 07:29:01 +00006571 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006572 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006573
Chris Lattneree588de2011-01-15 07:29:01 +00006574 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006575 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006576
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006577 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006578 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006579
Tim Northoveraeb8e062014-02-19 10:02:43 +00006580 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006581 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006582
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006583 if (auto *Switch = dyn_cast<SwitchInst>(I))
6584 return optimizeSwitchInst(Switch);
6585
Quentin Colombetc32615d2014-10-31 17:52:53 +00006586 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006587 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006588
Chris Lattneree588de2011-01-15 07:29:01 +00006589 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006590}
6591
James Molloyf01488e2016-01-15 09:20:19 +00006592/// Given an OR instruction, check to see if this is a bitreverse
6593/// idiom. If so, insert the new intrinsic and return true.
6594static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6595 const TargetLowering &TLI) {
6596 if (!I.getType()->isIntegerTy() ||
6597 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6598 TLI.getValueType(DL, I.getType(), true)))
6599 return false;
6600
6601 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00006602 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00006603 return false;
6604 Instruction *LastInst = Insts.back();
6605 I.replaceAllUsesWith(LastInst);
6606 RecursivelyDeleteTriviallyDeadInstructions(&I);
6607 return true;
6608}
6609
Chris Lattnerf2836d12007-03-31 04:06:36 +00006610// In this pass we look for GEP and cast instructions that are used
6611// across basic blocks and rewrite them to improve basic-block-at-a-time
6612// selection.
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006613bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00006614 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00006615 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00006616
Chris Lattner7a277142011-01-15 07:14:54 +00006617 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006618 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006619 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006620 if (ModifiedDT)
6621 return true;
6622 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00006623
James Molloyf01488e2016-01-15 09:20:19 +00006624 bool MadeBitReverse = true;
6625 while (TLI && MadeBitReverse) {
6626 MadeBitReverse = false;
6627 for (auto &I : reverse(BB)) {
6628 if (makeBitReverse(I, *DL, *TLI)) {
6629 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00006630 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00006631 break;
6632 }
6633 }
6634 }
James Molloy3ef84c42016-01-15 10:36:01 +00006635 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00006636
Chris Lattnerf2836d12007-03-31 04:06:36 +00006637 return MadeChange;
6638}
Devang Patel53771ba2011-08-18 00:50:51 +00006639
6640// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00006641// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00006642// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006643bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00006644 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006645 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00006646 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006647 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006648 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00006649 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00006650 // Leave dbg.values that refer to an alloca alone. These
Craig Topper87e715f2017-11-07 20:56:17 +00006651 // intrinsics describe the address of a variable (= the alloca)
Adrian Prantl32da8892014-04-25 20:49:25 +00006652 // being taken. They should not be moved next to the alloca
6653 // (and to the beginning of the scope), but rather stay close to
6654 // where said address is used.
6655 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00006656 PrevNonDbgInst = Insn;
6657 continue;
6658 }
6659
6660 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6661 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00006662 // If VI is a phi in a block with an EHPad terminator, we can't insert
6663 // after it.
6664 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6665 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006666 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
6667 << *DVI << ' ' << *VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006668 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00006669 if (isa<PHINode>(VI))
6670 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6671 else
6672 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006673 MadeChange = true;
6674 ++NumDbgValueMoved;
6675 }
6676 }
6677 }
6678 return MadeChange;
6679}
Tim Northovercea0abb2014-03-29 08:22:29 +00006680
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006681/// Scale down both weights to fit into uint32_t.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006682static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6683 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006684 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006685 NewTrue = NewTrue / Scale;
6686 NewFalse = NewFalse / Scale;
6687}
6688
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006689/// Some targets prefer to split a conditional branch like:
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006690/// \code
6691/// %0 = icmp ne i32 %a, 0
6692/// %1 = icmp ne i32 %b, 0
6693/// %or.cond = or i1 %0, %1
6694/// br i1 %or.cond, label %TrueBB, label %FalseBB
6695/// \endcode
6696/// into multiple branch instructions like:
6697/// \code
6698/// bb1:
6699/// %0 = icmp ne i32 %a, 0
6700/// br i1 %0, label %TrueBB, label %bb2
6701/// bb2:
6702/// %1 = icmp ne i32 %b, 0
6703/// br i1 %1, label %TrueBB, label %FalseBB
6704/// \endcode
6705/// This usually allows instruction selection to do even further optimizations
6706/// and combine the compare with the branch instruction. Currently this is
6707/// applied for targets which have "cheap" jump instructions.
6708///
6709/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6710///
6711bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006712 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006713 return false;
6714
6715 bool MadeChange = false;
6716 for (auto &BB : F) {
6717 // Does this BB end with the following?
6718 // %cond1 = icmp|fcmp|binary instruction ...
6719 // %cond2 = icmp|fcmp|binary instruction ...
6720 // %cond.or = or|and i1 %cond1, cond2
6721 // br i1 %cond.or label %dest1, label %dest2"
6722 BinaryOperator *LogicOp;
6723 BasicBlock *TBB, *FBB;
6724 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6725 continue;
6726
Sanjay Patel42574202015-09-02 19:23:23 +00006727 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6728 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6729 continue;
6730
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006731 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006732 Value *Cond1, *Cond2;
6733 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6734 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006735 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006736 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6737 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006738 Opc = Instruction::Or;
6739 else
6740 continue;
6741
6742 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6743 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6744 continue;
6745
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006746 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006747
6748 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00006749 auto TmpBB =
6750 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6751 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006752
6753 // Update original basic block by using the first condition directly by the
6754 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006755 Br1->setCondition(Cond1);
6756 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006757
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006758 // Depending on the conditon we have to either replace the true or the false
6759 // successor of the original branch instruction.
6760 if (Opc == Instruction::And)
6761 Br1->setSuccessor(0, TmpBB);
6762 else
6763 Br1->setSuccessor(1, TmpBB);
6764
6765 // Fill in the new basic block.
6766 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006767 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6768 I->removeFromParent();
6769 I->insertBefore(Br2);
6770 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006771
6772 // Update PHI nodes in both successors. The original BB needs to be
Hiroshi Inoue6a391bb2017-06-27 10:35:37 +00006773 // replaced in one successor's PHI nodes, because the branch comes now from
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006774 // the newly generated BB (NewBB). In the other successor we need to add one
6775 // incoming edge to the PHI nodes, because both branch instructions target
6776 // now the same successor. Depending on the original branch condition
6777 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006778 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006779 // This doesn't change the successor order of the just created branch
6780 // instruction (or any other instruction).
6781 if (Opc == Instruction::Or)
6782 std::swap(TBB, FBB);
6783
6784 // Replace the old BB with the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006785 for (PHINode &PN : TBB->phis()) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006786 int i;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006787 while ((i = PN.getBasicBlockIndex(&BB)) >= 0)
6788 PN.setIncomingBlock(i, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006789 }
6790
6791 // Add another incoming edge form the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006792 for (PHINode &PN : FBB->phis()) {
6793 auto *Val = PN.getIncomingValueForBlock(&BB);
6794 PN.addIncoming(Val, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006795 }
6796
6797 // Update the branch weights (from SelectionDAGBuilder::
6798 // FindMergedConditions).
6799 if (Opc == Instruction::Or) {
6800 // Codegen X | Y as:
6801 // BB1:
6802 // jmp_if_X TBB
6803 // jmp TmpBB
6804 // TmpBB:
6805 // jmp_if_Y TBB
6806 // jmp FBB
6807 //
6808
6809 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6810 // The requirement is that
6811 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6812 // = TrueProb for orignal BB.
6813 // Assuming the orignal weights are A and B, one choice is to set BB1's
6814 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6815 // assumes that
6816 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6817 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6818 // TmpBB, but the math is more complicated.
6819 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006820 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006821 uint64_t NewTrueWeight = TrueWeight;
6822 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6823 scaleWeights(NewTrueWeight, NewFalseWeight);
6824 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6825 .createBranchWeights(TrueWeight, FalseWeight));
6826
6827 NewTrueWeight = TrueWeight;
6828 NewFalseWeight = 2 * FalseWeight;
6829 scaleWeights(NewTrueWeight, NewFalseWeight);
6830 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6831 .createBranchWeights(TrueWeight, FalseWeight));
6832 }
6833 } else {
6834 // Codegen X & Y as:
6835 // BB1:
6836 // jmp_if_X TmpBB
6837 // jmp FBB
6838 // TmpBB:
6839 // jmp_if_Y TBB
6840 // jmp FBB
6841 //
6842 // This requires creation of TmpBB after CurBB.
6843
6844 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6845 // The requirement is that
6846 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6847 // = FalseProb for orignal BB.
6848 // Assuming the orignal weights are A and B, one choice is to set BB1's
6849 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6850 // assumes that
6851 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6852 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006853 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006854 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6855 uint64_t NewFalseWeight = FalseWeight;
6856 scaleWeights(NewTrueWeight, NewFalseWeight);
6857 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6858 .createBranchWeights(TrueWeight, FalseWeight));
6859
6860 NewTrueWeight = 2 * TrueWeight;
6861 NewFalseWeight = FalseWeight;
6862 scaleWeights(NewTrueWeight, NewFalseWeight);
6863 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6864 .createBranchWeights(TrueWeight, FalseWeight));
6865 }
6866 }
6867
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006868 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00006869 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006870 ModifiedDT = true;
6871
6872 MadeChange = true;
6873
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006874 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6875 TmpBB->dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006876 }
6877 return MadeChange;
6878}