blob: 2dbf2637dc8133b567d58ff4b34d73e62f54ec9b [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf2836d12007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
Eugene Zelenko900b6332017-08-29 22:32:07 +000016#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000019#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/STLExtras.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/Statistic.h"
Jun Bum Lim90b6b502016-12-16 20:38:39 +000024#include "llvm/Analysis/BlockFrequencyInfo.h"
25#include "llvm/Analysis/BranchProbabilityInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000026#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000028#include "llvm/Analysis/LoopInfo.h"
Zaara Syeda3a7578c2017-05-31 17:12:38 +000029#include "llvm/Analysis/MemoryBuiltins.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000030#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000031#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000032#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000033#include "llvm/Transforms/Utils/Local.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000034#include "llvm/Analysis/ValueTracking.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000035#include "llvm/CodeGen/Analysis.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000036#include "llvm/CodeGen/ISDOpcodes.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000037#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000038#include "llvm/CodeGen/TargetLowering.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000039#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000040#include "llvm/CodeGen/TargetSubtargetInfo.h"
Craig Topper2fa14362018-03-29 17:21:10 +000041#include "llvm/CodeGen/ValueTypes.h"
Nico Weber432a3882018-04-30 14:59:11 +000042#include "llvm/Config/llvm-config.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000043#include "llvm/IR/Argument.h"
44#include "llvm/IR/Attributes.h"
45#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000046#include "llvm/IR/CallSite.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000047#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000051#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000053#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000054#include "llvm/IR/GlobalValue.h"
55#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/IRBuilder.h"
57#include "llvm/IR/InlineAsm.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000058#include "llvm/IR/InstrTypes.h"
59#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000060#include "llvm/IR/Instructions.h"
61#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000062#include "llvm/IR/Intrinsics.h"
63#include "llvm/IR/LLVMContext.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000064#include "llvm/IR/MDBuilder.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000065#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000067#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000068#include "llvm/IR/Statepoint.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000069#include "llvm/IR/Type.h"
70#include "llvm/IR/Use.h"
71#include "llvm/IR/User.h"
72#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000073#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000074#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000075#include "llvm/Pass.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000076#include "llvm/Support/BlockFrequency.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000077#include "llvm/Support/BranchProbability.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000078#include "llvm/Support/Casting.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000079#include "llvm/Support/CommandLine.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000080#include "llvm/Support/Compiler.h"
Evan Chengd3d80172007-12-05 23:58:20 +000081#include "llvm/Support/Debug.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000082#include "llvm/Support/ErrorHandling.h"
David Blaikie13e77db2018-03-23 23:58:25 +000083#include "llvm/Support/MachineValueType.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000084#include "llvm/Support/MathExtras.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000085#include "llvm/Support/raw_ostream.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000086#include "llvm/Target/TargetMachine.h"
87#include "llvm/Target/TargetOptions.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000088#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000089#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000090#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000091#include <algorithm>
92#include <cassert>
93#include <cstdint>
94#include <iterator>
95#include <limits>
96#include <memory>
97#include <utility>
98#include <vector>
Zaara Syeda3a7578c2017-05-31 17:12:38 +000099
Chris Lattnerf2836d12007-03-31 04:06:36 +0000100using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +0000101using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000102
Chandler Carruth1b9dde02014-04-22 02:02:50 +0000103#define DEBUG_TYPE "codegenprepare"
104
Cameron Zwarichced753f2011-01-05 17:27:27 +0000105STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +0000106STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
107STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +0000108STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
109 "sunken Cmps");
110STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
111 "of sunken Casts");
112STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
113 "computations were sunk");
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000114STATISTIC(NumMemoryInstsPhiCreated,
115 "Number of phis created when address "
116 "computations were sunk to memory instructions");
117STATISTIC(NumMemoryInstsSelectCreated,
118 "Number of select created when address "
119 "computations were sunk to memory instructions");
Evan Cheng0663f232011-03-21 01:19:09 +0000120STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
121STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +0000122STATISTIC(NumAndsAdded,
123 "Number of and mask instructions added to form ext loads");
124STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +0000125STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +0000126STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000127STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +0000128STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +0000129
Cameron Zwarich338d3622011-03-11 21:52:04 +0000130static cl::opt<bool> DisableBranchOpts(
131 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
132 cl::desc("Disable branch optimizations in CodeGenPrepare"));
133
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000134static cl::opt<bool>
135 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
136 cl::desc("Disable GC optimizations in CodeGenPrepare"));
137
Benjamin Kramer3d38c172012-05-06 14:25:16 +0000138static cl::opt<bool> DisableSelectToBranch(
139 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
140 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000141
Hal Finkelc3998302014-04-12 00:59:48 +0000142static cl::opt<bool> AddrSinkUsingGEPs(
Eli Friedman5fba1e52017-04-06 22:42:18 +0000143 "addr-sink-using-gep", cl::Hidden, cl::init(true),
Hal Finkelc3998302014-04-12 00:59:48 +0000144 cl::desc("Address sinking in CGP using GEPs."));
145
Tim Northovercea0abb2014-03-29 08:22:29 +0000146static cl::opt<bool> EnableAndCmpSinking(
147 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
148 cl::desc("Enable sinkinig and/cmp into branches."));
149
Quentin Colombetc32615d2014-10-31 17:52:53 +0000150static cl::opt<bool> DisableStoreExtract(
151 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
152 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
153
154static cl::opt<bool> StressStoreExtract(
155 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
156 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
157
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000158static cl::opt<bool> DisableExtLdPromotion(
159 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
160 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
161 "CodeGenPrepare"));
162
163static cl::opt<bool> StressExtLdPromotion(
164 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
165 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
166 "optimization in CodeGenPrepare"));
167
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000168static cl::opt<bool> DisablePreheaderProtect(
169 "disable-preheader-prot", cl::Hidden, cl::init(false),
170 cl::desc("Disable protection against removing loop preheaders"));
171
Dehao Chen302b69c2016-10-18 20:42:47 +0000172static cl::opt<bool> ProfileGuidedSectionPrefix(
David Callahan5960d9b12017-06-14 20:35:33 +0000173 "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
Dehao Chen302b69c2016-10-18 20:42:47 +0000174 cl::desc("Use profile info to add section prefix for hot/cold functions"));
175
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000176static cl::opt<unsigned> FreqRatioToSkipMerge(
177 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
178 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
179 "(frequency of destination block) is greater than this ratio"));
180
Wei Mia2f0b592016-12-22 19:44:45 +0000181static cl::opt<bool> ForceSplitStore(
182 "force-split-store", cl::Hidden, cl::init(false),
183 cl::desc("Force store splitting no matter what the target query says."));
184
Jun Bum Limdee55652017-04-03 19:20:07 +0000185static cl::opt<bool>
186EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
187 cl::desc("Enable merging of redundant sexts when one is dominating"
188 " the other."), cl::init(true));
189
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000190static cl::opt<bool> DisableComplexAddrModes(
Serguei Katkovd4df7442017-11-29 09:48:50 +0000191 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000192 cl::desc("Disables combining addressing modes with different parts "
193 "in optimizeMemoryInst."));
194
195static cl::opt<bool>
196AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
197 cl::desc("Allow creation of Phis in Address sinking."));
198
199static cl::opt<bool>
Serguei Katkov9fe05242018-01-26 06:26:56 +0000200AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000201 cl::desc("Allow creation of selects in Address sinking."));
202
John Brawn70cdb5b2017-11-24 14:10:45 +0000203static cl::opt<bool> AddrSinkCombineBaseReg(
204 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
205 cl::desc("Allow combining of BaseReg field in Address sinking."));
206
207static cl::opt<bool> AddrSinkCombineBaseGV(
208 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
209 cl::desc("Allow combining of BaseGV field in Address sinking."));
210
211static cl::opt<bool> AddrSinkCombineBaseOffs(
212 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
213 cl::desc("Allow combining of BaseOffs field in Address sinking."));
214
215static cl::opt<bool> AddrSinkCombineScaledReg(
216 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
217 cl::desc("Allow combining of ScaledReg field in Address sinking."));
218
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000219static cl::opt<bool>
220 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
221 cl::init(true),
222 cl::desc("Enable splitting large offset of GEP."));
223
Eric Christopherc1ea1492008-09-24 05:32:41 +0000224namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000225
226using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
227using TypeIsSExt = PointerIntPair<Type *, 1, bool>;
228using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
229using SExts = SmallVector<Instruction *, 16>;
230using ValueToSExts = DenseMap<Value *, SExts>;
231
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000232class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000233
Chris Lattner2dd09db2009-09-02 06:11:42 +0000234 class CodeGenPrepare : public FunctionPass {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000235 const TargetMachine *TM = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000236 const TargetSubtargetInfo *SubtargetInfo;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000237 const TargetLowering *TLI = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000238 const TargetRegisterInfo *TRI;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000239 const TargetTransformInfo *TTI = nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000240 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000241 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000242 std::unique_ptr<BlockFrequencyInfo> BFI;
243 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000244
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000245 /// As we scan instructions optimizing them, this is the next instruction
246 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000247 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000248
Evan Cheng0663f232011-03-21 01:19:09 +0000249 /// Keeps track of non-local addresses that have been sunk into a block.
250 /// This allows us to avoid inserting duplicate code for blocks with
Simon Dardis230f4532017-11-24 16:45:28 +0000251 /// multiple load/stores of the same address. The usage of WeakTrackingVH
252 /// enables SunkAddrs to be treated as a cache whose entries can be
253 /// invalidated if a sunken address computation has been erased.
254 ValueMap<Value*, WeakTrackingVH> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000255
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000256 /// Keeps track of all instructions inserted for the current function.
257 SetOfInstrs InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000258
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000259 /// Keeps track of the type of the related instruction before their
260 /// promotion for the current function.
261 InstrToOrigTy PromotedInsts;
262
Jun Bum Limdee55652017-04-03 19:20:07 +0000263 /// Keep track of instructions removed during promotion.
264 SetOfInstrs RemovedInsts;
265
266 /// Keep track of sext chains based on their initial value.
267 DenseMap<Value *, Instruction *> SeenChainsForSExt;
268
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000269 /// Keep track of GEPs accessing the same data structures such as structs or
270 /// arrays that are candidates to be split later because of their large
271 /// size.
272 DenseMap<
273 AssertingVH<Value>,
274 SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
275 LargeOffsetGEPMap;
276
277 /// Keep track of new GEP base after splitting the GEPs having large offset.
278 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
279
280 /// Map serial numbers to Large offset GEPs.
281 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
282
Jun Bum Limdee55652017-04-03 19:20:07 +0000283 /// Keep track of SExt promoted.
284 ValueToSExts ValToSExtendedUses;
285
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000286 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000287 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000288
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000289 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000290 bool OptSize;
291
Mehdi Amini4fe37982015-07-07 18:45:17 +0000292 /// DataLayout for the Function being processed.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000293 const DataLayout *DL = nullptr;
Mehdi Amini4fe37982015-07-07 18:45:17 +0000294
Chris Lattnerf2836d12007-03-31 04:06:36 +0000295 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000296 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000297
298 CodeGenPrepare() : FunctionPass(ID) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000299 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
300 }
Eugene Zelenko900b6332017-08-29 22:32:07 +0000301
Craig Topper4584cd52014-03-07 09:26:03 +0000302 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000303
Mehdi Amini117296c2016-10-01 02:56:57 +0000304 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000305
Craig Topper4584cd52014-03-07 09:26:03 +0000306 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000307 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000308 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000309 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000310 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000311 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000312 }
313
Chris Lattnerf2836d12007-03-31 04:06:36 +0000314 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000315 bool eliminateFallThrough(Function &F);
316 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000317 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000318 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
319 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000320 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
321 bool isPreheader);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000322 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
323 bool optimizeInst(Instruction *I, bool &ModifiedDT);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000324 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
325 Type *AccessTy, unsigned AddrSpace);
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);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000330 bool optimizeLoadExt(LoadInst *Load);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000331 bool optimizeSelectInst(SelectInst *SI);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000332 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
333 bool optimizeSwitchInst(SwitchInst *SI);
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;
David Stenberg23bba562018-07-02 14:23:48 +0000465 // Use a set vector to get deterministic iteration order. The order the
466 // blocks are removed may affect whether or not PHI nodes in successors
467 // are removed.
468 SmallSetVector<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000469 for (BasicBlock &BB : F) {
470 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
471 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000472 if (!MadeChange) continue;
473
474 for (SmallVectorImpl<BasicBlock*>::iterator
475 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
476 if (pred_begin(*II) == pred_end(*II))
477 WorkList.insert(*II);
478 }
479
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000480 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000481 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000482 while (!WorkList.empty()) {
David Stenberg23bba562018-07-02 14:23:48 +0000483 BasicBlock *BB = WorkList.pop_back_val();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000484 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
485
486 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000487
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000488 for (SmallVectorImpl<BasicBlock*>::iterator
489 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
490 if (pred_begin(*II) == pred_end(*II))
491 WorkList.insert(*II);
492 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000493
Nadav Rotem70409992012-08-14 05:19:07 +0000494 // Merge pairs of basic blocks with unconditional branches, connected by
495 // a single edge.
496 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000497 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000498
Cameron Zwarich338d3622011-03-11 21:52:04 +0000499 EverMadeChange |= MadeChange;
500 }
501
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000502 if (!DisableGCOpts) {
503 SmallVector<Instruction *, 2> Statepoints;
504 for (BasicBlock &BB : F)
505 for (Instruction &I : BB)
506 if (isStatepoint(I))
507 Statepoints.push_back(&I);
508 for (auto &I : Statepoints)
509 EverMadeChange |= simplifyOffsetableRelocate(*I);
510 }
511
Chris Lattnerf2836d12007-03-31 04:06:36 +0000512 return EverMadeChange;
513}
514
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000515/// Merge basic blocks which are connected by a single edge, where one of the
516/// basic blocks has a single successor pointing to the other basic block,
517/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000518bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000519 bool Changed = false;
520 // Scan all of the blocks in the function, except for the entry block.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000521 // Use a temporary array to avoid iterator being invalidated when
522 // deleting blocks.
523 SmallVector<WeakTrackingVH, 16> Blocks;
524 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
525 Blocks.push_back(&Block);
526
527 for (auto &Block : Blocks) {
528 auto *BB = cast_or_null<BasicBlock>(Block);
529 if (!BB)
530 continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000531 // If the destination block has a single pred, then this is a trivial
532 // edge, just collapse it.
533 BasicBlock *SinglePred = BB->getSinglePredecessor();
534
Evan Cheng64a223a2012-09-28 23:58:57 +0000535 // Don't merge if BB's address is taken.
536 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000537
538 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
539 if (Term && !Term->isConditional()) {
540 Changed = true;
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000541 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000542
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000543 // Merge BB into SinglePred and delete it.
544 MergeBlockIntoPredecessor(BB);
Nadav Rotem70409992012-08-14 05:19:07 +0000545 }
546 }
547 return Changed;
548}
549
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000550/// Find a destination block from BB if BB is mergeable empty block.
551BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
552 // If this block doesn't end with an uncond branch, ignore it.
553 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
554 if (!BI || !BI->isUnconditional())
555 return nullptr;
556
557 // If the instruction before the branch (skipping debug info) isn't a phi
558 // node, then other stuff is happening here.
559 BasicBlock::iterator BBI = BI->getIterator();
560 if (BBI != BB->begin()) {
561 --BBI;
562 while (isa<DbgInfoIntrinsic>(BBI)) {
563 if (BBI == BB->begin())
564 break;
565 --BBI;
566 }
567 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
568 return nullptr;
569 }
570
571 // Do not break infinite loops.
572 BasicBlock *DestBB = BI->getSuccessor(0);
573 if (DestBB == BB)
574 return nullptr;
575
576 if (!canMergeBlocks(BB, DestBB))
577 DestBB = nullptr;
578
579 return DestBB;
580}
581
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000582/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
583/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
584/// edges in ways that are non-optimal for isel. Start by eliminating these
585/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000586bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000587 SmallPtrSet<BasicBlock *, 16> Preheaders;
588 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
589 while (!LoopList.empty()) {
590 Loop *L = LoopList.pop_back_val();
591 LoopList.insert(LoopList.end(), L->begin(), L->end());
592 if (BasicBlock *Preheader = L->getLoopPreheader())
593 Preheaders.insert(Preheader);
594 }
595
Chris Lattnerc3748562007-04-02 01:35:34 +0000596 bool MadeChange = false;
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000597 // Copy blocks into a temporary array to avoid iterator invalidation issues
598 // as we remove them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000599 // Note that this intentionally skips the entry block.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000600 SmallVector<WeakTrackingVH, 16> Blocks;
601 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
602 Blocks.push_back(&Block);
603
604 for (auto &Block : Blocks) {
605 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
606 if (!BB)
607 continue;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000608 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
609 if (!DestBB ||
610 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000611 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000612
Sanjay Patelfc580a62015-09-21 23:03:16 +0000613 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000614 MadeChange = true;
615 }
616 return MadeChange;
617}
618
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000619bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
620 BasicBlock *DestBB,
621 bool isPreheader) {
622 // Do not delete loop preheaders if doing so would create a critical edge.
623 // Loop preheaders can be good locations to spill registers. If the
624 // preheader is deleted and we create a critical edge, registers may be
625 // spilled in the loop body instead.
626 if (!DisablePreheaderProtect && isPreheader &&
627 !(BB->getSinglePredecessor() &&
628 BB->getSinglePredecessor()->getSingleSuccessor()))
629 return false;
630
631 // Try to skip merging if the unique predecessor of BB is terminated by a
632 // switch or indirect branch instruction, and BB is used as an incoming block
633 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
634 // add COPY instructions in the predecessor of BB instead of BB (if it is not
635 // merged). Note that the critical edge created by merging such blocks wont be
636 // split in MachineSink because the jump table is not analyzable. By keeping
637 // such empty block (BB), ISel will place COPY instructions in BB, not in the
638 // predecessor of BB.
639 BasicBlock *Pred = BB->getUniquePredecessor();
640 if (!Pred ||
641 !(isa<SwitchInst>(Pred->getTerminator()) ||
642 isa<IndirectBrInst>(Pred->getTerminator())))
643 return true;
644
Jonas Devlieghere42243df2018-08-07 12:14:01 +0000645 if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000646 return true;
647
648 // We use a simple cost heuristic which determine skipping merging is
649 // profitable if the cost of skipping merging is less than the cost of
650 // merging : Cost(skipping merging) < Cost(merging BB), where the
651 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
652 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
653 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
654 // Freq(Pred) / Freq(BB) > 2.
655 // Note that if there are multiple empty blocks sharing the same incoming
656 // value for the PHIs in the DestBB, we consider them together. In such
657 // case, Cost(merging BB) will be the sum of their frequencies.
658
659 if (!isa<PHINode>(DestBB->begin()))
660 return true;
661
662 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
663
664 // Find all other incoming blocks from which incoming values of all PHIs in
665 // DestBB are the same as the ones from BB.
666 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
667 ++PI) {
668 BasicBlock *DestBBPred = *PI;
669 if (DestBBPred == BB)
670 continue;
671
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000672 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
673 return DestPN.getIncomingValueForBlock(BB) ==
674 DestPN.getIncomingValueForBlock(DestBBPred);
675 }))
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000676 SameIncomingValueBBs.insert(DestBBPred);
677 }
678
679 // See if all BB's incoming values are same as the value from Pred. In this
680 // case, no reason to skip merging because COPYs are expected to be place in
681 // Pred already.
682 if (SameIncomingValueBBs.count(Pred))
683 return true;
684
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000685 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
686 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
687
688 for (auto SameValueBB : SameIncomingValueBBs)
689 if (SameValueBB->getUniquePredecessor() == Pred &&
690 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
691 BBFreq += BFI->getBlockFreq(SameValueBB);
692
693 return PredFreq.getFrequency() <=
694 BBFreq.getFrequency() * FreqRatioToSkipMerge;
695}
696
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000697/// Return true if we can merge BB into DestBB if there is a single
698/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000699/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000700bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000701 const BasicBlock *DestBB) const {
702 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
703 // the successor. If there are more complex condition (e.g. preheaders),
704 // don't mess around with them.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000705 for (const PHINode &PN : BB->phis()) {
706 for (const User *U : PN.users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000707 const Instruction *UI = cast<Instruction>(U);
708 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000709 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000710 // If User is inside DestBB block and it is a PHINode then check
711 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000712 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000713 if (UI->getParent() == DestBB) {
714 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000715 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
716 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
717 if (Insn && Insn->getParent() == BB &&
718 Insn->getParent() != UPN->getIncomingBlock(I))
719 return false;
720 }
721 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000722 }
723 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000724
Chris Lattnerc3748562007-04-02 01:35:34 +0000725 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
726 // and DestBB may have conflicting incoming values for the block. If so, we
727 // can't merge the block.
728 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
729 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000730
Chris Lattnerc3748562007-04-02 01:35:34 +0000731 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000732 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000733 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
734 // It is faster to get preds from a PHI than with pred_iterator.
735 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
736 BBPreds.insert(BBPN->getIncomingBlock(i));
737 } else {
738 BBPreds.insert(pred_begin(BB), pred_end(BB));
739 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000740
Chris Lattnerc3748562007-04-02 01:35:34 +0000741 // Walk the preds of DestBB.
742 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
743 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
744 if (BBPreds.count(Pred)) { // Common predecessor?
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000745 for (const PHINode &PN : DestBB->phis()) {
746 const Value *V1 = PN.getIncomingValueForBlock(Pred);
747 const Value *V2 = PN.getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000748
Chris Lattnerc3748562007-04-02 01:35:34 +0000749 // If V2 is a phi node in BB, look up what the mapped value will be.
750 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
751 if (V2PN->getParent() == BB)
752 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000753
Chris Lattnerc3748562007-04-02 01:35:34 +0000754 // If there is a conflict, bail out.
755 if (V1 != V2) return false;
756 }
757 }
758 }
759
760 return true;
761}
762
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000763/// Eliminate a basic block that has only phi's and an unconditional branch in
764/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000765void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000766 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
767 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000768
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000769 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
770 << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000771
Chris Lattnerc3748562007-04-02 01:35:34 +0000772 // If the destination block has a single pred, then this is a trivial edge,
773 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000774 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000775 if (SinglePred != DestBB) {
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000776 assert(SinglePred == BB &&
777 "Single predecessor not the same as predecessor");
778 // Merge DestBB into SinglePred/BB and delete it.
779 MergeBlockIntoPredecessor(DestBB);
780 // Note: BB(=SinglePred) will not be deleted on this path.
781 // DestBB(=its single successor) is the one that was deleted.
782 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000783 return;
784 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000785 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000786
Chris Lattnerc3748562007-04-02 01:35:34 +0000787 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
788 // to handle the new incoming edges it is about to have.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000789 for (PHINode &PN : DestBB->phis()) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000790 // Remove the incoming value for BB, and remember it.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000791 Value *InVal = PN.removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000792
Chris Lattnerc3748562007-04-02 01:35:34 +0000793 // Two options: either the InVal is a phi node defined in BB or it is some
794 // value that dominates BB.
795 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
796 if (InValPhi && InValPhi->getParent() == BB) {
797 // Add all of the input values of the input PHI as inputs of this phi.
798 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000799 PN.addIncoming(InValPhi->getIncomingValue(i),
800 InValPhi->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000801 } else {
802 // Otherwise, add one instance of the dominating value for each edge that
803 // we will be adding.
804 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
805 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000806 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000807 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000808 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000809 PN.addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000810 }
811 }
812 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000813
Chris Lattnerc3748562007-04-02 01:35:34 +0000814 // The PHIs are now updated, change everything that refers to BB to use
815 // DestBB and remove BB.
816 BB->replaceAllUsesWith(DestBB);
817 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000818 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000819
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000820 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000821}
822
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000823// Computes a map of base pointer relocation instructions to corresponding
824// derived pointer relocation instructions given a vector of all relocate calls
825static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000826 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
827 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
828 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000829 // Collect information in two maps: one primarily for locating the base object
830 // while filling the second map; the second map is the final structure holding
831 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000832 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
833 for (auto *ThisRelocate : AllRelocateCalls) {
834 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
835 ThisRelocate->getDerivedPtrIndex());
836 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000837 }
838 for (auto &Item : RelocateIdxMap) {
839 std::pair<unsigned, unsigned> Key = Item.first;
840 if (Key.first == Key.second)
841 // Base relocation: nothing to insert
842 continue;
843
Manuel Jacob83eefa62016-01-05 04:03:00 +0000844 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000845 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000846
847 // We're iterating over RelocateIdxMap so we cannot modify it.
848 auto MaybeBase = RelocateIdxMap.find(BaseKey);
849 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000850 // TODO: We might want to insert a new base object relocate and gep off
851 // that, if there are enough derived object relocates.
852 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000853
854 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000855 }
856}
857
858// Accepts a GEP and extracts the operands into a vector provided they're all
859// small integer constants
860static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
861 SmallVectorImpl<Value *> &OffsetV) {
862 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
863 // Only accept small constant integer operands
864 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
865 if (!Op || Op->getZExtValue() > 20)
866 return false;
867 }
868
869 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
870 OffsetV.push_back(GEP->getOperand(i));
871 return true;
872}
873
874// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
875// replace, computes a replacement, and affects it.
876static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000877simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
878 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000879 bool MadeChange = false;
Serguei Katkov9e5604d2017-08-17 05:48:30 +0000880 // We must ensure the relocation of derived pointer is defined after
881 // relocation of base pointer. If we find a relocation corresponding to base
882 // defined earlier than relocation of base then we move relocation of base
883 // right before found relocation. We consider only relocation in the same
884 // basic block as relocation of base. Relocations from other basic block will
885 // be skipped by optimization and we do not care about them.
886 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
887 &*R != RelocatedBase; ++R)
888 if (auto RI = dyn_cast<GCRelocateInst>(R))
889 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
890 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
891 RelocatedBase->moveBefore(RI);
892 break;
893 }
894
Manuel Jacob83eefa62016-01-05 04:03:00 +0000895 for (GCRelocateInst *ToReplace : Targets) {
896 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000897 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000898 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000899 // A duplicate relocate call. TODO: coalesce duplicates.
900 continue;
901 }
902
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000903 if (RelocatedBase->getParent() != ToReplace->getParent()) {
904 // Base and derived relocates are in different basic blocks.
905 // In this case transform is only valid when base dominates derived
906 // relocate. However it would be too expensive to check dominance
907 // for each such relocate, so we skip the whole transformation.
908 continue;
909 }
910
Manuel Jacob83eefa62016-01-05 04:03:00 +0000911 Value *Base = ToReplace->getBasePtr();
912 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000913 if (!Derived || Derived->getPointerOperand() != Base)
914 continue;
915
916 SmallVector<Value *, 2> OffsetV;
917 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
918 continue;
919
920 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000921 assert(RelocatedBase->getNextNode() &&
922 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000923
924 // Insert after RelocatedBase
925 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000926 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000927
928 // If gc_relocate does not match the actual type, cast it to the right type.
929 // In theory, there must be a bitcast after gc_relocate if the type does not
930 // match, and we should reuse it to get the derived pointer. But it could be
931 // cases like this:
932 // bb1:
933 // ...
934 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
935 // br label %merge
936 //
937 // bb2:
938 // ...
939 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
940 // br label %merge
941 //
942 // merge:
943 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
944 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
945 //
946 // In this case, we can not find the bitcast any more. So we insert a new bitcast
947 // no matter there is already one or not. In this way, we can handle all cases, and
948 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000949 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000950 if (RelocatedBase->getType() != Base->getType()) {
951 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000952 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000953 }
David Blaikie68d535c2015-03-24 22:38:16 +0000954 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000955 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000956 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000957 // If the newly generated derived pointer's type does not match the original derived
958 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000959 Value *ActualReplacement = Replacement;
960 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000961 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000962 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000963 }
964 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000965 ToReplace->eraseFromParent();
966
967 MadeChange = true;
968 }
969 return MadeChange;
970}
971
972// Turns this:
973//
974// %base = ...
975// %ptr = gep %base + 15
976// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
977// %base' = relocate(%tok, i32 4, i32 4)
978// %ptr' = relocate(%tok, i32 4, i32 5)
979// %val = load %ptr'
980//
981// into this:
982//
983// %base = ...
984// %ptr = gep %base + 15
985// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
986// %base' = gc.relocate(%tok, i32 4, i32 4)
987// %ptr' = gep %base' + 15
988// %val = load %ptr'
989bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
990 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000991 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000992
993 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000994 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000995 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000996 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000997
998 // We need atleast one base pointer relocation + one derived pointer
999 // relocation to mangle
1000 if (AllRelocateCalls.size() < 2)
1001 return false;
1002
1003 // RelocateInstMap is a mapping from the base relocate instruction to the
1004 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +00001005 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001006 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1007 if (RelocateInstMap.empty())
1008 return false;
1009
1010 for (auto &Item : RelocateInstMap)
1011 // Item.first is the RelocatedBase to offset against
1012 // Item.second is the vector of Targets to replace
1013 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1014 return MadeChange;
1015}
1016
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001017/// SinkCast - Sink the specified cast instruction into its user blocks
1018static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001019 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001020
Chris Lattnerf2836d12007-03-31 04:06:36 +00001021 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001022 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001023
Chris Lattnerf2836d12007-03-31 04:06:36 +00001024 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001025 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001026 UI != E; ) {
1027 Use &TheUse = UI.getUse();
1028 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001029
Chris Lattnerf2836d12007-03-31 04:06:36 +00001030 // Figure out which BB this cast is used in. For PHI's this is the
1031 // appropriate predecessor block.
1032 BasicBlock *UserBB = User->getParent();
1033 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001034 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001035 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001036
Chris Lattnerf2836d12007-03-31 04:06:36 +00001037 // Preincrement use iterator so we don't invalidate it.
1038 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001039
David Majnemer0c80e2e2016-04-27 19:36:38 +00001040 // The first insertion point of a block containing an EH pad is after the
1041 // pad. If the pad is the user, we cannot sink the cast past the pad.
1042 if (User->isEHPad())
1043 continue;
1044
Andrew Kaylord0430e82015-11-23 19:16:15 +00001045 // If the block selected to receive the cast is an EH pad that does not
1046 // allow non-PHI instructions before the terminator, we can't sink the
1047 // cast.
1048 if (UserBB->getTerminator()->isEHPad())
1049 continue;
1050
Chris Lattnerf2836d12007-03-31 04:06:36 +00001051 // If this user is in the same block as the cast, don't change the cast.
1052 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001053
Chris Lattnerf2836d12007-03-31 04:06:36 +00001054 // If we have already inserted a cast into this block, use it.
1055 CastInst *&InsertedCast = InsertedCasts[UserBB];
1056
1057 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001058 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001059 assert(InsertPt != UserBB->end());
1060 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1061 CI->getType(), "", &*InsertPt);
Vedant Kumar9374c042018-05-23 22:03:48 +00001062 InsertedCast->setDebugLoc(CI->getDebugLoc());
Chris Lattnerf2836d12007-03-31 04:06:36 +00001063 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001064
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001065 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001066 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001067 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001068 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001069 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001070
Chris Lattnerf2836d12007-03-31 04:06:36 +00001071 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001072 if (CI->use_empty()) {
Adrian Prantl261ac8b2017-11-03 21:55:03 +00001073 salvageDebugInfo(*CI);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001074 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001075 MadeChange = true;
1076 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001077
Chris Lattnerf2836d12007-03-31 04:06:36 +00001078 return MadeChange;
1079}
1080
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001081/// If the specified cast instruction is a noop copy (e.g. it's casting from
1082/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1083/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001084///
1085/// Return true if any changes are made.
Mehdi Amini44ede332015-07-09 02:09:04 +00001086static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1087 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001088 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1089 // than sinking only nop casts, but is helpful on some platforms.
1090 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1091 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1092 ASC->getDestAddressSpace()))
1093 return false;
1094 }
1095
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001096 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001097 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1098 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001099
1100 // This is an fp<->int conversion?
1101 if (SrcVT.isInteger() != DstVT.isInteger())
1102 return false;
1103
1104 // If this is an extension, it will be a zero or sign extension, which
1105 // isn't a noop.
1106 if (SrcVT.bitsLT(DstVT)) return false;
1107
1108 // If these values will be promoted, find out what they will be promoted
1109 // to. This helps us consider truncates on PPC as noop copies when they
1110 // are.
1111 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1112 TargetLowering::TypePromoteInteger)
1113 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1114 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1115 TargetLowering::TypePromoteInteger)
1116 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1117
1118 // If, after promotion, these are the same types, this is a noop copy.
1119 if (SrcVT != DstVT)
1120 return false;
1121
1122 return SinkCast(CI);
1123}
1124
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001125/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1126/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001127///
1128/// Return true if any changes were made.
1129static bool CombineUAddWithOverflow(CmpInst *CI) {
1130 Value *A, *B;
1131 Instruction *AddI;
1132 if (!match(CI,
1133 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1134 return false;
1135
1136 Type *Ty = AddI->getType();
1137 if (!isa<IntegerType>(Ty))
1138 return false;
1139
1140 // We don't want to move around uses of condition values this late, so we we
1141 // check if it is legal to create the call to the intrinsic in the basic
1142 // block containing the icmp:
1143
1144 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1145 return false;
1146
1147#ifndef NDEBUG
1148 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1149 // for now:
1150 if (AddI->hasOneUse())
1151 assert(*AddI->user_begin() == CI && "expected!");
1152#endif
1153
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001154 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001155 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1156
1157 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1158
1159 auto *UAddWithOverflow =
1160 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1161 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1162 auto *Overflow =
1163 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1164
1165 CI->replaceAllUsesWith(Overflow);
1166 AddI->replaceAllUsesWith(UAdd);
1167 CI->eraseFromParent();
1168 AddI->eraseFromParent();
1169 return true;
1170}
1171
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001172/// Sink the given CmpInst into user blocks to reduce the number of virtual
1173/// registers that must be created and coalesced. This is a clear win except on
1174/// targets with multiple condition code registers (PowerPC), where it might
1175/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001176///
1177/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001178static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001179 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001180
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001181 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001182 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001183 return false;
1184
1185 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001186 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001187
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001188 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001189 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001190 UI != E; ) {
1191 Use &TheUse = UI.getUse();
1192 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001193
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001194 // Preincrement use iterator so we don't invalidate it.
1195 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001196
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001197 // Don't bother for PHI nodes.
1198 if (isa<PHINode>(User))
1199 continue;
1200
1201 // Figure out which BB this cmp is used in.
1202 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001203
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001204 // If this user is in the same block as the cmp, don't change the cmp.
1205 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001206
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001207 // If we have already inserted a cmp into this block, use it.
1208 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1209
1210 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001211 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001212 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001213 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001214 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1215 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001216 // Propagate the debug info.
1217 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001218 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001219
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001220 // Replace a use of the cmp with a use of the new cmp.
1221 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001222 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001223 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001224 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001225
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001226 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001227 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001228 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001229 MadeChange = true;
1230 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001231
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001232 return MadeChange;
1233}
1234
Peter Zotovf87e5502016-04-03 17:11:53 +00001235static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001236 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001237 return true;
1238
1239 if (CombineUAddWithOverflow(CI))
1240 return true;
1241
1242 return false;
1243}
1244
Geoff Berry5d534b62017-02-21 18:53:14 +00001245/// Duplicate and sink the given 'and' instruction into user blocks where it is
1246/// used in a compare to allow isel to generate better code for targets where
1247/// this operation can be combined.
1248///
1249/// Return true if any changes are made.
1250static bool sinkAndCmp0Expression(Instruction *AndI,
1251 const TargetLowering &TLI,
1252 SetOfInstrs &InsertedInsts) {
1253 // Double-check that we're not trying to optimize an instruction that was
1254 // already optimized by some other part of this pass.
1255 assert(!InsertedInsts.count(AndI) &&
1256 "Attempting to optimize already optimized and instruction");
1257 (void) InsertedInsts;
1258
1259 // Nothing to do for single use in same basic block.
1260 if (AndI->hasOneUse() &&
1261 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1262 return false;
1263
1264 // Try to avoid cases where sinking/duplicating is likely to increase register
1265 // pressure.
1266 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1267 !isa<ConstantInt>(AndI->getOperand(1)) &&
1268 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1269 return false;
1270
1271 for (auto *U : AndI->users()) {
1272 Instruction *User = cast<Instruction>(U);
1273
1274 // Only sink for and mask feeding icmp with 0.
1275 if (!isa<ICmpInst>(User))
1276 return false;
1277
1278 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1279 if (!CmpC || !CmpC->isZero())
1280 return false;
1281 }
1282
1283 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1284 return false;
1285
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001286 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1287 LLVM_DEBUG(AndI->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001288
1289 // Push the 'and' into the same block as the icmp 0. There should only be
1290 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1291 // others, so we don't need to keep track of which BBs we insert into.
1292 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1293 UI != E; ) {
1294 Use &TheUse = UI.getUse();
1295 Instruction *User = cast<Instruction>(*UI);
1296
1297 // Preincrement use iterator so we don't invalidate it.
1298 ++UI;
1299
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001300 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
Geoff Berry5d534b62017-02-21 18:53:14 +00001301
1302 // Keep the 'and' in the same place if the use is already in the same block.
1303 Instruction *InsertPt =
1304 User->getParent() == AndI->getParent() ? AndI : User;
1305 Instruction *InsertedAnd =
1306 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1307 AndI->getOperand(1), "", InsertPt);
1308 // Propagate the debug info.
1309 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1310
1311 // Replace a use of the 'and' with a use of the new 'and'.
1312 TheUse = InsertedAnd;
1313 ++NumAndUses;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001314 LLVM_DEBUG(User->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001315 }
1316
1317 // We removed all uses, nuke the and.
1318 AndI->eraseFromParent();
1319 return true;
1320}
1321
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001322/// Check if the candidates could be combined with a shift instruction, which
1323/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001324/// 1. Truncate instruction
1325/// 2. And instruction and the imm is a mask of the low bits:
1326/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001327static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001328 if (!isa<TruncInst>(User)) {
1329 if (User->getOpcode() != Instruction::And ||
1330 !isa<ConstantInt>(User->getOperand(1)))
1331 return false;
1332
Quentin Colombetd4f44692014-04-22 01:20:34 +00001333 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001334
Quentin Colombetd4f44692014-04-22 01:20:34 +00001335 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001336 return false;
1337 }
1338 return true;
1339}
1340
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001341/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001342static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001343SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1344 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001345 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001346 BasicBlock *UserBB = User->getParent();
1347 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1348 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1349 bool MadeChange = false;
1350
1351 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1352 TruncE = TruncI->user_end();
1353 TruncUI != TruncE;) {
1354
1355 Use &TruncTheUse = TruncUI.getUse();
1356 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1357 // Preincrement use iterator so we don't invalidate it.
1358
1359 ++TruncUI;
1360
1361 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1362 if (!ISDOpcode)
1363 continue;
1364
Tim Northovere2239ff2014-07-29 10:20:22 +00001365 // If the use is actually a legal node, there will not be an
1366 // implicit truncate.
1367 // FIXME: always querying the result type is just an
1368 // approximation; some nodes' legality is determined by the
1369 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001370 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001371 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001372 continue;
1373
1374 // Don't bother for PHI nodes.
1375 if (isa<PHINode>(TruncUser))
1376 continue;
1377
1378 BasicBlock *TruncUserBB = TruncUser->getParent();
1379
1380 if (UserBB == TruncUserBB)
1381 continue;
1382
1383 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1384 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1385
1386 if (!InsertedShift && !InsertedTrunc) {
1387 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001388 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001389 // Sink the shift
1390 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001391 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1392 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001393 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001394 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1395 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001396
1397 // Sink the trunc
1398 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1399 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001400 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001401
1402 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001403 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001404
1405 MadeChange = true;
1406
1407 TruncTheUse = InsertedTrunc;
1408 }
1409 }
1410 return MadeChange;
1411}
1412
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001413/// Sink the shift *right* instruction into user blocks if the uses could
1414/// potentially be combined with this shift instruction and generate BitExtract
1415/// instruction. It will only be applied if the architecture supports BitExtract
1416/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001417/// BB1:
1418/// %x.extract.shift = lshr i64 %arg1, 32
1419/// BB2:
1420/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1421/// ==>
1422///
1423/// BB2:
1424/// %x.extract.shift.1 = lshr i64 %arg1, 32
1425/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1426///
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001427/// CodeGen will recognize the pattern in BB2 and generate BitExtract
Yi Jiangd069f632014-04-21 19:34:27 +00001428/// instruction.
1429/// Return true if any changes are made.
1430static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001431 const TargetLowering &TLI,
1432 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001433 BasicBlock *DefBB = ShiftI->getParent();
1434
1435 /// Only insert instructions in each block once.
1436 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1437
Mehdi Amini44ede332015-07-09 02:09:04 +00001438 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001439
1440 bool MadeChange = false;
1441 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1442 UI != E;) {
1443 Use &TheUse = UI.getUse();
1444 Instruction *User = cast<Instruction>(*UI);
1445 // Preincrement use iterator so we don't invalidate it.
1446 ++UI;
1447
1448 // Don't bother for PHI nodes.
1449 if (isa<PHINode>(User))
1450 continue;
1451
1452 if (!isExtractBitsCandidateUse(User))
1453 continue;
1454
1455 BasicBlock *UserBB = User->getParent();
1456
1457 if (UserBB == DefBB) {
1458 // If the shift and truncate instruction are in the same BB. The use of
1459 // the truncate(TruncUse) may still introduce another truncate if not
1460 // legal. In this case, we would like to sink both shift and truncate
1461 // instruction to the BB of TruncUse.
1462 // for example:
1463 // BB1:
1464 // i64 shift.result = lshr i64 opnd, imm
1465 // trunc.result = trunc shift.result to i16
1466 //
1467 // BB2:
1468 // ----> We will have an implicit truncate here if the architecture does
1469 // not have i16 compare.
1470 // cmp i16 trunc.result, opnd2
1471 //
1472 if (isa<TruncInst>(User) && shiftIsLegal
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001473 // If the type of the truncate is legal, no truncate will be
Yi Jiangd069f632014-04-21 19:34:27 +00001474 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001475 &&
1476 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001477 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001478 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001479
1480 continue;
1481 }
1482 // If we have already inserted a shift into this block, use it.
1483 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1484
1485 if (!InsertedShift) {
1486 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001487 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001488
1489 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001490 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1491 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001492 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001493 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1494 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001495
1496 MadeChange = true;
1497 }
1498
1499 // Replace a use of the shift with a use of the new shift.
1500 TheUse = InsertedShift;
1501 }
1502
1503 // If we removed all uses, nuke the shift.
1504 if (ShiftI->use_empty())
1505 ShiftI->eraseFromParent();
1506
1507 return MadeChange;
1508}
1509
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001510/// If counting leading or trailing zeros is an expensive operation and a zero
1511/// input is defined, add a check for zero to avoid calling the intrinsic.
1512///
1513/// We want to transform:
1514/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1515///
1516/// into:
1517/// entry:
1518/// %cmpz = icmp eq i64 %A, 0
1519/// br i1 %cmpz, label %cond.end, label %cond.false
1520/// cond.false:
1521/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1522/// br label %cond.end
1523/// cond.end:
1524/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1525///
1526/// If the transform is performed, return true and set ModifiedDT to true.
1527static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1528 const TargetLowering *TLI,
1529 const DataLayout *DL,
1530 bool &ModifiedDT) {
1531 if (!TLI || !DL)
1532 return false;
1533
1534 // If a zero input is undefined, it doesn't make sense to despeculate that.
1535 if (match(CountZeros->getOperand(1), m_One()))
1536 return false;
1537
1538 // If it's cheap to speculate, there's nothing to do.
1539 auto IntrinsicID = CountZeros->getIntrinsicID();
1540 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1541 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1542 return false;
1543
1544 // Only handle legal scalar cases. Anything else requires too much work.
1545 Type *Ty = CountZeros->getType();
1546 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001547 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001548 return false;
1549
1550 // The intrinsic will be sunk behind a compare against zero and branch.
1551 BasicBlock *StartBlock = CountZeros->getParent();
1552 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1553
1554 // Create another block after the count zero intrinsic. A PHI will be added
1555 // in this block to select the result of the intrinsic or the bit-width
1556 // constant if the input to the intrinsic is zero.
1557 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1558 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1559
1560 // Set up a builder to create a compare, conditional branch, and PHI.
1561 IRBuilder<> Builder(CountZeros->getContext());
1562 Builder.SetInsertPoint(StartBlock->getTerminator());
1563 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1564
1565 // Replace the unconditional branch that was created by the first split with
1566 // a compare against zero and a conditional branch.
1567 Value *Zero = Constant::getNullValue(Ty);
1568 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1569 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1570 StartBlock->getTerminator()->eraseFromParent();
1571
1572 // Create a PHI in the end block to select either the output of the intrinsic
1573 // or the bit width of the operand.
1574 Builder.SetInsertPoint(&EndBlock->front());
1575 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1576 CountZeros->replaceAllUsesWith(PN);
1577 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1578 PN->addIncoming(BitWidth, StartBlock);
1579 PN->addIncoming(CountZeros, CallBlock);
1580
1581 // We are explicitly handling the zero case, so we can set the intrinsic's
1582 // undefined zero argument to 'true'. This will also prevent reprocessing the
1583 // intrinsic; we only despeculate when a zero input is defined.
1584 CountZeros->setArgOperand(1, Builder.getTrue());
1585 ModifiedDT = true;
1586 return true;
1587}
1588
Sanjay Patel3b8974b2017-06-08 20:00:09 +00001589bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001590 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001591
Chris Lattner7a277142011-01-15 07:14:54 +00001592 // Lower inline assembly if we can.
1593 // If we found an inline asm expession, and if the target knows how to
1594 // lower it to normal LLVM code, do so now.
1595 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1596 if (TLI->ExpandInlineAsm(CI)) {
1597 // Avoid invalidating the iterator.
1598 CurInstIterator = BB->begin();
1599 // Avoid processing instructions out of order, which could cause
1600 // reuse before a value is defined.
1601 SunkAddrs.clear();
1602 return true;
1603 }
1604 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001605 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001606 return true;
1607 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001608
John Brawn0dbcd652015-03-18 12:01:59 +00001609 // Align the pointer arguments to this call if the target thinks it's a good
1610 // idea
1611 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001612 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001613 for (auto &Arg : CI->arg_operands()) {
1614 // We want to align both objects whose address is used directly and
1615 // objects whose address is used in casts and GEPs, though it only makes
1616 // sense for GEPs if the offset is a multiple of the desired alignment and
1617 // if size - offset meets the size threshold.
1618 if (!Arg->getType()->isPointerTy())
1619 continue;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001620 APInt Offset(DL->getIndexSizeInBits(
Mehdi Amini4fe37982015-07-07 18:45:17 +00001621 cast<PointerType>(Arg->getType())->getAddressSpace()),
1622 0);
1623 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001624 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001625 if ((Offset2 & (PrefAlign-1)) != 0)
1626 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001627 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001628 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1629 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001630 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001631 // Global variables can only be aligned if they are defined in this
1632 // object (i.e. they are uniquely initialized in this object), and
1633 // over-aligning global variables that have an explicit section is
1634 // forbidden.
1635 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001636 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001637 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001638 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001639 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001640 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001641 }
1642 // If this is a memcpy (or similar) then we may be able to improve the
1643 // alignment
1644 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Daniel Neilsonbe58a222018-01-31 17:24:53 +00001645 unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
1646 if (DestAlign > MI->getDestAlignment())
1647 MI->setDestAlignment(DestAlign);
1648 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1649 unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
1650 if (SrcAlign > MTI->getSourceAlignment())
1651 MTI->setSourceAlignment(SrcAlign);
1652 }
John Brawn0dbcd652015-03-18 12:01:59 +00001653 }
1654 }
1655
Philip Reamesac115ed2016-03-09 23:13:12 +00001656 // If we have a cold call site, try to sink addressing computation into the
1657 // cold block. This interacts with our handling for loads and stores to
1658 // ensure that we can fold all uses of a potential addressing computation
1659 // into their uses. TODO: generalize this to work over profiling data
1660 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1661 for (auto &Arg : CI->arg_operands()) {
1662 if (!Arg->getType()->isPointerTy())
1663 continue;
1664 unsigned AS = Arg->getType()->getPointerAddressSpace();
1665 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1666 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001667
Eric Christopher4b7948e2010-03-11 02:41:03 +00001668 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001669 if (II) {
1670 switch (II->getIntrinsicID()) {
1671 default: break;
1672 case Intrinsic::objectsize: {
1673 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00001674 ConstantInt *RetVal =
1675 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001676 // Substituting this can cause recursive simplifications, which can
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001677 // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case
1678 // this
Sanjoy Das2cbeb002017-04-26 16:37:05 +00001679 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001680 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001681 WeakTrackingVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001682
Sanjay Patel545a4562016-01-20 18:59:16 +00001683 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001684
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001685 // If the iterator instruction was recursively deleted, start over at the
1686 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001687 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001688 CurInstIterator = BB->begin();
1689 SunkAddrs.clear();
1690 }
1691 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001692 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001693 case Intrinsic::aarch64_stlxr:
1694 case Intrinsic::aarch64_stxr: {
1695 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1696 if (!ExtVal || !ExtVal->hasOneUse() ||
1697 ExtVal->getParent() == CI->getParent())
1698 return false;
1699 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1700 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001701 // Mark this instruction as "inserted by CGP", so that other
1702 // optimizations don't touch it.
1703 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001704 return true;
1705 }
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001706 case Intrinsic::launder_invariant_group:
Piotr Padlewski5b3db452018-07-02 04:49:30 +00001707 case Intrinsic::strip_invariant_group:
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001708 II->replaceAllUsesWith(II->getArgOperand(0));
1709 II->eraseFromParent();
1710 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001711
1712 case Intrinsic::cttz:
1713 case Intrinsic::ctlz:
1714 // If counting zeros is expensive, try to avoid it.
1715 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001716 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001717
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001718 if (TLI) {
1719 SmallVector<Value*, 2> PtrOps;
1720 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001721 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1722 while (!PtrOps.empty()) {
1723 Value *PtrVal = PtrOps.pop_back_val();
1724 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1725 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001726 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001727 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001728 }
Pete Cooper615fd892012-03-13 20:59:56 +00001729 }
1730
Eric Christopher4b7948e2010-03-11 02:41:03 +00001731 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001732 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001733
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001734 // Lower all default uses of _chk calls. This is very similar
1735 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001736 // to fortified library functions (e.g. __memcpy_chk) that have the default
1737 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001738 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001739 if (Value *V = Simplifier.optimizeCall(CI)) {
1740 CI->replaceAllUsesWith(V);
1741 CI->eraseFromParent();
1742 return true;
1743 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001744
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001745 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001746}
Chris Lattner1b93be52011-01-15 07:25:29 +00001747
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001748/// Look for opportunities to duplicate return instructions to the predecessor
1749/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001750/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001751/// bb0:
1752/// %tmp0 = tail call i32 @f0()
1753/// br label %return
1754/// bb1:
1755/// %tmp1 = tail call i32 @f1()
1756/// br label %return
1757/// bb2:
1758/// %tmp2 = tail call i32 @f2()
1759/// br label %return
1760/// return:
1761/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1762/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001763/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001764///
1765/// =>
1766///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001767/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001768/// bb0:
1769/// %tmp0 = tail call i32 @f0()
1770/// ret i32 %tmp0
1771/// bb1:
1772/// %tmp1 = tail call i32 @f1()
1773/// ret i32 %tmp1
1774/// bb2:
1775/// %tmp2 = tail call i32 @f2()
1776/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001777/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001778bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001779 if (!TLI)
1780 return false;
1781
Michael Kuperstein71321562016-09-07 20:29:49 +00001782 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1783 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001784 return false;
1785
Craig Topperc0196b12014-04-14 00:51:57 +00001786 PHINode *PN = nullptr;
1787 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001788 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001789 if (V) {
1790 BCI = dyn_cast<BitCastInst>(V);
1791 if (BCI)
1792 V = BCI->getOperand(0);
1793
1794 PN = dyn_cast<PHINode>(V);
1795 if (!PN)
1796 return false;
1797 }
Evan Cheng0663f232011-03-21 01:19:09 +00001798
Cameron Zwarich4649f172011-03-24 04:52:10 +00001799 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001800 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001801
Cameron Zwarich4649f172011-03-24 04:52:10 +00001802 // Make sure there are no instructions between the PHI and return, or that the
1803 // return is the first instruction in the block.
1804 if (PN) {
1805 BasicBlock::iterator BI = BB->begin();
1806 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001807 if (&*BI == BCI)
1808 // Also skip over the bitcast.
1809 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001810 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001811 return false;
1812 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001813 BasicBlock::iterator BI = BB->begin();
1814 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001815 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001816 return false;
1817 }
Evan Cheng0663f232011-03-21 01:19:09 +00001818
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001819 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1820 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001821 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001822 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001823 if (PN) {
1824 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1825 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1826 // Make sure the phi value is indeed produced by the tail call.
1827 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001828 TLI->mayBeEmittedAsTailCall(CI) &&
1829 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001830 TailCalls.push_back(CI);
1831 }
1832 } else {
1833 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001834 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001835 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001836 continue;
1837
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001838 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001839 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1840 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001841 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1842 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001843 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001844
Cameron Zwarich4649f172011-03-24 04:52:10 +00001845 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001846 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1847 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001848 TailCalls.push_back(CI);
1849 }
Evan Cheng0663f232011-03-21 01:19:09 +00001850 }
1851
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001852 bool Changed = false;
1853 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1854 CallInst *CI = TailCalls[i];
1855 CallSite CS(CI);
1856
1857 // Conservatively require the attributes of the call to match those of the
1858 // return. Ignore noalias because it doesn't affect the call sequence.
Reid Klecknerb5180542017-03-21 16:57:19 +00001859 AttributeList CalleeAttrs = CS.getAttributes();
1860 if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1861 .removeAttribute(Attribute::NoAlias) !=
1862 AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1863 .removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001864 continue;
1865
1866 // Make sure the call instruction is followed by an unconditional branch to
1867 // the return block.
1868 BasicBlock *CallBB = CI->getParent();
1869 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1870 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1871 continue;
1872
1873 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00001874 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001875 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001876 ++NumRetsDup;
1877 }
1878
1879 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001880 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001881 BB->eraseFromParent();
1882
1883 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001884}
1885
Chris Lattner728f9022008-11-25 07:09:13 +00001886//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001887// Memory Optimization
1888//===----------------------------------------------------------------------===//
1889
Chandler Carruthc8925912013-01-05 02:09:22 +00001890namespace {
1891
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001892/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00001893/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001894struct ExtAddrMode : public TargetLowering::AddrMode {
Eugene Zelenko900b6332017-08-29 22:32:07 +00001895 Value *BaseReg = nullptr;
1896 Value *ScaledReg = nullptr;
John Brawn736bf002017-10-03 13:08:22 +00001897 Value *OriginalValue = nullptr;
1898
1899 enum FieldName {
1900 NoField = 0x00,
1901 BaseRegField = 0x01,
1902 BaseGVField = 0x02,
1903 BaseOffsField = 0x04,
1904 ScaledRegField = 0x08,
1905 ScaleField = 0x10,
1906 MultipleFields = 0xff
1907 };
Eugene Zelenko900b6332017-08-29 22:32:07 +00001908
1909 ExtAddrMode() = default;
1910
Chandler Carruthc8925912013-01-05 02:09:22 +00001911 void print(raw_ostream &OS) const;
1912 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001913
John Brawn736bf002017-10-03 13:08:22 +00001914 FieldName compare(const ExtAddrMode &other) {
1915 // First check that the types are the same on each field, as differing types
1916 // is something we can't cope with later on.
1917 if (BaseReg && other.BaseReg &&
1918 BaseReg->getType() != other.BaseReg->getType())
1919 return MultipleFields;
1920 if (BaseGV && other.BaseGV &&
1921 BaseGV->getType() != other.BaseGV->getType())
1922 return MultipleFields;
1923 if (ScaledReg && other.ScaledReg &&
1924 ScaledReg->getType() != other.ScaledReg->getType())
1925 return MultipleFields;
1926
1927 // Check each field to see if it differs.
1928 unsigned Result = NoField;
1929 if (BaseReg != other.BaseReg)
1930 Result |= BaseRegField;
1931 if (BaseGV != other.BaseGV)
1932 Result |= BaseGVField;
1933 if (BaseOffs != other.BaseOffs)
1934 Result |= BaseOffsField;
1935 if (ScaledReg != other.ScaledReg)
1936 Result |= ScaledRegField;
1937 // Don't count 0 as being a different scale, because that actually means
1938 // unscaled (which will already be counted by having no ScaledReg).
1939 if (Scale && other.Scale && Scale != other.Scale)
1940 Result |= ScaleField;
1941
1942 if (countPopulation(Result) > 1)
1943 return MultipleFields;
1944 else
1945 return static_cast<FieldName>(Result);
1946 }
1947
John Brawn4b476482017-11-27 11:29:15 +00001948 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
1949 // with no offset.
John Brawn736bf002017-10-03 13:08:22 +00001950 bool isTrivial() {
John Brawn4b476482017-11-27 11:29:15 +00001951 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
1952 // trivial if at most one of these terms is nonzero, except that BaseGV and
1953 // BaseReg both being zero actually means a null pointer value, which we
1954 // consider to be 'non-zero' here.
1955 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
Chandler Carruthc8925912013-01-05 02:09:22 +00001956 }
John Brawn70cdb5b2017-11-24 14:10:45 +00001957
1958 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
1959 switch (Field) {
1960 default:
1961 return nullptr;
1962 case BaseRegField:
1963 return BaseReg;
1964 case BaseGVField:
1965 return BaseGV;
1966 case ScaledRegField:
1967 return ScaledReg;
1968 case BaseOffsField:
1969 return ConstantInt::get(IntPtrTy, BaseOffs);
1970 }
1971 }
1972
1973 void SetCombinedField(FieldName Field, Value *V,
1974 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
1975 switch (Field) {
1976 default:
1977 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
1978 break;
1979 case ExtAddrMode::BaseRegField:
1980 BaseReg = V;
1981 break;
1982 case ExtAddrMode::BaseGVField:
1983 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
1984 // in the BaseReg field.
1985 assert(BaseReg == nullptr);
1986 BaseReg = V;
1987 BaseGV = nullptr;
1988 break;
1989 case ExtAddrMode::ScaledRegField:
1990 ScaledReg = V;
1991 // If we have a mix of scaled and unscaled addrmodes then we want scale
1992 // to be the scale and not zero.
1993 if (!Scale)
1994 for (const ExtAddrMode &AM : AddrModes)
1995 if (AM.Scale) {
1996 Scale = AM.Scale;
1997 break;
1998 }
1999 break;
2000 case ExtAddrMode::BaseOffsField:
2001 // The offset is no longer a constant, so it goes in ScaledReg with a
2002 // scale of 1.
2003 assert(ScaledReg == nullptr);
2004 ScaledReg = V;
2005 Scale = 1;
2006 BaseOffs = 0;
2007 break;
2008 }
2009 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002010};
2011
Eugene Zelenko900b6332017-08-29 22:32:07 +00002012} // end anonymous namespace
2013
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002014#ifndef NDEBUG
2015static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2016 AM.print(OS);
2017 return OS;
2018}
2019#endif
2020
Aaron Ballman615eb472017-10-15 14:32:27 +00002021#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthc8925912013-01-05 02:09:22 +00002022void ExtAddrMode::print(raw_ostream &OS) const {
2023 bool NeedPlus = false;
2024 OS << "[";
2025 if (BaseGV) {
2026 OS << (NeedPlus ? " + " : "")
2027 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002028 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002029 NeedPlus = true;
2030 }
2031
Richard Trieuc0f91212014-05-30 03:15:17 +00002032 if (BaseOffs) {
2033 OS << (NeedPlus ? " + " : "")
2034 << BaseOffs;
2035 NeedPlus = true;
2036 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002037
2038 if (BaseReg) {
2039 OS << (NeedPlus ? " + " : "")
2040 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002041 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002042 NeedPlus = true;
2043 }
2044 if (Scale) {
2045 OS << (NeedPlus ? " + " : "")
2046 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002047 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002048 }
2049
2050 OS << ']';
2051}
2052
Yaron Kereneb2a2542016-01-29 20:50:44 +00002053LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002054 print(dbgs());
2055 dbgs() << '\n';
2056}
2057#endif
2058
Eugene Zelenko900b6332017-08-29 22:32:07 +00002059namespace {
2060
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002061/// This class provides transaction based operation on the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002062/// Every change made through this class is recorded in the internal state and
2063/// can be undone (rollback) until commit is called.
2064class TypePromotionTransaction {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002065 /// This represents the common interface of the individual transaction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002066 /// Each class implements the logic for doing one specific modification on
2067 /// the IR via the TypePromotionTransaction.
2068 class TypePromotionAction {
2069 protected:
2070 /// The Instruction modified.
2071 Instruction *Inst;
2072
2073 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002074 /// Constructor of the action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002075 /// The constructor performs the related action on the IR.
2076 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2077
Eugene Zelenko900b6332017-08-29 22:32:07 +00002078 virtual ~TypePromotionAction() = default;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002079
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002080 /// Undo the modification done by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002081 /// When this method is called, the IR must be in the same state as it was
2082 /// before this action was applied.
2083 /// \pre Undoing the action works if and only if the IR is in the exact same
2084 /// state as it was directly after this action was applied.
2085 virtual void undo() = 0;
2086
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002087 /// Advocate every change made by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002088 /// When the results on the IR of the action are to be kept, it is important
2089 /// to call this function, otherwise hidden information may be kept forever.
2090 virtual void commit() {
2091 // Nothing to be done, this action is not doing anything.
2092 }
2093 };
2094
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002095 /// Utility to remember the position of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002096 class InsertionHandler {
2097 /// Position of an instruction.
2098 /// Either an instruction:
2099 /// - Is the first in a basic block: BB is used.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002100 /// - Has a previous instruction: PrevInst is used.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002101 union {
2102 Instruction *PrevInst;
2103 BasicBlock *BB;
2104 } Point;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002105
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002106 /// Remember whether or not the instruction had a previous instruction.
2107 bool HasPrevInstruction;
2108
2109 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002110 /// Record the position of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002111 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002112 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002113 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2114 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002115 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002116 else
2117 Point.BB = Inst->getParent();
2118 }
2119
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002120 /// Insert \p Inst at the recorded position.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002121 void insert(Instruction *Inst) {
2122 if (HasPrevInstruction) {
2123 if (Inst->getParent())
2124 Inst->removeFromParent();
2125 Inst->insertAfter(Point.PrevInst);
2126 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002127 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002128 if (Inst->getParent())
2129 Inst->moveBefore(Position);
2130 else
2131 Inst->insertBefore(Position);
2132 }
2133 }
2134 };
2135
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002136 /// Move an instruction before another.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002137 class InstructionMoveBefore : public TypePromotionAction {
2138 /// Original position of the instruction.
2139 InsertionHandler Position;
2140
2141 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002142 /// Move \p Inst before \p Before.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002143 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2144 : TypePromotionAction(Inst), Position(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002145 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
2146 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002147 Inst->moveBefore(Before);
2148 }
2149
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002150 /// Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002151 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002152 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002153 Position.insert(Inst);
2154 }
2155 };
2156
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002157 /// Set the operand of an instruction with a new value.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002158 class OperandSetter : public TypePromotionAction {
2159 /// Original operand of the instruction.
2160 Value *Origin;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002161
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002162 /// Index of the modified instruction.
2163 unsigned Idx;
2164
2165 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002166 /// Set \p Idx operand of \p Inst with \p NewVal.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002167 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2168 : TypePromotionAction(Inst), Idx(Idx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002169 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2170 << "for:" << *Inst << "\n"
2171 << "with:" << *NewVal << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002172 Origin = Inst->getOperand(Idx);
2173 Inst->setOperand(Idx, NewVal);
2174 }
2175
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002176 /// Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002177 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002178 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2179 << "for: " << *Inst << "\n"
2180 << "with: " << *Origin << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002181 Inst->setOperand(Idx, Origin);
2182 }
2183 };
2184
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002185 /// Hide the operands of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002186 /// Do as if this instruction was not using any of its operands.
2187 class OperandsHider : public TypePromotionAction {
2188 /// The list of original operands.
2189 SmallVector<Value *, 4> OriginalValues;
2190
2191 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002192 /// Remove \p Inst from the uses of the operands of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002193 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002194 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002195 unsigned NumOpnds = Inst->getNumOperands();
2196 OriginalValues.reserve(NumOpnds);
2197 for (unsigned It = 0; It < NumOpnds; ++It) {
2198 // Save the current operand.
2199 Value *Val = Inst->getOperand(It);
2200 OriginalValues.push_back(Val);
2201 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002202 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002203 // that we are not willing to pay.
2204 Inst->setOperand(It, UndefValue::get(Val->getType()));
2205 }
2206 }
2207
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002208 /// Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002209 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002210 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002211 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2212 Inst->setOperand(It, OriginalValues[It]);
2213 }
2214 };
2215
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002216 /// Build a truncate instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002217 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002218 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002219
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002220 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002221 /// Build a truncate instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002222 /// result.
2223 /// trunc Opnd to Ty.
2224 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2225 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002226 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002227 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002228 }
2229
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002230 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002231 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002232
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002233 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002234 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002235 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002236 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2237 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002238 }
2239 };
2240
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002241 /// Build a sign extension instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002242 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002243 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002244
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002245 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002246 /// Build a sign extension instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002247 /// result.
2248 /// sext Opnd to Ty.
2249 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002250 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002251 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002252 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002253 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002254 }
2255
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002256 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002257 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002258
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002259 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002260 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002261 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002262 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2263 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002264 }
2265 };
2266
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002267 /// Build a zero extension instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002268 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002269 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002270
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002271 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002272 /// Build a zero extension instruction of \p Opnd producing a \p Ty
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002273 /// result.
2274 /// zext Opnd to Ty.
2275 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002276 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002277 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002278 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002279 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002280 }
2281
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002282 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002283 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002284
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002285 /// Remove the built instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002286 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002287 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002288 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2289 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002290 }
2291 };
2292
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002293 /// Mutate an instruction to another type.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002294 class TypeMutator : public TypePromotionAction {
2295 /// Record the original type.
2296 Type *OrigTy;
2297
2298 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002299 /// Mutate the type of \p Inst into \p NewTy.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002300 TypeMutator(Instruction *Inst, Type *NewTy)
2301 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002302 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2303 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002304 Inst->mutateType(NewTy);
2305 }
2306
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002307 /// Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002308 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002309 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2310 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002311 Inst->mutateType(OrigTy);
2312 }
2313 };
2314
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002315 /// Replace the uses of an instruction by another instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002316 class UsesReplacer : public TypePromotionAction {
2317 /// Helper structure to keep track of the replaced uses.
2318 struct InstructionAndIdx {
2319 /// The instruction using the instruction.
2320 Instruction *Inst;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002321
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002322 /// The index where this instruction is used for Inst.
2323 unsigned Idx;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002324
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002325 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2326 : Inst(Inst), Idx(Idx) {}
2327 };
2328
2329 /// Keep track of the original uses (pair Instruction, Index).
2330 SmallVector<InstructionAndIdx, 4> OriginalUses;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002331
2332 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002333
2334 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002335 /// Replace all the use of \p Inst by \p New.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002336 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002337 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2338 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002339 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002340 for (Use &U : Inst->uses()) {
2341 Instruction *UserI = cast<Instruction>(U.getUser());
2342 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002343 }
2344 // Now, we can replace the uses.
2345 Inst->replaceAllUsesWith(New);
2346 }
2347
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002348 /// Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002349 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002350 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002351 for (use_iterator UseIt = OriginalUses.begin(),
2352 EndIt = OriginalUses.end();
2353 UseIt != EndIt; ++UseIt) {
2354 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2355 }
2356 }
2357 };
2358
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002359 /// Remove an instruction from the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002360 class InstructionRemover : public TypePromotionAction {
2361 /// Original position of the instruction.
2362 InsertionHandler Inserter;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002363
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002364 /// Helper structure to hide all the link to the instruction. In other
2365 /// words, this helps to do as if the instruction was removed.
2366 OperandsHider Hider;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002367
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002368 /// Keep track of the uses replaced, if any.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002369 UsesReplacer *Replacer = nullptr;
2370
Jun Bum Limdee55652017-04-03 19:20:07 +00002371 /// Keep track of instructions removed.
2372 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002373
2374 public:
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002375 /// Remove all reference of \p Inst and optionally replace all its
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002376 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002377 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002378 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002379 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2380 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002381 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Eugene Zelenko900b6332017-08-29 22:32:07 +00002382 RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002383 if (New)
2384 Replacer = new UsesReplacer(Inst, New);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002385 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002386 RemovedInsts.insert(Inst);
2387 /// The instructions removed here will be freed after completing
2388 /// optimizeBlock() for all blocks as we need to keep track of the
2389 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002390 Inst->removeFromParent();
2391 }
2392
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002393 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002394
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002395 /// Resurrect the instruction and reassign it to the proper uses if
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002396 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002397 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002398 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002399 Inserter.insert(Inst);
2400 if (Replacer)
2401 Replacer->undo();
2402 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002403 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002404 }
2405 };
2406
2407public:
2408 /// Restoration point.
2409 /// The restoration point is a pointer to an action instead of an iterator
2410 /// because the iterator may be invalidated but not the pointer.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002411 using ConstRestorationPt = const TypePromotionAction *;
Jun Bum Limdee55652017-04-03 19:20:07 +00002412
2413 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2414 : RemovedInsts(RemovedInsts) {}
2415
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002416 /// Advocate every changes made in that transaction.
2417 void commit();
Eugene Zelenko900b6332017-08-29 22:32:07 +00002418
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002419 /// Undo all the changes made after the given point.
2420 void rollback(ConstRestorationPt Point);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002421
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002422 /// Get the current restoration point.
2423 ConstRestorationPt getRestorationPoint() const;
2424
2425 /// \name API for IR modification with state keeping to support rollback.
2426 /// @{
2427 /// Same as Instruction::setOperand.
2428 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002429
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002430 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002431 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002432
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002433 /// Same as Value::replaceAllUsesWith.
2434 void replaceAllUsesWith(Instruction *Inst, Value *New);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002435
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002436 /// Same as Value::mutateType.
2437 void mutateType(Instruction *Inst, Type *NewTy);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002438
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002439 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002440 Value *createTrunc(Instruction *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002441
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002442 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002443 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002444
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002445 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002446 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002447
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002448 /// Same as Instruction::moveBefore.
2449 void moveBefore(Instruction *Inst, Instruction *Before);
2450 /// @}
2451
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002452private:
2453 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002454 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002455
2456 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2457
Jun Bum Limdee55652017-04-03 19:20:07 +00002458 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002459};
2460
Eugene Zelenko900b6332017-08-29 22:32:07 +00002461} // end anonymous namespace
2462
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002463void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2464 Value *NewVal) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002465 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2466 Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002467}
2468
2469void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2470 Value *NewVal) {
2471 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002472 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2473 Inst, RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002474}
2475
2476void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2477 Value *New) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002478 Actions.push_back(
2479 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002480}
2481
2482void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002483 Actions.push_back(
2484 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002485}
2486
Quentin Colombetac55b152014-09-16 22:36:07 +00002487Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2488 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002489 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002490 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002491 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002492 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002493}
2494
Quentin Colombetac55b152014-09-16 22:36:07 +00002495Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2496 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002497 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002498 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002499 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002500 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002501}
2502
Quentin Colombetac55b152014-09-16 22:36:07 +00002503Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2504 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002505 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002506 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002507 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002508 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002509}
2510
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002511void TypePromotionTransaction::moveBefore(Instruction *Inst,
2512 Instruction *Before) {
2513 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002514 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2515 Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002516}
2517
2518TypePromotionTransaction::ConstRestorationPt
2519TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002520 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002521}
2522
2523void TypePromotionTransaction::commit() {
2524 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002525 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002526 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002527 Actions.clear();
2528}
2529
2530void TypePromotionTransaction::rollback(
2531 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002532 while (!Actions.empty() && Point != Actions.back().get()) {
2533 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002534 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002535 }
2536}
2537
Eugene Zelenko900b6332017-08-29 22:32:07 +00002538namespace {
2539
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002540/// A helper class for matching addressing modes.
Chandler Carruthc8925912013-01-05 02:09:22 +00002541///
2542/// This encapsulates the logic for matching the target-legal addressing modes.
2543class AddressingModeMatcher {
2544 SmallVectorImpl<Instruction*> &AddrModeInsts;
2545 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002546 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002547 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002548
2549 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2550 /// the memory instruction that we're computing this address for.
2551 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002552 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002553 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002554
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002555 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002556 /// part of the return value of this addressing mode matching stuff.
2557 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002558
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002559 /// The instructions inserted by other CodeGenPrepare optimizations.
2560 const SetOfInstrs &InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002561
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002562 /// A map from the instructions to their type before promotion.
2563 InstrToOrigTy &PromotedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002564
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002565 /// The ongoing transaction where every action should be registered.
2566 TypePromotionTransaction &TPT;
2567
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002568 // A GEP which has too large offset to be folded into the addressing mode.
2569 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
2570
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002571 /// This is set to true when we should not do profitability checks.
2572 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002573 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002574
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002575 AddressingModeMatcher(
2576 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
2577 const TargetRegisterInfo &TRI, Type *AT, unsigned AS, Instruction *MI,
2578 ExtAddrMode &AM, const SetOfInstrs &InsertedInsts,
2579 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
2580 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002581 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002582 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2583 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002584 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002585 IgnoreProfitability = false;
2586 }
Stephen Lin837bba12013-07-15 17:55:02 +00002587
Eugene Zelenko900b6332017-08-29 22:32:07 +00002588public:
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002589 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002590 /// give an access type of AccessTy. This returns a list of involved
2591 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002592 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002593 /// optimizations.
2594 /// \p PromotedInsts maps the instructions to their type before promotion.
2595 /// \p The ongoing transaction where every action should be registered.
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002596 static ExtAddrMode
2597 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
2598 SmallVectorImpl<Instruction *> &AddrModeInsts,
2599 const TargetLowering &TLI, const TargetRegisterInfo &TRI,
2600 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
2601 TypePromotionTransaction &TPT,
2602 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002603 ExtAddrMode Result;
2604
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002605 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002606 MemoryInst, Result, InsertedInsts,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002607 PromotedInsts, TPT, LargeOffsetGEP)
2608 .matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002609 (void)Success; assert(Success && "Couldn't select *anything*?");
2610 return Result;
2611 }
Eugene Zelenko900b6332017-08-29 22:32:07 +00002612
Chandler Carruthc8925912013-01-05 02:09:22 +00002613private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002614 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
Fangrui Songcb0bab82018-07-16 18:51:40 +00002615 bool matchAddr(Value *Addr, unsigned Depth);
2616 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002617 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002618 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002619 ExtAddrMode &AMBefore,
2620 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002621 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2622 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002623 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002624};
2625
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002626/// Keep track of simplification of Phi nodes.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002627/// Accept the set of all phi nodes and erase phi node from this set
2628/// if it is simplified.
2629class SimplificationTracker {
2630 DenseMap<Value *, Value *> Storage;
2631 const SimplifyQuery &SQ;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002632 // Tracks newly created Phi nodes. We use a SetVector to get deterministic
2633 // order when iterating over the set in MatchPhiSet.
2634 SmallSetVector<PHINode *, 32> AllPhiNodes;
2635 // Tracks newly created Select nodes.
2636 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002637
2638public:
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002639 SimplificationTracker(const SimplifyQuery &sq)
2640 : SQ(sq) {}
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002641
2642 Value *Get(Value *V) {
2643 do {
2644 auto SV = Storage.find(V);
2645 if (SV == Storage.end())
2646 return V;
2647 V = SV->second;
2648 } while (true);
2649 }
2650
2651 Value *Simplify(Value *Val) {
2652 SmallVector<Value *, 32> WorkList;
2653 SmallPtrSet<Value *, 32> Visited;
2654 WorkList.push_back(Val);
2655 while (!WorkList.empty()) {
2656 auto P = WorkList.pop_back_val();
2657 if (!Visited.insert(P).second)
2658 continue;
2659 if (auto *PI = dyn_cast<Instruction>(P))
2660 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
2661 for (auto *U : PI->users())
2662 WorkList.push_back(cast<Value>(U));
2663 Put(PI, V);
2664 PI->replaceAllUsesWith(V);
2665 if (auto *PHI = dyn_cast<PHINode>(PI))
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002666 AllPhiNodes.remove(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002667 if (auto *Select = dyn_cast<SelectInst>(PI))
2668 AllSelectNodes.erase(Select);
2669 PI->eraseFromParent();
2670 }
2671 }
2672 return Get(Val);
2673 }
2674
2675 void Put(Value *From, Value *To) {
2676 Storage.insert({ From, To });
2677 }
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002678
2679 void ReplacePhi(PHINode *From, PHINode *To) {
2680 Value* OldReplacement = Get(From);
2681 while (OldReplacement != From) {
2682 From = To;
2683 To = dyn_cast<PHINode>(OldReplacement);
2684 OldReplacement = Get(From);
2685 }
2686 assert(Get(To) == To && "Replacement PHI node is already replaced.");
2687 Put(From, To);
2688 From->replaceAllUsesWith(To);
2689 AllPhiNodes.remove(From);
2690 From->eraseFromParent();
2691 }
2692
2693 SmallSetVector<PHINode *, 32>& newPhiNodes() { return AllPhiNodes; }
2694
2695 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
2696
2697 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
2698
2699 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
2700
2701 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
2702
2703 void destroyNewNodes(Type *CommonType) {
2704 // For safe erasing, replace the uses with dummy value first.
2705 auto Dummy = UndefValue::get(CommonType);
2706 for (auto I : AllPhiNodes) {
2707 I->replaceAllUsesWith(Dummy);
2708 I->eraseFromParent();
2709 }
2710 AllPhiNodes.clear();
2711 for (auto I : AllSelectNodes) {
2712 I->replaceAllUsesWith(Dummy);
2713 I->eraseFromParent();
2714 }
2715 AllSelectNodes.clear();
2716 }
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002717};
2718
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002719/// A helper class for combining addressing modes.
John Brawn736bf002017-10-03 13:08:22 +00002720class AddressingModeCombiner {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002721 typedef std::pair<Value *, BasicBlock *> ValueInBB;
2722 typedef DenseMap<ValueInBB, Value *> FoldAddrToValueMapping;
2723 typedef std::pair<PHINode *, PHINode *> PHIPair;
2724
John Brawn736bf002017-10-03 13:08:22 +00002725private:
2726 /// The addressing modes we've collected.
2727 SmallVector<ExtAddrMode, 16> AddrModes;
2728
2729 /// The field in which the AddrModes differ, when we have more than one.
2730 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
2731
2732 /// Are the AddrModes that we have all just equal to their original values?
2733 bool AllAddrModesTrivial = true;
2734
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002735 /// Common Type for all different fields in addressing modes.
2736 Type *CommonType;
2737
2738 /// SimplifyQuery for simplifyInstruction utility.
2739 const SimplifyQuery &SQ;
2740
2741 /// Original Address.
2742 ValueInBB Original;
2743
John Brawn736bf002017-10-03 13:08:22 +00002744public:
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002745 AddressingModeCombiner(const SimplifyQuery &_SQ, ValueInBB OriginalValue)
2746 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
2747
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002748 /// Get the combined AddrMode
John Brawn736bf002017-10-03 13:08:22 +00002749 const ExtAddrMode &getAddrMode() const {
2750 return AddrModes[0];
2751 }
2752
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002753 /// Add a new AddrMode if it's compatible with the AddrModes we already
John Brawn736bf002017-10-03 13:08:22 +00002754 /// have.
2755 /// \return True iff we succeeded in doing so.
2756 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
2757 // Take note of if we have any non-trivial AddrModes, as we need to detect
2758 // when all AddrModes are trivial as then we would introduce a phi or select
2759 // which just duplicates what's already there.
2760 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
2761
2762 // If this is the first addrmode then everything is fine.
2763 if (AddrModes.empty()) {
2764 AddrModes.emplace_back(NewAddrMode);
2765 return true;
2766 }
2767
2768 // Figure out how different this is from the other address modes, which we
2769 // can do just by comparing against the first one given that we only care
2770 // about the cumulative difference.
2771 ExtAddrMode::FieldName ThisDifferentField =
2772 AddrModes[0].compare(NewAddrMode);
2773 if (DifferentField == ExtAddrMode::NoField)
2774 DifferentField = ThisDifferentField;
2775 else if (DifferentField != ThisDifferentField)
2776 DifferentField = ExtAddrMode::MultipleFields;
2777
Serguei Katkov17e57942018-01-23 12:07:49 +00002778 // If NewAddrMode differs in more than one dimension we cannot handle it.
2779 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
2780
2781 // If Scale Field is different then we reject.
2782 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
2783
Serguei Katkov4d1dd6b2018-01-09 04:37:06 +00002784 // We also must reject the case when base offset is different and
2785 // scale reg is not null, we cannot handle this case due to merge of
2786 // different offsets will be used as ScaleReg.
Serguei Katkov17e57942018-01-23 12:07:49 +00002787 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
2788 !NewAddrMode.ScaledReg);
John Brawn736bf002017-10-03 13:08:22 +00002789
Serguei Katkov17e57942018-01-23 12:07:49 +00002790 // We also must reject the case when GV is different and BaseReg installed
2791 // due to we want to use base reg as a merge of GV values.
2792 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
2793 !NewAddrMode.HasBaseReg);
2794
2795 // Even if NewAddMode is the same we still need to collect it due to
2796 // original value is different. And later we will need all original values
2797 // as anchors during finding the common Phi node.
2798 if (CanHandle)
2799 AddrModes.emplace_back(NewAddrMode);
2800 else
2801 AddrModes.clear();
2802
2803 return CanHandle;
John Brawn736bf002017-10-03 13:08:22 +00002804 }
2805
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002806 /// Combine the addressing modes we've collected into a single
John Brawn736bf002017-10-03 13:08:22 +00002807 /// addressing mode.
2808 /// \return True iff we successfully combined them or we only had one so
2809 /// didn't need to combine them anyway.
2810 bool combineAddrModes() {
2811 // If we have no AddrModes then they can't be combined.
2812 if (AddrModes.size() == 0)
2813 return false;
2814
2815 // A single AddrMode can trivially be combined.
Serguei Katkov505359f2017-11-20 05:42:36 +00002816 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
John Brawn736bf002017-10-03 13:08:22 +00002817 return true;
2818
2819 // If the AddrModes we collected are all just equal to the value they are
2820 // derived from then combining them wouldn't do anything useful.
2821 if (AllAddrModesTrivial)
2822 return false;
2823
John Brawn70cdb5b2017-11-24 14:10:45 +00002824 if (!addrModeCombiningAllowed())
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002825 return false;
2826
2827 // Build a map between <original value, basic block where we saw it> to
2828 // value of base register.
Serguei Katkov50364592017-11-29 05:51:26 +00002829 // Bail out if there is no common type.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002830 FoldAddrToValueMapping Map;
Serguei Katkov50364592017-11-29 05:51:26 +00002831 if (!initializeMap(Map))
2832 return false;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002833
2834 Value *CommonValue = findCommon(Map);
2835 if (CommonValue)
John Brawn70cdb5b2017-11-24 14:10:45 +00002836 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002837 return CommonValue != nullptr;
2838 }
2839
2840private:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002841 /// Initialize Map with anchor values. For address seen in some BB
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002842 /// we set the value of different field saw in this address.
2843 /// If address is not an instruction than basic block is set to null.
2844 /// At the same time we find a common type for different field we will
2845 /// use to create new Phi/Select nodes. Keep it in CommonType field.
Serguei Katkov50364592017-11-29 05:51:26 +00002846 /// Return false if there is no common type found.
2847 bool initializeMap(FoldAddrToValueMapping &Map) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002848 // Keep track of keys where the value is null. We will need to replace it
2849 // with constant null when we know the common type.
2850 SmallVector<ValueInBB, 2> NullValue;
John Brawn70cdb5b2017-11-24 14:10:45 +00002851 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002852 for (auto &AM : AddrModes) {
2853 BasicBlock *BB = nullptr;
2854 if (Instruction *I = dyn_cast<Instruction>(AM.OriginalValue))
2855 BB = I->getParent();
2856
John Brawn70cdb5b2017-11-24 14:10:45 +00002857 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002858 if (DV) {
Serguei Katkov50364592017-11-29 05:51:26 +00002859 auto *Type = DV->getType();
2860 if (CommonType && CommonType != Type)
2861 return false;
2862 CommonType = Type;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002863 Map[{ AM.OriginalValue, BB }] = DV;
2864 } else {
2865 NullValue.push_back({ AM.OriginalValue, BB });
2866 }
2867 }
2868 assert(CommonType && "At least one non-null value must be!");
2869 for (auto VIBB : NullValue)
2870 Map[VIBB] = Constant::getNullValue(CommonType);
Serguei Katkov50364592017-11-29 05:51:26 +00002871 return true;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002872 }
2873
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002874 /// We have mapping between value A and basic block where value A
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002875 /// seen to other value B where B was a field in addressing mode represented
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002876 /// by A. Also we have an original value C representing an address in some
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002877 /// basic block. Traversing from C through phi and selects we ended up with
2878 /// A's in a map. This utility function tries to find a value V which is a
2879 /// field in addressing mode C and traversing through phi nodes and selects
2880 /// we will end up in corresponded values B in a map.
2881 /// The utility will create a new Phi/Selects if needed.
2882 // The simple example looks as follows:
2883 // BB1:
2884 // p1 = b1 + 40
2885 // br cond BB2, BB3
2886 // BB2:
2887 // p2 = b2 + 40
2888 // br BB3
2889 // BB3:
2890 // p = phi [p1, BB1], [p2, BB2]
2891 // v = load p
2892 // Map is
2893 // <p1, BB1> -> b1
2894 // <p2, BB2> -> b2
2895 // Request is
2896 // <p, BB3> -> ?
2897 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3
2898 Value *findCommon(FoldAddrToValueMapping &Map) {
Eric Christopherd72f78e2018-01-09 23:25:38 +00002899 // Tracks the simplification of newly created phi nodes. The reason we use
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002900 // this mapping is because we will add new created Phi nodes in AddrToBase.
2901 // Simplification of Phi nodes is recursive, so some Phi node may
2902 // be simplified after we added it to AddrToBase.
2903 // Using this mapping we can find the current value in AddrToBase.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002904 SimplificationTracker ST(SQ);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002905
2906 // First step, DFS to create PHI nodes for all intermediate blocks.
2907 // Also fill traverse order for the second step.
2908 SmallVector<ValueInBB, 32> TraverseOrder;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002909 InsertPlaceholders(Map, TraverseOrder, ST);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002910
2911 // Second Step, fill new nodes by merged values and simplify if possible.
2912 FillPlaceholders(Map, TraverseOrder, ST);
2913
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002914 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
2915 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002916 return nullptr;
2917 }
2918
2919 // Now we'd like to match New Phi nodes to existed ones.
2920 unsigned PhiNotMatchedCount = 0;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002921 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
2922 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002923 return nullptr;
2924 }
2925
2926 auto *Result = ST.Get(Map.find(Original)->second);
2927 if (Result) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002928 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
2929 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002930 }
2931 return Result;
2932 }
2933
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002934 /// Try to match PHI node to Candidate.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002935 /// Matcher tracks the matched Phi nodes.
2936 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002937 SmallSetVector<PHIPair, 8> &Matcher,
2938 SmallSetVector<PHINode *, 32> &PhiNodesToMatch) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002939 SmallVector<PHIPair, 8> WorkList;
2940 Matcher.insert({ PHI, Candidate });
2941 WorkList.push_back({ PHI, Candidate });
2942 SmallSet<PHIPair, 8> Visited;
2943 while (!WorkList.empty()) {
2944 auto Item = WorkList.pop_back_val();
2945 if (!Visited.insert(Item).second)
2946 continue;
2947 // We iterate over all incoming values to Phi to compare them.
2948 // If values are different and both of them Phi and the first one is a
2949 // Phi we added (subject to match) and both of them is in the same basic
2950 // block then we can match our pair if values match. So we state that
2951 // these values match and add it to work list to verify that.
2952 for (auto B : Item.first->blocks()) {
2953 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
2954 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
2955 if (FirstValue == SecondValue)
2956 continue;
2957
2958 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
2959 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
2960
2961 // One of them is not Phi or
2962 // The first one is not Phi node from the set we'd like to match or
2963 // Phi nodes from different basic blocks then
2964 // we will not be able to match.
2965 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
2966 FirstPhi->getParent() != SecondPhi->getParent())
2967 return false;
2968
2969 // If we already matched them then continue.
2970 if (Matcher.count({ FirstPhi, SecondPhi }))
2971 continue;
2972 // So the values are different and does not match. So we need them to
2973 // match.
2974 Matcher.insert({ FirstPhi, SecondPhi });
2975 // But me must check it.
2976 WorkList.push_back({ FirstPhi, SecondPhi });
2977 }
2978 }
2979 return true;
2980 }
2981
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002982 /// For the given set of PHI nodes (in the SimplificationTracker) try
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002983 /// to find their equivalents.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002984 /// Returns false if this matching fails and creation of new Phi is disabled.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002985 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002986 unsigned &PhiNotMatchedCount) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002987 // Use a SetVector for Matched to make sure we do replacements (ReplacePhi)
2988 // in a deterministic order below.
2989 SmallSetVector<PHIPair, 8> Matched;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002990 SmallPtrSet<PHINode *, 8> WillNotMatch;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002991 SmallSetVector<PHINode *, 32> &PhiNodesToMatch = ST.newPhiNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002992 while (PhiNodesToMatch.size()) {
2993 PHINode *PHI = *PhiNodesToMatch.begin();
2994
2995 // Add us, if no Phi nodes in the basic block we do not match.
2996 WillNotMatch.clear();
2997 WillNotMatch.insert(PHI);
2998
2999 // Traverse all Phis until we found equivalent or fail to do that.
3000 bool IsMatched = false;
3001 for (auto &P : PHI->getParent()->phis()) {
3002 if (&P == PHI)
3003 continue;
3004 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3005 break;
3006 // If it does not match, collect all Phi nodes from matcher.
3007 // if we end up with no match, them all these Phi nodes will not match
3008 // later.
3009 for (auto M : Matched)
3010 WillNotMatch.insert(M.first);
3011 Matched.clear();
3012 }
3013 if (IsMatched) {
Serguei Katkova20e05b2018-03-12 03:50:07 +00003014 // Replace all matched values and erase them.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003015 for (auto MV : Matched)
3016 ST.ReplacePhi(MV.first, MV.second);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003017 Matched.clear();
3018 continue;
3019 }
3020 // If we are not allowed to create new nodes then bail out.
3021 if (!AllowNewPhiNodes)
3022 return false;
3023 // Just remove all seen values in matcher. They will not match anything.
3024 PhiNotMatchedCount += WillNotMatch.size();
3025 for (auto *P : WillNotMatch)
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003026 PhiNodesToMatch.remove(P);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003027 }
3028 return true;
3029 }
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003030 /// Fill the placeholder with values from predecessors and simplify it.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003031 void FillPlaceholders(FoldAddrToValueMapping &Map,
3032 SmallVectorImpl<ValueInBB> &TraverseOrder,
3033 SimplificationTracker &ST) {
3034 while (!TraverseOrder.empty()) {
3035 auto Current = TraverseOrder.pop_back_val();
3036 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
3037 Value *CurrentValue = Current.first;
3038 BasicBlock *CurrentBlock = Current.second;
3039 Value *V = Map[Current];
3040
3041 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3042 // CurrentValue also must be Select.
3043 auto *CurrentSelect = cast<SelectInst>(CurrentValue);
3044 auto *TrueValue = CurrentSelect->getTrueValue();
3045 ValueInBB TrueItem = { TrueValue, isa<Instruction>(TrueValue)
3046 ? CurrentBlock
3047 : nullptr };
3048 assert(Map.find(TrueItem) != Map.end() && "No True Value!");
Serguei Katkovb0b67a82017-12-18 04:25:07 +00003049 Select->setTrueValue(ST.Get(Map[TrueItem]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003050 auto *FalseValue = CurrentSelect->getFalseValue();
3051 ValueInBB FalseItem = { FalseValue, isa<Instruction>(FalseValue)
3052 ? CurrentBlock
3053 : nullptr };
3054 assert(Map.find(FalseItem) != Map.end() && "No False Value!");
Serguei Katkovb0b67a82017-12-18 04:25:07 +00003055 Select->setFalseValue(ST.Get(Map[FalseItem]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003056 } else {
3057 // Must be a Phi node then.
3058 PHINode *PHI = cast<PHINode>(V);
3059 // Fill the Phi node with values from predecessors.
3060 bool IsDefinedInThisBB =
3061 cast<Instruction>(CurrentValue)->getParent() == CurrentBlock;
3062 auto *CurrentPhi = dyn_cast<PHINode>(CurrentValue);
3063 for (auto B : predecessors(CurrentBlock)) {
3064 Value *PV = IsDefinedInThisBB
3065 ? CurrentPhi->getIncomingValueForBlock(B)
3066 : CurrentValue;
3067 ValueInBB item = { PV, isa<Instruction>(PV) ? B : nullptr };
3068 assert(Map.find(item) != Map.end() && "No predecessor Value!");
3069 PHI->addIncoming(ST.Get(Map[item]), B);
3070 }
3071 }
3072 // Simplify if possible.
3073 Map[Current] = ST.Simplify(V);
3074 }
3075 }
3076
3077 /// Starting from value recursively iterates over predecessors up to known
3078 /// ending values represented in a map. For each traversed block inserts
3079 /// a placeholder Phi or Select.
3080 /// Reports all new created Phi/Select nodes by adding them to set.
3081 /// Also reports and order in what basic blocks have been traversed.
3082 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3083 SmallVectorImpl<ValueInBB> &TraverseOrder,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003084 SimplificationTracker &ST) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003085 SmallVector<ValueInBB, 32> Worklist;
3086 assert((isa<PHINode>(Original.first) || isa<SelectInst>(Original.first)) &&
3087 "Address must be a Phi or Select node");
3088 auto *Dummy = UndefValue::get(CommonType);
3089 Worklist.push_back(Original);
3090 while (!Worklist.empty()) {
3091 auto Current = Worklist.pop_back_val();
3092 // If value is not an instruction it is something global, constant,
3093 // parameter and we can say that this value is observable in any block.
3094 // Set block to null to denote it.
3095 // Also please take into account that it is how we build anchors.
3096 if (!isa<Instruction>(Current.first))
3097 Current.second = nullptr;
3098 // if it is already visited or it is an ending value then skip it.
3099 if (Map.find(Current) != Map.end())
3100 continue;
3101 TraverseOrder.push_back(Current);
3102
3103 Value *CurrentValue = Current.first;
3104 BasicBlock *CurrentBlock = Current.second;
3105 // CurrentValue must be a Phi node or select. All others must be covered
3106 // by anchors.
3107 Instruction *CurrentI = cast<Instruction>(CurrentValue);
3108 bool IsDefinedInThisBB = CurrentI->getParent() == CurrentBlock;
3109
Vedant Kumare0b5f862018-05-10 23:01:54 +00003110 unsigned PredCount = pred_size(CurrentBlock);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003111 // if Current Value is not defined in this basic block we are interested
3112 // in values in predecessors.
3113 if (!IsDefinedInThisBB) {
3114 assert(PredCount && "Unreachable block?!");
3115 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3116 &CurrentBlock->front());
3117 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003118 ST.insertNewPhi(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003119 // Add all predecessors in work list.
3120 for (auto B : predecessors(CurrentBlock))
3121 Worklist.push_back({ CurrentValue, B });
3122 continue;
3123 }
3124 // Value is defined in this basic block.
3125 if (SelectInst *OrigSelect = dyn_cast<SelectInst>(CurrentI)) {
3126 // Is it OK to get metadata from OrigSelect?!
3127 // Create a Select placeholder with dummy value.
3128 SelectInst *Select =
3129 SelectInst::Create(OrigSelect->getCondition(), Dummy, Dummy,
3130 OrigSelect->getName(), OrigSelect, OrigSelect);
3131 Map[Current] = Select;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003132 ST.insertNewSelect(Select);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003133 // We are interested in True and False value in this basic block.
3134 Worklist.push_back({ OrigSelect->getTrueValue(), CurrentBlock });
3135 Worklist.push_back({ OrigSelect->getFalseValue(), CurrentBlock });
3136 } else {
3137 // It must be a Phi node then.
3138 auto *CurrentPhi = cast<PHINode>(CurrentI);
3139 // Create new Phi node for merge of bases.
3140 assert(PredCount && "Unreachable block?!");
3141 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3142 &CurrentBlock->front());
3143 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003144 ST.insertNewPhi(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003145
3146 // Add all predecessors in work list.
3147 for (auto B : predecessors(CurrentBlock))
3148 Worklist.push_back({ CurrentPhi->getIncomingValueForBlock(B), B });
3149 }
3150 }
John Brawn736bf002017-10-03 13:08:22 +00003151 }
John Brawn70cdb5b2017-11-24 14:10:45 +00003152
3153 bool addrModeCombiningAllowed() {
3154 if (DisableComplexAddrModes)
3155 return false;
3156 switch (DifferentField) {
3157 default:
3158 return false;
3159 case ExtAddrMode::BaseRegField:
3160 return AddrSinkCombineBaseReg;
3161 case ExtAddrMode::BaseGVField:
3162 return AddrSinkCombineBaseGV;
3163 case ExtAddrMode::BaseOffsField:
3164 return AddrSinkCombineBaseOffs;
3165 case ExtAddrMode::ScaledRegField:
3166 return AddrSinkCombineScaledReg;
3167 }
3168 }
John Brawn736bf002017-10-03 13:08:22 +00003169};
Eugene Zelenko900b6332017-08-29 22:32:07 +00003170} // end anonymous namespace
3171
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003172/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003173/// Return true and update AddrMode if this addr mode is legal for the target,
3174/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003175bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003176 unsigned Depth) {
3177 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3178 // mode. Just process that directly.
3179 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003180 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003181
Chandler Carruthc8925912013-01-05 02:09:22 +00003182 // If the scale is 0, it takes nothing to add this.
3183 if (Scale == 0)
3184 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003185
Chandler Carruthc8925912013-01-05 02:09:22 +00003186 // If we already have a scale of this value, we can add to it, otherwise, we
3187 // need an available scale field.
3188 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3189 return false;
3190
3191 ExtAddrMode TestAddrMode = AddrMode;
3192
3193 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3194 // [A+B + A*7] -> [B+A*8].
3195 TestAddrMode.Scale += Scale;
3196 TestAddrMode.ScaledReg = ScaleReg;
3197
3198 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003199 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003200 return false;
3201
3202 // It was legal, so commit it.
3203 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003204
Chandler Carruthc8925912013-01-05 02:09:22 +00003205 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3206 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3207 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003208 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003209 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3210 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3211 TestAddrMode.ScaledReg = AddLHS;
3212 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003213
Chandler Carruthc8925912013-01-05 02:09:22 +00003214 // If this addressing mode is legal, commit it and remember that we folded
3215 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003216 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003217 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3218 AddrMode = TestAddrMode;
3219 return true;
3220 }
3221 }
3222
3223 // Otherwise, not (x+c)*scale, just return what we have.
3224 return true;
3225}
3226
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003227/// This is a little filter, which returns true if an addressing computation
3228/// involving I might be folded into a load/store accessing it.
3229/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003230/// the set of instructions that MatchOperationAddr can.
3231static bool MightBeFoldableInst(Instruction *I) {
3232 switch (I->getOpcode()) {
3233 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003234 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003235 // Don't touch identity bitcasts.
3236 if (I->getType() == I->getOperand(0)->getType())
3237 return false;
Vedant Kumarb3091da2018-07-06 20:17:42 +00003238 return I->getType()->isIntOrPtrTy();
Chandler Carruthc8925912013-01-05 02:09:22 +00003239 case Instruction::PtrToInt:
3240 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3241 return true;
3242 case Instruction::IntToPtr:
3243 // We know the input is intptr_t, so this is foldable.
3244 return true;
3245 case Instruction::Add:
3246 return true;
3247 case Instruction::Mul:
3248 case Instruction::Shl:
3249 // Can only handle X*C and X << C.
3250 return isa<ConstantInt>(I->getOperand(1));
3251 case Instruction::GetElementPtr:
3252 return true;
3253 default:
3254 return false;
3255 }
3256}
3257
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003258/// Check whether or not \p Val is a legal instruction for \p TLI.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003259/// \note \p Val is assumed to be the product of some type promotion.
3260/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3261/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003262static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3263 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003264 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3265 if (!PromotedInst)
3266 return false;
3267 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3268 // If the ISDOpcode is undefined, it was undefined before the promotion.
3269 if (!ISDOpcode)
3270 return true;
3271 // Otherwise, check if the promoted instruction is legal or not.
3272 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003273 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003274}
3275
Eugene Zelenko900b6332017-08-29 22:32:07 +00003276namespace {
3277
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003278/// Hepler class to perform type promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003279class TypePromotionHelper {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003280 /// Utility function to check whether or not a sign or zero extension
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003281 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3282 /// either using the operands of \p Inst or promoting \p Inst.
3283 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003284 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003285 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003286 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003287 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003288 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003289 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003290 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003291 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3292 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003293
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003294 /// Utility function to determine if \p OpIdx should be promoted when
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003295 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003296 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003297 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003298 }
3299
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003300 /// Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003301 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003302 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003303 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003304 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003305 /// Newly added extensions are inserted in \p Exts.
3306 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003307 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003308 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003309 static Value *promoteOperandForTruncAndAnyExt(
3310 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003311 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003312 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003313 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003314
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003315 /// Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003316 /// operand is promotable and is not a supported trunc or sext.
3317 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003318 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003319 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003320 /// Newly added extensions are inserted in \p Exts.
3321 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003322 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003323 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003324 static Value *promoteOperandForOther(Instruction *Ext,
3325 TypePromotionTransaction &TPT,
3326 InstrToOrigTy &PromotedInsts,
3327 unsigned &CreatedInstsCost,
3328 SmallVectorImpl<Instruction *> *Exts,
3329 SmallVectorImpl<Instruction *> *Truncs,
3330 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003331
3332 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003333 static Value *signExtendOperandForOther(
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, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003340 }
3341
3342 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003343 static Value *zeroExtendOperandForOther(
3344 Instruction *Ext, TypePromotionTransaction &TPT,
3345 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3346 SmallVectorImpl<Instruction *> *Exts,
3347 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3348 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3349 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003350 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003351
3352public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003353 /// Type for the utility function that promotes the operand of Ext.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003354 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3355 InstrToOrigTy &PromotedInsts,
3356 unsigned &CreatedInstsCost,
3357 SmallVectorImpl<Instruction *> *Exts,
3358 SmallVectorImpl<Instruction *> *Truncs,
3359 const TargetLowering &TLI);
3360
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003361 /// Given a sign/zero extend instruction \p Ext, return the appropriate
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003362 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003363 /// \return NULL if no promotable action is possible with the current
3364 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003365 /// \p InsertedInsts keeps track of all the instructions inserted by the
3366 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003367 /// because we do not want to promote these instructions as CodeGenPrepare
3368 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3369 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003370 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003371 const TargetLowering &TLI,
3372 const InstrToOrigTy &PromotedInsts);
3373};
3374
Eugene Zelenko900b6332017-08-29 22:32:07 +00003375} // end anonymous namespace
3376
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003377bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003378 Type *ConsideredExtType,
3379 const InstrToOrigTy &PromotedInsts,
3380 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003381 // The promotion helper does not know how to deal with vector types yet.
3382 // To be able to fix that, we would need to fix the places where we
3383 // statically extend, e.g., constants and such.
3384 if (Inst->getType()->isVectorTy())
3385 return false;
3386
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003387 // We can always get through zext.
3388 if (isa<ZExtInst>(Inst))
3389 return true;
3390
3391 // sext(sext) is ok too.
3392 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003393 return true;
3394
3395 // We can get through binary operator, if it is legal. In other words, the
3396 // binary operator must have a nuw or nsw flag.
3397 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3398 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003399 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3400 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003401 return true;
3402
Guozhi Weic4c6b542018-06-05 21:03:52 +00003403 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
3404 if ((Inst->getOpcode() == Instruction::And ||
3405 Inst->getOpcode() == Instruction::Or))
3406 return true;
3407
3408 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
3409 if (Inst->getOpcode() == Instruction::Xor) {
3410 const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1));
3411 // Make sure it is not a NOT.
3412 if (Cst && !Cst->getValue().isAllOnesValue())
3413 return true;
3414 }
3415
3416 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
3417 // It may change a poisoned value into a regular value, like
3418 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
3419 // poisoned value regular value
3420 // It should be OK since undef covers valid value.
3421 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
3422 return true;
3423
3424 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
3425 // It may change a poisoned value into a regular value, like
3426 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
3427 // poisoned value regular value
3428 // It should be OK since undef covers valid value.
3429 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
3430 const Instruction *ExtInst =
3431 dyn_cast<const Instruction>(*Inst->user_begin());
3432 if (ExtInst->hasOneUse()) {
3433 const Instruction *AndInst =
3434 dyn_cast<const Instruction>(*ExtInst->user_begin());
3435 if (AndInst && AndInst->getOpcode() == Instruction::And) {
3436 const ConstantInt *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
3437 if (Cst &&
3438 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
3439 return true;
3440 }
3441 }
3442 }
3443
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003444 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003445 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003446 if (!isa<TruncInst>(Inst))
3447 return false;
3448
3449 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003450 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003451 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003452 if (!OpndVal->getType()->isIntegerTy() ||
3453 OpndVal->getType()->getIntegerBitWidth() >
3454 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003455 return false;
3456
3457 // If the operand of the truncate is not an instruction, we will not have
3458 // any information on the dropped bits.
3459 // (Actually we could for constant but it is not worth the extra logic).
3460 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3461 if (!Opnd)
3462 return false;
3463
3464 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003465 // I.e., check that trunc just drops extended bits of the same kind of
3466 // the extension.
3467 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003468 const Type *OpndType;
3469 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003470 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3471 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003472 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3473 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003474 else
3475 return false;
3476
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003477 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003478 return Inst->getType()->getIntegerBitWidth() >=
3479 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003480}
3481
3482TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003483 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003484 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003485 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3486 "Unexpected instruction type");
3487 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3488 Type *ExtTy = Ext->getType();
3489 bool IsSExt = isa<SExtInst>(Ext);
3490 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003491 // get through.
3492 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003493 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003494 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003495
3496 // Do not promote if the operand has been added by codegenprepare.
3497 // Otherwise, it means we are undoing an optimization that is likely to be
3498 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003499 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003500 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003501
3502 // SExt or Trunc instructions.
3503 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003504 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3505 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003506 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003507
3508 // Regular instruction.
3509 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003510 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003511 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003512 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003513}
3514
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003515Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003516 Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003517 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003518 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003519 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003520 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3521 // get through it and this method should not be called.
3522 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003523 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003524 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003525 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003526 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003527 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003528 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003529 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003530 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3531 TPT.replaceAllUsesWith(SExt, ZExt);
3532 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003533 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003534 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003535 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3536 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003537 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3538 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003539 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003540
3541 // Remove dead code.
3542 if (SExtOpnd->use_empty())
3543 TPT.eraseInstruction(SExtOpnd);
3544
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003545 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003546 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003547 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003548 if (ExtInst) {
3549 if (Exts)
3550 Exts->push_back(ExtInst);
3551 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3552 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003553 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003554 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003555
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003556 // At this point we have: ext ty opnd to ty.
3557 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3558 Value *NextVal = ExtInst->getOperand(0);
3559 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003560 return NextVal;
3561}
3562
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003563Value *TypePromotionHelper::promoteOperandForOther(
3564 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003565 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003566 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003567 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3568 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003569 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003570 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003571 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003572 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003573 if (!ExtOpnd->hasOneUse()) {
3574 // ExtOpnd will be promoted.
3575 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003576 // promoted version.
3577 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003578 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003579 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
Quentin Colombetac55b152014-09-16 22:36:07 +00003580 // Insert it just after the definition.
Sanjay Patel674d2c22017-08-29 14:07:48 +00003581 ITrunc->moveAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003582 if (Truncs)
3583 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003584 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003585
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003586 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003587 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003588 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003589 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003590 }
3591
3592 // Get through the Instruction:
3593 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003594 // 2. Replace the uses of Ext by Inst.
3595 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003596
3597 // Remember the original type of the instruction before promotion.
3598 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003599 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3600 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003601 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003602 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003603 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003604 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003605 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003606 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003607
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003608 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003609 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003610 ++OpIdx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003611 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003612 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3613 !shouldExtOperand(ExtOpnd, OpIdx)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003614 LLVM_DEBUG(dbgs() << "No need to propagate\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003615 continue;
3616 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003617 // Check if we can statically extend the operand.
3618 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003619 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003620 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003621 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3622 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3623 : Cst->getValue().zext(BitWidth);
3624 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003625 continue;
3626 }
3627 // UndefValue are typed, so we have to statically sign extend them.
3628 if (isa<UndefValue>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003629 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003630 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003631 continue;
3632 }
3633
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003634 // Otherwise we have to explicitly sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003635 // Check if Ext was reused to extend an operand.
3636 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003637 // If yes, create a new one.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003638 LLVM_DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003639 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3640 : TPT.createZExt(Ext, Opnd, Ext->getType());
3641 if (!isa<Instruction>(ValForExtOpnd)) {
3642 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3643 continue;
3644 }
3645 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003646 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003647 if (Exts)
3648 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003649 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003650
3651 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003652 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3653 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003654 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003655 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003656 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003657 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003658 if (ExtForOpnd == Ext) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003659 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003660 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003661 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003662 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003663}
3664
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003665/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003666/// \p NewCost gives the cost of extension instructions created by the
3667/// promotion.
3668/// \p OldCost gives the cost of extension instructions before the promotion
3669/// plus the number of instructions that have been
3670/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003671/// \p PromotedOperand is the value that has been promoted.
3672/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003673bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003674 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003675 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
3676 << '\n');
Quentin Colombet1b274f92015-03-10 21:48:15 +00003677 // The cost of the new extensions is greater than the cost of the
3678 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003679 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003680 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003681 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003682 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003683 return true;
3684 // The promotion is neutral but it may help folding the sign extension in
3685 // loads for instance.
3686 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003687 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003688}
3689
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003690/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003691/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003692/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003693/// If \p MovedAway is not NULL, it contains the information of whether or
3694/// not AddrInst has to be folded into the addressing mode on success.
3695/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3696/// because it has been moved away.
3697/// Thus AddrInst must not be added in the matched instructions.
3698/// This state can happen when AddrInst is a sext, since it may be moved away.
3699/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3700/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003701bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003702 unsigned Depth,
3703 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003704 // Avoid exponential behavior on extremely deep expression trees.
3705 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003706
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003707 // By default, all matched instructions stay in place.
3708 if (MovedAway)
3709 *MovedAway = false;
3710
Chandler Carruthc8925912013-01-05 02:09:22 +00003711 switch (Opcode) {
3712 case Instruction::PtrToInt:
3713 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003714 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003715 case Instruction::IntToPtr: {
3716 auto AS = AddrInst->getType()->getPointerAddressSpace();
3717 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003718 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003719 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003720 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003721 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003722 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003723 case Instruction::BitCast:
3724 // BitCast is always a noop, and we can handle it as long as it is
3725 // int->int or pointer->pointer (we don't want int<->fp or something).
Vedant Kumarb3091da2018-07-06 20:17:42 +00003726 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
Chandler Carruthc8925912013-01-05 02:09:22 +00003727 // Don't touch identity bitcasts. These were probably put here by LSR,
3728 // and we don't want to mess around with them. Assume it knows what it
3729 // is doing.
3730 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003731 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003732 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003733 case Instruction::AddrSpaceCast: {
3734 unsigned SrcAS
3735 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3736 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3737 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003738 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003739 return false;
3740 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003741 case Instruction::Add: {
3742 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3743 ExtAddrMode BackupAddrMode = AddrMode;
3744 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003745 // Start a transaction at this point.
3746 // The LHS may match but not the RHS.
3747 // Therefore, we need a higher level restoration point to undo partially
3748 // matched operation.
3749 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3750 TPT.getRestorationPoint();
3751
Sanjay Patelfc580a62015-09-21 23:03:16 +00003752 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3753 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003754 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003755
Chandler Carruthc8925912013-01-05 02:09:22 +00003756 // Restore the old addr mode info.
3757 AddrMode = BackupAddrMode;
3758 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003759 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003760
Chandler Carruthc8925912013-01-05 02:09:22 +00003761 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003762 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3763 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003764 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003765
Chandler Carruthc8925912013-01-05 02:09:22 +00003766 // Otherwise we definitely can't merge the ADD in.
3767 AddrMode = BackupAddrMode;
3768 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003769 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003770 break;
3771 }
3772 //case Instruction::Or:
3773 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3774 //break;
3775 case Instruction::Mul:
3776 case Instruction::Shl: {
3777 // Can only handle X*C and X << C.
3778 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Philip Reames9c3cbee2017-10-30 23:59:51 +00003779 if (!RHS || RHS->getBitWidth() > 64)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003780 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003781 int64_t Scale = RHS->getSExtValue();
3782 if (Opcode == Instruction::Shl)
3783 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003784
Sanjay Patelfc580a62015-09-21 23:03:16 +00003785 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003786 }
3787 case Instruction::GetElementPtr: {
3788 // Scan the GEP. We check it if it contains constant offsets and at most
3789 // one variable offset.
3790 int VariableOperand = -1;
3791 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003792
Chandler Carruthc8925912013-01-05 02:09:22 +00003793 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003794 gep_type_iterator GTI = gep_type_begin(AddrInst);
3795 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003796 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003797 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003798 unsigned Idx =
3799 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3800 ConstantOffset += SL->getElementOffset(Idx);
3801 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003802 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003803 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
Simon Pilgrimee82a792018-08-13 12:10:09 +00003804 const APInt &CVal = CI->getValue();
3805 if (CVal.getMinSignedBits() <= 64) {
3806 ConstantOffset += CVal.getSExtValue() * TypeSize;
3807 continue;
3808 }
3809 }
3810 if (TypeSize) { // Scales of zero don't do anything.
Chandler Carruthc8925912013-01-05 02:09:22 +00003811 // We only allow one variable index at the moment.
3812 if (VariableOperand != -1)
3813 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003814
Chandler Carruthc8925912013-01-05 02:09:22 +00003815 // Remember the variable index.
3816 VariableOperand = i;
3817 VariableScale = TypeSize;
3818 }
3819 }
3820 }
Stephen Lin837bba12013-07-15 17:55:02 +00003821
Chandler Carruthc8925912013-01-05 02:09:22 +00003822 // A common case is for the GEP to only do a constant offset. In this case,
3823 // just add it to the disp field and check validity.
3824 if (VariableOperand == -1) {
3825 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003826 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003827 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003828 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003829 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003830 return true;
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00003831 } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
3832 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
3833 ConstantOffset > 0) {
3834 // Record GEPs with non-zero offsets as candidates for splitting in the
3835 // event that the offset cannot fit into the r+i addressing mode.
3836 // Simple and common case that only one GEP is used in calculating the
3837 // address for the memory access.
3838 Value *Base = AddrInst->getOperand(0);
3839 auto *BaseI = dyn_cast<Instruction>(Base);
3840 auto *GEP = cast<GetElementPtrInst>(AddrInst);
3841 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
3842 (BaseI && !isa<CastInst>(BaseI) &&
3843 !isa<GetElementPtrInst>(BaseI))) {
3844 // If the base is an instruction, make sure the GEP is not in the same
3845 // basic block as the base. If the base is an argument or global
3846 // value, make sure the GEP is not in the entry block. Otherwise,
3847 // instruction selection can undo the split. Also make sure the
3848 // parent block allows inserting non-PHI instructions before the
3849 // terminator.
3850 BasicBlock *Parent =
3851 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
3852 if (GEP->getParent() != Parent && !Parent->getTerminator()->isEHPad())
3853 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
3854 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003855 }
3856 AddrMode.BaseOffs -= ConstantOffset;
3857 return false;
3858 }
3859
3860 // Save the valid addressing mode in case we can't match.
3861 ExtAddrMode BackupAddrMode = AddrMode;
3862 unsigned OldSize = AddrModeInsts.size();
3863
3864 // See if the scale and offset amount is valid for this target.
3865 AddrMode.BaseOffs += ConstantOffset;
3866
3867 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003868 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003869 // If it couldn't be matched, just stuff the value in a register.
3870 if (AddrMode.HasBaseReg) {
3871 AddrMode = BackupAddrMode;
3872 AddrModeInsts.resize(OldSize);
3873 return false;
3874 }
3875 AddrMode.HasBaseReg = true;
3876 AddrMode.BaseReg = AddrInst->getOperand(0);
3877 }
3878
3879 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003880 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003881 Depth)) {
3882 // If it couldn't be matched, try stuffing the base into a register
3883 // instead of matching it, and retrying the match of the scale.
3884 AddrMode = BackupAddrMode;
3885 AddrModeInsts.resize(OldSize);
3886 if (AddrMode.HasBaseReg)
3887 return false;
3888 AddrMode.HasBaseReg = true;
3889 AddrMode.BaseReg = AddrInst->getOperand(0);
3890 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003891 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003892 VariableScale, Depth)) {
3893 // If even that didn't work, bail.
3894 AddrMode = BackupAddrMode;
3895 AddrModeInsts.resize(OldSize);
3896 return false;
3897 }
3898 }
3899
3900 return true;
3901 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003902 case Instruction::SExt:
3903 case Instruction::ZExt: {
3904 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3905 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003906 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003907
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003908 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003909 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003910 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003911 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003912 if (!TPH)
3913 return false;
3914
3915 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3916 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003917 unsigned CreatedInstsCost = 0;
3918 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003919 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003920 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003921 // SExt has been moved away.
3922 // Thus either it will be rematched later in the recursive calls or it is
3923 // gone. Anyway, we must not fold it into the addressing mode at this point.
3924 // E.g.,
3925 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003926 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003927 // addr = gep base, idx
3928 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003929 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003930 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3931 // addr = gep base, op <- match
3932 if (MovedAway)
3933 *MovedAway = true;
3934
3935 assert(PromotedOperand &&
3936 "TypePromotionHelper should have filtered out those cases");
3937
3938 ExtAddrMode BackupAddrMode = AddrMode;
3939 unsigned OldSize = AddrModeInsts.size();
3940
Sanjay Patelfc580a62015-09-21 23:03:16 +00003941 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003942 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003943 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003944 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003945 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003946 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003947 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003948 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003949 AddrMode = BackupAddrMode;
3950 AddrModeInsts.resize(OldSize);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003951 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003952 TPT.rollback(LastKnownGood);
3953 return false;
3954 }
3955 return true;
3956 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003957 }
3958 return false;
3959}
3960
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003961/// If we can, try to add the value of 'Addr' into the current addressing mode.
3962/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3963/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3964/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003965///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003966bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003967 // Start a transaction at this point that we will rollback if the matching
3968 // fails.
3969 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3970 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003971 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3972 // Fold in immediates if legal for the target.
3973 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003974 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003975 return true;
3976 AddrMode.BaseOffs -= CI->getSExtValue();
3977 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3978 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003979 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003980 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003981 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003982 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003983 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003984 }
3985 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3986 ExtAddrMode BackupAddrMode = AddrMode;
3987 unsigned OldSize = AddrModeInsts.size();
3988
3989 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003990 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003991 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003992 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003993 // to check here.
3994 if (MovedAway)
3995 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003996 // Okay, it's possible to fold this. Check to see if it is actually
3997 // *profitable* to do so. We use a simple cost model to avoid increasing
3998 // register pressure too much.
3999 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00004000 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004001 AddrModeInsts.push_back(I);
4002 return true;
4003 }
Stephen Lin837bba12013-07-15 17:55:02 +00004004
Chandler Carruthc8925912013-01-05 02:09:22 +00004005 // It isn't profitable to do this, roll back.
4006 //cerr << "NOT FOLDING: " << *I;
4007 AddrMode = BackupAddrMode;
4008 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004009 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004010 }
4011 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00004012 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00004013 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004014 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004015 } else if (isa<ConstantPointerNull>(Addr)) {
4016 // Null pointer gets folded without affecting the addressing mode.
4017 return true;
4018 }
4019
4020 // Worse case, the target should support [reg] addressing modes. :)
4021 if (!AddrMode.HasBaseReg) {
4022 AddrMode.HasBaseReg = true;
4023 AddrMode.BaseReg = Addr;
4024 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004025 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004026 return true;
4027 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00004028 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004029 }
4030
4031 // If the base register is already taken, see if we can do [r+r].
4032 if (AddrMode.Scale == 0) {
4033 AddrMode.Scale = 1;
4034 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004035 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004036 return true;
4037 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00004038 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004039 }
4040 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004041 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004042 return false;
4043}
4044
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004045/// Check to see if all uses of OpVal by the specified inline asm call are due
4046/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00004047static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004048 const TargetLowering &TLI,
4049 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00004050 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00004051 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004052 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004053 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004054
Chandler Carruthc8925912013-01-05 02:09:22 +00004055 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4056 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00004057
Chandler Carruthc8925912013-01-05 02:09:22 +00004058 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004059 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00004060
4061 // If this asm operand is our Value*, and if it isn't an indirect memory
4062 // operand, we can't fold it!
4063 if (OpInfo.CallOperandVal == OpVal &&
4064 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4065 !OpInfo.isIndirect))
4066 return false;
4067 }
4068
4069 return true;
4070}
4071
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004072// Max number of memory uses to look at before aborting the search to conserve
4073// compile time.
4074static constexpr int MaxMemoryUsesToScan = 20;
4075
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004076/// Recursively walk all the uses of I until we find a memory use.
4077/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00004078/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00004079static bool FindAllMemoryUses(
4080 Instruction *I,
4081 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004082 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4083 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004084 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00004085 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00004086 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004087
Chandler Carruthc8925912013-01-05 02:09:22 +00004088 // If this is an obviously unfoldable instruction, bail out.
4089 if (!MightBeFoldableInst(I))
4090 return true;
4091
Philip Reamesac115ed2016-03-09 23:13:12 +00004092 const bool OptSize = I->getFunction()->optForSize();
4093
Chandler Carruthc8925912013-01-05 02:09:22 +00004094 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004095 for (Use &U : I->uses()) {
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004096 // Conservatively return true if we're seeing a large number or a deep chain
4097 // of users. This avoids excessive compilation times in pathological cases.
4098 if (SeenInsts++ >= MaxMemoryUsesToScan)
4099 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004100
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004101 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthcdf47882014-03-09 03:16:01 +00004102 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4103 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00004104 continue;
4105 }
Stephen Lin837bba12013-07-15 17:55:02 +00004106
Chandler Carruthcdf47882014-03-09 03:16:01 +00004107 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4108 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00004109 if (opNo != StoreInst::getPointerOperandIndex())
4110 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00004111 MemoryUses.push_back(std::make_pair(SI, opNo));
4112 continue;
4113 }
Stephen Lin837bba12013-07-15 17:55:02 +00004114
Matt Arsenault02d915b2017-03-15 22:35:20 +00004115 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4116 unsigned opNo = U.getOperandNo();
4117 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4118 return true; // Storing addr, not into addr.
4119 MemoryUses.push_back(std::make_pair(RMW, opNo));
4120 continue;
4121 }
4122
4123 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4124 unsigned opNo = U.getOperandNo();
4125 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4126 return true; // Storing addr, not into addr.
4127 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4128 continue;
4129 }
4130
Chandler Carruthcdf47882014-03-09 03:16:01 +00004131 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004132 // If this is a cold call, we can sink the addressing calculation into
4133 // the cold path. See optimizeCallInst
4134 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4135 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004136
Chandler Carruthc8925912013-01-05 02:09:22 +00004137 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4138 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004139
Chandler Carruthc8925912013-01-05 02:09:22 +00004140 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004141 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004142 return true;
4143 continue;
4144 }
Stephen Lin837bba12013-07-15 17:55:02 +00004145
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004146 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4147 SeenInsts))
Chandler Carruthc8925912013-01-05 02:09:22 +00004148 return true;
4149 }
4150
4151 return false;
4152}
4153
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004154/// Return true if Val is already known to be live at the use site that we're
4155/// folding it into. If so, there is no cost to include it in the addressing
4156/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4157/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004158bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004159 Value *KnownLive2) {
4160 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004161 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004162 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004163
Chandler Carruthc8925912013-01-05 02:09:22 +00004164 // All values other than instructions and arguments (e.g. constants) are live.
4165 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004166
Chandler Carruthc8925912013-01-05 02:09:22 +00004167 // If Val is a constant sized alloca in the entry block, it is live, this is
4168 // true because it is just a reference to the stack/frame pointer, which is
4169 // live for the whole function.
4170 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4171 if (AI->isStaticAlloca())
4172 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004173
Chandler Carruthc8925912013-01-05 02:09:22 +00004174 // Check to see if this value is already used in the memory instruction's
4175 // block. If so, it's already live into the block at the very least, so we
4176 // can reasonably fold it.
4177 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4178}
4179
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004180/// It is possible for the addressing mode of the machine to fold the specified
4181/// instruction into a load or store that ultimately uses it.
4182/// However, the specified instruction has multiple uses.
4183/// Given this, it may actually increase register pressure to fold it
4184/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004185///
4186/// X = ...
4187/// Y = X+1
4188/// use(Y) -> nonload/store
4189/// Z = Y+1
4190/// load Z
4191///
4192/// In this case, Y has multiple uses, and can be folded into the load of Z
4193/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4194/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4195/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4196/// number of computations either.
4197///
4198/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4199/// X was live across 'load Z' for other reasons, we actually *would* want to
4200/// fold the addressing mode in the Z case. This would make Y die earlier.
4201bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004202isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004203 ExtAddrMode &AMAfter) {
4204 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004205
Chandler Carruthc8925912013-01-05 02:09:22 +00004206 // AMBefore is the addressing mode before this instruction was folded into it,
4207 // and AMAfter is the addressing mode after the instruction was folded. Get
4208 // the set of registers referenced by AMAfter and subtract out those
4209 // referenced by AMBefore: this is the set of values which folding in this
4210 // address extends the lifetime of.
4211 //
4212 // Note that there are only two potential values being referenced here,
4213 // BaseReg and ScaleReg (global addresses are always available, as are any
4214 // folded immediates).
4215 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004216
Chandler Carruthc8925912013-01-05 02:09:22 +00004217 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4218 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004219 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004220 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004221 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004222 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004223
4224 // If folding this instruction (and it's subexprs) didn't extend any live
4225 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004226 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004227 return true;
4228
Philip Reamesac115ed2016-03-09 23:13:12 +00004229 // If all uses of this instruction can have the address mode sunk into them,
4230 // we can remove the addressing mode and effectively trade one live register
4231 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004232 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004233 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4234 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004235 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004236 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004237
Chandler Carruthc8925912013-01-05 02:09:22 +00004238 // Now that we know that all uses of this instruction are part of a chain of
4239 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004240 // into a memory use, loop over each of these memory operation uses and see
4241 // if they could *actually* fold the instruction. The assumption is that
4242 // addressing modes are cheap and that duplicating the computation involved
4243 // many times is worthwhile, even on a fastpath. For sinking candidates
4244 // (i.e. cold call sites), this serves as a way to prevent excessive code
4245 // growth since most architectures have some reasonable small and fast way to
4246 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004247 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4248 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4249 Instruction *User = MemoryUses[i].first;
4250 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004251
Chandler Carruthc8925912013-01-05 02:09:22 +00004252 // Get the access type of this use. If the use isn't a pointer, we don't
4253 // know what it accesses.
4254 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004255 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4256 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004257 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004258 Type *AddressAccessTy = AddrTy->getElementType();
4259 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004260
Chandler Carruthc8925912013-01-05 02:09:22 +00004261 // Do a match against the root of this address, ignoring profitability. This
4262 // will tell us if the addressing mode for the memory operation will
4263 // *actually* cover the shared instruction.
4264 ExtAddrMode Result;
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004265 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4266 0);
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004267 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4268 TPT.getRestorationPoint();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004269 AddressingModeMatcher Matcher(
4270 MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result,
4271 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Chandler Carruthc8925912013-01-05 02:09:22 +00004272 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004273 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004274 (void)Success; assert(Success && "Couldn't select *anything*?");
4275
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004276 // The match was to check the profitability, the changes made are not
4277 // part of the original matcher. Therefore, they should be dropped
4278 // otherwise the original matcher will not present the right state.
4279 TPT.rollback(LastKnownGood);
4280
Chandler Carruthc8925912013-01-05 02:09:22 +00004281 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004282 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004283 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004284
Chandler Carruthc8925912013-01-05 02:09:22 +00004285 MatchedAddrModeInsts.clear();
4286 }
Stephen Lin837bba12013-07-15 17:55:02 +00004287
Chandler Carruthc8925912013-01-05 02:09:22 +00004288 return true;
4289}
4290
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004291/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004292/// different basic block than BB.
4293static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4294 if (Instruction *I = dyn_cast<Instruction>(V))
4295 return I->getParent() != BB;
4296 return false;
4297}
4298
Philip Reamesac115ed2016-03-09 23:13:12 +00004299/// Sink addressing mode computation immediate before MemoryInst if doing so
4300/// can be done without increasing register pressure. The need for the
4301/// register pressure constraint means this can end up being an all or nothing
4302/// decision for all uses of the same addressing computation.
4303///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004304/// Load and Store Instructions often have addressing modes that can do
4305/// significant amounts of computation. As such, instruction selection will try
4306/// to get the load or store to do as much computation as possible for the
4307/// program. The problem is that isel can only see within a single block. As
4308/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004309///
4310/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004311/// operands. It's also used to sink addressing computations feeding into cold
4312/// call sites into their (cold) basic block.
4313///
4314/// The motivation for handling sinking into cold blocks is that doing so can
4315/// both enable other address mode sinking (by satisfying the register pressure
4316/// constraint above), and reduce register pressure globally (by removing the
4317/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004318bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004319 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004320 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004321
4322 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004323 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004324 SmallVector<Value*, 8> worklist;
4325 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004326 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004327
John Brawneb83c752017-10-03 13:04:15 +00004328 // Use a worklist to iteratively look through PHI and select nodes, and
4329 // ensure that the addressing mode obtained from the non-PHI/select roots of
John Brawn736bf002017-10-03 13:08:22 +00004330 // the graph are compatible.
John Brawneb83c752017-10-03 13:04:15 +00004331 bool PhiOrSelectSeen = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004332 SmallVector<Instruction*, 16> AddrModeInsts;
Serguei Katkovaee63752017-11-05 07:59:02 +00004333 const SimplifyQuery SQ(*DL, TLInfo);
4334 AddressingModeCombiner AddrModes(SQ, { Addr, MemoryInst->getParent() });
Jun Bum Limdee55652017-04-03 19:20:07 +00004335 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004336 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4337 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004338 while (!worklist.empty()) {
4339 Value *V = worklist.back();
4340 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004341
Serguei Katkov4ea855e2017-07-19 04:49:17 +00004342 // We allow traversing cyclic Phi nodes.
4343 // In case of success after this loop we ensure that traversing through
4344 // Phi nodes ends up with all cases to compute address of the form
4345 // BaseGV + Base + Scale * Index + Offset
4346 // where Scale and Offset are constans and BaseGV, Base and Index
4347 // are exactly the same Values in all cases.
4348 // It means that BaseGV, Scale and Offset dominate our memory instruction
4349 // and have the same value as they had in address computation represented
4350 // as Phi. So we can safely sink address computation to memory instruction.
4351 if (!Visited.insert(V).second)
4352 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00004353
Owen Anderson8ba5f392010-11-27 08:15:55 +00004354 // For a PHI node, push all of its incoming values.
4355 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004356 for (Value *IncValue : P->incoming_values())
4357 worklist.push_back(IncValue);
John Brawneb83c752017-10-03 13:04:15 +00004358 PhiOrSelectSeen = true;
4359 continue;
4360 }
4361 // Similar for select.
4362 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4363 worklist.push_back(SI->getFalseValue());
4364 worklist.push_back(SI->getTrueValue());
4365 PhiOrSelectSeen = true;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004366 continue;
4367 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004368
Philip Reamesac115ed2016-03-09 23:13:12 +00004369 // For non-PHIs, determine the addressing mode being computed. Note that
4370 // the result may differ depending on what other uses our candidate
4371 // addressing instructions might have.
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004372 AddrModeInsts.clear();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004373 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4374 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004375 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004376 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004377 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004378
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004379 GetElementPtrInst *GEP = LargeOffsetGEP.first;
4380 if (GEP && GEP->getParent() != MemoryInst->getParent() &&
4381 !NewGEPBases.count(GEP)) {
4382 // If splitting the underlying data structure can reduce the offset of a
4383 // GEP, collect the GEP. Skip the GEPs that are the new bases of
4384 // previously split data structures.
4385 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
4386 if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
4387 LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
4388 }
4389
4390 NewAddrMode.OriginalValue = V;
John Brawn736bf002017-10-03 13:08:22 +00004391 if (!AddrModes.addNewAddrMode(NewAddrMode))
4392 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004393 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004394
John Brawn736bf002017-10-03 13:08:22 +00004395 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4396 // or we have multiple but either couldn't combine them or combining them
4397 // wouldn't do anything useful, bail out now.
4398 if (!AddrModes.combineAddrModes()) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004399 TPT.rollback(LastKnownGood);
4400 return false;
4401 }
4402 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004403
John Brawn736bf002017-10-03 13:08:22 +00004404 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4405 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4406
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004407 // If all the instructions matched are already in this BB, don't do anything.
John Brawneb83c752017-10-03 13:04:15 +00004408 // If we saw a Phi node then it is not local definitely, and if we saw a select
4409 // then we want to push the address calculation past it even if it's already
4410 // in this BB.
4411 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
Justin Lebar838c7f52016-11-21 22:49:11 +00004412 return IsNonLocalValue(V, MemoryInst->getParent());
Serguei Katkov0b7b59a2017-07-11 06:24:44 +00004413 })) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004414 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
4415 << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004416 return false;
4417 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004418
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004419 // Insert this computation right after this user. Since our caller is
4420 // scanning from the top of the BB to the bottom, reuse of the expr are
4421 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004422 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004423
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004424 // Now that we determined the addressing expression we want to use and know
4425 // that we have to sink it into this block. Check to see if we have already
Simon Dardis230f4532017-11-24 16:45:28 +00004426 // done this for some other load/store instr in this block. If so, reuse
4427 // the computation. Before attempting reuse, check if the address is valid
4428 // as it may have been erased.
4429
4430 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
4431
4432 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004433 if (SunkAddr) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004434 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
4435 << " for " << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004436 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004437 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004438 } else if (AddrSinkUsingGEPs ||
David Blaikie8ad9a972018-03-28 22:28:50 +00004439 (!AddrSinkUsingGEPs.getNumOccurrences() && TM && TTI->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004440 // By default, we use the GEP-based method when AA is used later. This
4441 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004442 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4443 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004444 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004445 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004446
4447 // First, find the pointer.
4448 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4449 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004450 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004451 }
4452
4453 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4454 // We can't add more than one pointer together, nor can we scale a
4455 // pointer (both of which seem meaningless).
4456 if (ResultPtr || AddrMode.Scale != 1)
4457 return false;
4458
4459 ResultPtr = AddrMode.ScaledReg;
4460 AddrMode.Scale = 0;
4461 }
4462
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004463 // It is only safe to sign extend the BaseReg if we know that the math
4464 // required to create it did not overflow before we extend it. Since
4465 // the original IR value was tossed in favor of a constant back when
4466 // the AddrMode was created we need to bail out gracefully if widths
4467 // do not match instead of extending it.
4468 //
4469 // (See below for code to add the scale.)
4470 if (AddrMode.Scale) {
4471 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4472 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4473 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4474 return false;
4475 }
4476
Hal Finkelc3998302014-04-12 00:59:48 +00004477 if (AddrMode.BaseGV) {
4478 if (ResultPtr)
4479 return false;
4480
4481 ResultPtr = AddrMode.BaseGV;
4482 }
4483
4484 // If the real base value actually came from an inttoptr, then the matcher
4485 // will look through it and provide only the integer value. In that case,
4486 // use it here.
Keno Fischer05e4ac22017-06-29 20:28:59 +00004487 if (!DL->isNonIntegralPointerType(Addr->getType())) {
4488 if (!ResultPtr && AddrMode.BaseReg) {
4489 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4490 "sunkaddr");
4491 AddrMode.BaseReg = nullptr;
4492 } else if (!ResultPtr && AddrMode.Scale == 1) {
4493 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4494 "sunkaddr");
4495 AddrMode.Scale = 0;
4496 }
Hal Finkelc3998302014-04-12 00:59:48 +00004497 }
4498
4499 if (!ResultPtr &&
4500 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4501 SunkAddr = Constant::getNullValue(Addr->getType());
4502 } else if (!ResultPtr) {
4503 return false;
4504 } else {
4505 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004506 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4507 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004508
4509 // Start with the base register. Do this first so that subsequent address
4510 // matching finds it last, which will prevent it from trying to match it
4511 // as the scaled value in case it happens to be a mul. That would be
4512 // problematic if we've sunk a different mul for the scale, because then
4513 // we'd end up sinking both muls.
4514 if (AddrMode.BaseReg) {
4515 Value *V = AddrMode.BaseReg;
4516 if (V->getType() != IntPtrTy)
4517 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4518
4519 ResultIndex = V;
4520 }
4521
4522 // Add the scale value.
4523 if (AddrMode.Scale) {
4524 Value *V = AddrMode.ScaledReg;
4525 if (V->getType() == IntPtrTy) {
4526 // done.
Hal Finkelc3998302014-04-12 00:59:48 +00004527 } else {
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004528 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4529 cast<IntegerType>(V->getType())->getBitWidth() &&
4530 "We can't transform if ScaledReg is too narrow");
4531 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004532 }
4533
4534 if (AddrMode.Scale != 1)
4535 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4536 "sunkaddr");
4537 if (ResultIndex)
4538 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4539 else
4540 ResultIndex = V;
4541 }
4542
4543 // Add in the Base Offset if present.
4544 if (AddrMode.BaseOffs) {
4545 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4546 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004547 // We need to add this separately from the scale above to help with
4548 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004549 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004550 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004551 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004552 }
4553
4554 ResultIndex = V;
4555 }
4556
4557 if (!ResultIndex) {
4558 SunkAddr = ResultPtr;
4559 } else {
4560 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004561 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004562 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004563 }
4564
4565 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004566 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004567 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004568 } else {
Keno Fischer05e4ac22017-06-29 20:28:59 +00004569 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4570 // non-integral pointers, so in that case bail out now.
4571 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4572 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4573 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4574 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4575 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4576 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4577 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4578 (AddrMode.BaseGV &&
4579 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4580 return false;
4581
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004582 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4583 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004584 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004585 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004586
4587 // Start with the base register. Do this first so that subsequent address
4588 // matching finds it last, which will prevent it from trying to match it
4589 // as the scaled value in case it happens to be a mul. That would be
4590 // problematic if we've sunk a different mul for the scale, because then
4591 // we'd end up sinking both muls.
4592 if (AddrMode.BaseReg) {
4593 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004594 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004595 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004596 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004597 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004598 Result = V;
4599 }
4600
4601 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004602 if (AddrMode.Scale) {
4603 Value *V = AddrMode.ScaledReg;
4604 if (V->getType() == IntPtrTy) {
4605 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004606 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004607 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004608 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4609 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004610 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004611 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004612 // It is only safe to sign extend the BaseReg if we know that the math
4613 // required to create it did not overflow before we extend it. Since
4614 // the original IR value was tossed in favor of a constant back when
4615 // the AddrMode was created we need to bail out gracefully if widths
4616 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004617 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004618 if (I && (Result != AddrMode.BaseReg))
4619 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004620 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004621 }
4622 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004623 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4624 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004625 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004626 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004627 else
4628 Result = V;
4629 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004630
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004631 // Add in the BaseGV if present.
4632 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004633 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004634 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004635 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004636 else
4637 Result = V;
4638 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004639
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004640 // Add in the Base Offset if present.
4641 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004642 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004643 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004644 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004645 else
4646 Result = V;
4647 }
4648
Craig Topperc0196b12014-04-14 00:51:57 +00004649 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004650 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004651 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004652 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004653 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004654
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004655 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Simon Dardis230f4532017-11-24 16:45:28 +00004656 // Store the newly computed address into the cache. In the case we reused a
4657 // value, this should be idempotent.
4658 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004659
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004660 // If we have no uses, recursively delete the value and all dead instructions
4661 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004662 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004663 // This can cause recursive deletion, which can invalidate our iterator.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004664 // Use a WeakTrackingVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004665 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004666 WeakTrackingVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004667 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004668
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004669 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004670
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004671 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004672 // If the iterator instruction was recursively deleted, start over at the
4673 // start of the block.
4674 CurInstIterator = BB->begin();
4675 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004676 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004677 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004678 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004679 return true;
4680}
4681
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004682/// If there are any memory operands, use OptimizeMemoryInst to sink their
4683/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004684bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004685 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004686
Eric Christopher11e4df72015-02-26 22:38:43 +00004687 const TargetRegisterInfo *TRI =
Sanjay Patel4137d512017-06-07 14:29:52 +00004688 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004689 TargetLowering::AsmOperandInfoVector TargetConstraints =
4690 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004691 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004692 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4693 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004694
Evan Cheng1da25002008-02-26 02:42:37 +00004695 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004696 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004697
Eli Friedman666bbe32008-02-26 18:37:49 +00004698 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4699 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004700 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004701 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004702 } else if (OpInfo.Type == InlineAsm::isInput)
4703 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004704 }
4705
4706 return MadeChange;
4707}
4708
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004709/// Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004710/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00004711static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4712 assert(!Val->use_empty() && "Input must have at least one use");
4713 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004714 bool IsSExt = isa<SExtInst>(FirstUser);
4715 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00004716 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004717 const Instruction *UI = cast<Instruction>(U);
4718 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4719 return false;
4720 Type *CurTy = UI->getType();
4721 // Same input and output types: Same instruction after CSE.
4722 if (CurTy == ExtTy)
4723 continue;
4724
4725 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00004726 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004727 // b = sext ty1 a to ty2
4728 // c = sext ty1 a to ty3
4729 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00004730 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004731 // b = sext ty1 a to ty2
4732 // c = sext ty2 b to ty3
4733 // However, the last sext is not free.
4734 if (IsSExt)
4735 return false;
4736
4737 // This is a ZExt, maybe this is free to extend from one type to another.
4738 // In that case, we would not account for a different use.
4739 Type *NarrowTy;
4740 Type *LargeTy;
4741 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4742 CurTy->getScalarType()->getIntegerBitWidth()) {
4743 NarrowTy = CurTy;
4744 LargeTy = ExtTy;
4745 } else {
4746 NarrowTy = ExtTy;
4747 LargeTy = CurTy;
4748 }
4749
4750 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4751 return false;
4752 }
4753 // All uses are the same or can be derived from one another for free.
4754 return true;
4755}
4756
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004757/// Try to speculatively promote extensions in \p Exts and continue
Jun Bum Lim42301012017-03-17 19:05:21 +00004758/// promoting through newly promoted operands recursively as far as doing so is
4759/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4760/// When some promotion happened, \p TPT contains the proper state to revert
4761/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004762///
Jun Bum Lim42301012017-03-17 19:05:21 +00004763/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00004764bool CodeGenPrepare::tryToPromoteExts(
4765 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4766 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4767 unsigned CreatedInstsCost) {
4768 bool Promoted = false;
4769
4770 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004771 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004772 // Early check if we directly have ext(load).
4773 if (isa<LoadInst>(I->getOperand(0))) {
4774 ProfitablyMovedExts.push_back(I);
4775 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004776 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004777
4778 // Check whether or not we want to do any promotion. The reason we have
4779 // this check inside the for loop is to catch the case where an extension
4780 // is directly fed by a load because in such case the extension can be moved
4781 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004782 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00004783 return false;
4784
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004785 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00004786 TypePromotionHelper::Action TPH =
4787 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004788 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00004789 if (!TPH) {
4790 // Save the current extension as we cannot move up through its operand.
4791 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004792 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00004793 }
4794
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004795 // Save the current state.
4796 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4797 TPT.getRestorationPoint();
4798 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004799 unsigned NewCreatedInstsCost = 0;
4800 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004801 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004802 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4803 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004804 assert(PromotedVal &&
4805 "TypePromotionHelper should have filtered out those cases");
4806
4807 // We would be able to merge only one extension in a load.
4808 // Therefore, if we have more than 1 new extension we heuristically
4809 // cut this search path, because it means we degrade the code quality.
4810 // With exactly 2, the transformation is neutral, because we will merge
4811 // one extension but leave one. However, we optimistically keep going,
4812 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004813 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004814 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00004815 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004816 TotalCreatedInstsCost =
4817 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004818 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004819 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004820 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004821 // This promotion is not profitable, rollback to the previous state, and
4822 // save the current extension in ProfitablyMovedExts as the latest
4823 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004824 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00004825 ProfitablyMovedExts.push_back(I);
4826 continue;
4827 }
4828 // Continue promoting NewExts as far as doing so is profitable.
4829 SmallVector<Instruction *, 2> NewlyMovedExts;
4830 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4831 bool NewPromoted = false;
4832 for (auto ExtInst : NewlyMovedExts) {
4833 Instruction *MovedExt = cast<Instruction>(ExtInst);
4834 Value *ExtOperand = MovedExt->getOperand(0);
4835 // If we have reached to a load, we need this extra profitability check
4836 // as it could potentially be merged into an ext(load).
4837 if (isa<LoadInst>(ExtOperand) &&
4838 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4839 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
4840 continue;
4841
4842 ProfitablyMovedExts.push_back(MovedExt);
4843 NewPromoted = true;
4844 }
4845
4846 // If none of speculative promotions for NewExts is profitable, rollback
4847 // and save the current extension (I) as the last profitable extension.
4848 if (!NewPromoted) {
4849 TPT.rollback(LastKnownGood);
4850 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004851 continue;
4852 }
4853 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00004854 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004855 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004856 return Promoted;
4857}
4858
Jun Bum Limdee55652017-04-03 19:20:07 +00004859/// Merging redundant sexts when one is dominating the other.
4860bool CodeGenPrepare::mergeSExts(Function &F) {
4861 DominatorTree DT(F);
4862 bool Changed = false;
4863 for (auto &Entry : ValToSExtendedUses) {
4864 SExts &Insts = Entry.second;
4865 SExts CurPts;
4866 for (Instruction *Inst : Insts) {
4867 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
4868 Inst->getOperand(0) != Entry.first)
4869 continue;
4870 bool inserted = false;
4871 for (auto &Pt : CurPts) {
4872 if (DT.dominates(Inst, Pt)) {
4873 Pt->replaceAllUsesWith(Inst);
4874 RemovedInsts.insert(Pt);
4875 Pt->removeFromParent();
4876 Pt = Inst;
4877 inserted = true;
4878 Changed = true;
4879 break;
4880 }
4881 if (!DT.dominates(Pt, Inst))
4882 // Give up if we need to merge in a common dominator as the
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00004883 // experiments show it is not profitable.
Jun Bum Limdee55652017-04-03 19:20:07 +00004884 continue;
4885 Inst->replaceAllUsesWith(Pt);
4886 RemovedInsts.insert(Inst);
4887 Inst->removeFromParent();
4888 inserted = true;
4889 Changed = true;
4890 break;
4891 }
4892 if (!inserted)
4893 CurPts.push_back(Inst);
4894 }
4895 }
4896 return Changed;
4897}
4898
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004899// Spliting large data structures so that the GEPs accessing them can have
4900// smaller offsets so that they can be sunk to the same blocks as their users.
4901// For example, a large struct starting from %base is splitted into two parts
4902// where the second part starts from %new_base.
4903//
4904// Before:
4905// BB0:
4906// %base =
4907//
4908// BB1:
4909// %gep0 = gep %base, off0
4910// %gep1 = gep %base, off1
4911// %gep2 = gep %base, off2
4912//
4913// BB2:
4914// %load1 = load %gep0
4915// %load2 = load %gep1
4916// %load3 = load %gep2
4917//
4918// After:
4919// BB0:
4920// %base =
4921// %new_base = gep %base, off0
4922//
4923// BB1:
4924// %new_gep0 = %new_base
4925// %new_gep1 = gep %new_base, off1 - off0
4926// %new_gep2 = gep %new_base, off2 - off0
4927//
4928// BB2:
4929// %load1 = load i32, i32* %new_gep0
4930// %load2 = load i32, i32* %new_gep1
4931// %load3 = load i32, i32* %new_gep2
4932//
4933// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
4934// their offsets are smaller enough to fit into the addressing mode.
4935bool CodeGenPrepare::splitLargeGEPOffsets() {
4936 bool Changed = false;
4937 for (auto &Entry : LargeOffsetGEPMap) {
4938 Value *OldBase = Entry.first;
4939 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
4940 &LargeOffsetGEPs = Entry.second;
4941 auto compareGEPOffset =
4942 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
4943 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
4944 if (LHS.first == RHS.first)
4945 return false;
4946 if (LHS.second != RHS.second)
4947 return LHS.second < RHS.second;
4948 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
4949 };
4950 // Sorting all the GEPs of the same data structures based on the offsets.
4951 llvm::sort(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end(),
4952 compareGEPOffset);
4953 LargeOffsetGEPs.erase(
4954 std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()),
4955 LargeOffsetGEPs.end());
4956 // Skip if all the GEPs have the same offsets.
4957 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
4958 continue;
4959 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
4960 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
4961 Value *NewBaseGEP = nullptr;
4962
4963 auto LargeOffsetGEP = LargeOffsetGEPs.begin();
4964 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
4965 GetElementPtrInst *GEP = LargeOffsetGEP->first;
4966 int64_t Offset = LargeOffsetGEP->second;
4967 if (Offset != BaseOffset) {
4968 TargetLowering::AddrMode AddrMode;
4969 AddrMode.BaseOffs = Offset - BaseOffset;
4970 // The result type of the GEP might not be the type of the memory
4971 // access.
4972 if (!TLI->isLegalAddressingMode(*DL, AddrMode,
4973 GEP->getResultElementType(),
4974 GEP->getAddressSpace())) {
4975 // We need to create a new base if the offset to the current base is
4976 // too large to fit into the addressing mode. So, a very large struct
4977 // may be splitted into several parts.
4978 BaseGEP = GEP;
4979 BaseOffset = Offset;
4980 NewBaseGEP = nullptr;
4981 }
4982 }
4983
4984 // Generate a new GEP to replace the current one.
4985 IRBuilder<> Builder(GEP);
4986 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
4987 Type *I8PtrTy =
4988 Builder.getInt8PtrTy(GEP->getType()->getPointerAddressSpace());
4989 Type *I8Ty = Builder.getInt8Ty();
4990
4991 if (!NewBaseGEP) {
4992 // Create a new base if we don't have one yet. Find the insertion
4993 // pointer for the new base first.
4994 BasicBlock::iterator NewBaseInsertPt;
4995 BasicBlock *NewBaseInsertBB;
4996 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
4997 // If the base of the struct is an instruction, the new base will be
4998 // inserted close to it.
4999 NewBaseInsertBB = BaseI->getParent();
5000 if (isa<PHINode>(BaseI))
5001 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5002 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
5003 NewBaseInsertBB =
5004 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
5005 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5006 } else
5007 NewBaseInsertPt = std::next(BaseI->getIterator());
5008 } else {
5009 // If the current base is an argument or global value, the new base
5010 // will be inserted to the entry block.
5011 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
5012 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5013 }
5014 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
5015 // Create a new base.
5016 Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset);
5017 NewBaseGEP = OldBase;
5018 if (NewBaseGEP->getType() != I8PtrTy)
5019 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
5020 NewBaseGEP =
5021 NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep");
5022 NewGEPBases.insert(NewBaseGEP);
5023 }
5024
5025 Value *NewGEP = NewBaseGEP;
5026 if (Offset == BaseOffset) {
5027 if (GEP->getType() != I8PtrTy)
5028 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5029 } else {
5030 // Calculate the new offset for the new GEP.
5031 Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset);
5032 NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index);
5033
5034 if (GEP->getType() != I8PtrTy)
5035 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5036 }
5037 GEP->replaceAllUsesWith(NewGEP);
5038 LargeOffsetGEPID.erase(GEP);
5039 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
5040 GEP->eraseFromParent();
5041 Changed = true;
5042 }
5043 }
5044 return Changed;
5045}
5046
Jun Bum Lim42301012017-03-17 19:05:21 +00005047/// Return true, if an ext(load) can be formed from an extension in
5048/// \p MovedExts.
5049bool CodeGenPrepare::canFormExtLd(
5050 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
5051 Instruction *&Inst, bool HasPromoted) {
5052 for (auto *MovedExtInst : MovedExts) {
5053 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
5054 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
5055 Inst = MovedExtInst;
5056 break;
5057 }
5058 }
5059 if (!LI)
5060 return false;
5061
5062 // If they're already in the same block, there's nothing to do.
5063 // Make the cheap checks first if we did not promote.
5064 // If we promoted, we need to check if it is indeed profitable.
5065 if (!HasPromoted && LI->getParent() == Inst->getParent())
5066 return false;
5067
Haicheng Wuabdef9e2017-07-15 02:12:16 +00005068 return TLI->isExtLoad(LI, Inst, *DL);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005069}
5070
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005071/// Move a zext or sext fed by a load into the same basic block as the load,
5072/// unless conditions are unfavorable. This allows SelectionDAG to fold the
5073/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00005074///
Jun Bum Limdee55652017-04-03 19:20:07 +00005075/// E.g.,
5076/// \code
5077/// %ld = load i32* %addr
5078/// %add = add nuw i32 %ld, 4
5079/// %zext = zext i32 %add to i64
5080// \endcode
5081/// =>
5082/// \code
5083/// %ld = load i32* %addr
5084/// %zext = zext i32 %ld to i64
5085/// %add = add nuw i64 %zext, 4
5086/// \encode
5087/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
5088/// allow us to match zext(load i32*) to i64.
5089///
5090/// Also, try to promote the computations used to obtain a sign extended
5091/// value used into memory accesses.
5092/// E.g.,
5093/// \code
5094/// a = add nsw i32 b, 3
5095/// d = sext i32 a to i64
5096/// e = getelementptr ..., i64 d
5097/// \endcode
5098/// =>
5099/// \code
5100/// f = sext i32 b to i64
5101/// a = add nsw i64 f, 3
5102/// e = getelementptr ..., i64 a
5103/// \endcode
5104///
5105/// \p Inst[in/out] the extension may be modified during the process if some
5106/// promotions apply.
5107bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
5108 // ExtLoad formation and address type promotion infrastructure requires TLI to
5109 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00005110 if (!TLI)
5111 return false;
5112
Jun Bum Limdee55652017-04-03 19:20:07 +00005113 bool AllowPromotionWithoutCommonHeader = false;
5114 /// See if it is an interesting sext operations for the address type
5115 /// promotion before trying to promote it, e.g., the ones with the right
5116 /// type and used in memory accesses.
5117 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
5118 *Inst, AllowPromotionWithoutCommonHeader);
5119 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005120 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00005121 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005122 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00005123 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
5124 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00005125
Jun Bum Limdee55652017-04-03 19:20:07 +00005126 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00005127
Dan Gohman99429a02009-10-16 20:59:35 +00005128 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005129 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00005130 Instruction *ExtFedByLoad;
5131
5132 // Try to promote a chain of computation if it allows to form an extended
5133 // load.
5134 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
5135 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
5136 TPT.commit();
5137 // Move the extend into the same block as the load
Sanjay Patel674d2c22017-08-29 14:07:48 +00005138 ExtFedByLoad->moveAfter(LI);
Jun Bum Limdee55652017-04-03 19:20:07 +00005139 // CGP does not check if the zext would be speculatively executed when moved
5140 // to the same basic block as the load. Preserving its original location
5141 // would pessimize the debugging experience, as well as negatively impact
5142 // the quality of sample pgo. We don't want to use "line 0" as that has a
5143 // size cost in the line-table section and logically the zext can be seen as
5144 // part of the load. Therefore we conservatively reuse the same debug
5145 // location for the load and the zext.
5146 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
5147 ++NumExtsMoved;
5148 Inst = ExtFedByLoad;
5149 return true;
5150 }
5151
5152 // Continue promoting SExts if known as considerable depending on targets.
5153 if (ATPConsiderable &&
5154 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
5155 HasPromoted, TPT, SpeculativelyMovedExts))
5156 return true;
5157
5158 TPT.rollback(LastKnownGood);
5159 return false;
5160}
5161
5162// Perform address type promotion if doing so is profitable.
5163// If AllowPromotionWithoutCommonHeader == false, we should find other sext
5164// instructions that sign extended the same initial value. However, if
5165// AllowPromotionWithoutCommonHeader == true, we expect promoting the
5166// extension is just profitable.
5167bool CodeGenPrepare::performAddressTypePromotion(
5168 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
5169 bool HasPromoted, TypePromotionTransaction &TPT,
5170 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
5171 bool Promoted = false;
5172 SmallPtrSet<Instruction *, 1> UnhandledExts;
5173 bool AllSeenFirst = true;
5174 for (auto I : SpeculativelyMovedExts) {
5175 Value *HeadOfChain = I->getOperand(0);
5176 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
5177 SeenChainsForSExt.find(HeadOfChain);
5178 // If there is an unhandled SExt which has the same header, try to promote
5179 // it as well.
5180 if (AlreadySeen != SeenChainsForSExt.end()) {
5181 if (AlreadySeen->second != nullptr)
5182 UnhandledExts.insert(AlreadySeen->second);
5183 AllSeenFirst = false;
5184 }
5185 }
5186
5187 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
5188 SpeculativelyMovedExts.size() == 1)) {
5189 TPT.commit();
5190 if (HasPromoted)
5191 Promoted = true;
5192 for (auto I : SpeculativelyMovedExts) {
5193 Value *HeadOfChain = I->getOperand(0);
5194 SeenChainsForSExt[HeadOfChain] = nullptr;
5195 ValToSExtendedUses[HeadOfChain].push_back(I);
5196 }
5197 // Update Inst as promotion happen.
5198 Inst = SpeculativelyMovedExts.pop_back_val();
5199 } else {
5200 // This is the first chain visited from the header, keep the current chain
5201 // as unhandled. Defer to promote this until we encounter another SExt
5202 // chain derived from the same header.
5203 for (auto I : SpeculativelyMovedExts) {
5204 Value *HeadOfChain = I->getOperand(0);
5205 SeenChainsForSExt[HeadOfChain] = Inst;
5206 }
Dan Gohman99429a02009-10-16 20:59:35 +00005207 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005208 }
Dan Gohman99429a02009-10-16 20:59:35 +00005209
Jun Bum Limdee55652017-04-03 19:20:07 +00005210 if (!AllSeenFirst && !UnhandledExts.empty())
5211 for (auto VisitedSExt : UnhandledExts) {
5212 if (RemovedInsts.count(VisitedSExt))
5213 continue;
5214 TypePromotionTransaction TPT(RemovedInsts);
5215 SmallVector<Instruction *, 1> Exts;
5216 SmallVector<Instruction *, 2> Chains;
5217 Exts.push_back(VisitedSExt);
5218 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
5219 TPT.commit();
5220 if (HasPromoted)
5221 Promoted = true;
5222 for (auto I : Chains) {
5223 Value *HeadOfChain = I->getOperand(0);
5224 // Mark this as handled.
5225 SeenChainsForSExt[HeadOfChain] = nullptr;
5226 ValToSExtendedUses[HeadOfChain].push_back(I);
5227 }
5228 }
5229 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00005230}
5231
Sanjay Patelfc580a62015-09-21 23:03:16 +00005232bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00005233 BasicBlock *DefBB = I->getParent();
5234
Bob Wilsonff714f92010-09-21 21:44:14 +00005235 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00005236 // other uses of the source with result of extension.
5237 Value *Src = I->getOperand(0);
5238 if (Src->hasOneUse())
5239 return false;
5240
Evan Cheng2011df42007-12-13 07:50:36 +00005241 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00005242 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00005243 return false;
5244
Evan Cheng7bc89422007-12-12 00:51:06 +00005245 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00005246 // this block.
5247 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00005248 return false;
5249
Evan Chengd3d80172007-12-05 23:58:20 +00005250 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005251 for (User *U : I->users()) {
5252 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00005253
5254 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005255 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00005256 if (UserBB == DefBB) continue;
5257 DefIsLiveOut = true;
5258 break;
5259 }
5260 if (!DefIsLiveOut)
5261 return false;
5262
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00005263 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005264 for (User *U : Src->users()) {
5265 Instruction *UI = cast<Instruction>(U);
5266 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00005267 if (UserBB == DefBB) continue;
5268 // Be conservative. We don't want this xform to end up introducing
5269 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005270 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00005271 return false;
5272 }
5273
Evan Chengd3d80172007-12-05 23:58:20 +00005274 // InsertedTruncs - Only insert one trunc in each block once.
5275 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5276
5277 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005278 for (Use &U : Src->uses()) {
5279 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00005280
5281 // Figure out which BB this ext is used in.
5282 BasicBlock *UserBB = User->getParent();
5283 if (UserBB == DefBB) continue;
5284
5285 // Both src and def are live in this block. Rewrite the use.
5286 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5287
5288 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00005289 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005290 assert(InsertPt != UserBB->end());
5291 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005292 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00005293 }
5294
5295 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005296 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00005297 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00005298 MadeChange = true;
5299 }
5300
5301 return MadeChange;
5302}
5303
Geoff Berry5256fca2015-11-20 22:34:39 +00005304// Find loads whose uses only use some of the loaded value's bits. Add an "and"
5305// just after the load if the target can fold this into one extload instruction,
5306// with the hope of eliminating some of the other later "and" instructions using
5307// the loaded value. "and"s that are made trivially redundant by the insertion
5308// of the new "and" are removed by this function, while others (e.g. those whose
5309// path from the load goes through a phi) are left for isel to potentially
5310// remove.
5311//
5312// For example:
5313//
5314// b0:
5315// x = load i32
5316// ...
5317// b1:
5318// y = and x, 0xff
5319// z = use y
5320//
5321// becomes:
5322//
5323// b0:
5324// x = load i32
5325// x' = and x, 0xff
5326// ...
5327// b1:
5328// z = use x'
5329//
5330// whereas:
5331//
5332// b0:
5333// x1 = load i32
5334// ...
5335// b1:
5336// x2 = load i32
5337// ...
5338// b2:
5339// x = phi x1, x2
5340// y = and x, 0xff
5341//
5342// becomes (after a call to optimizeLoadExt for each load):
5343//
5344// b0:
5345// x1 = load i32
5346// x1' = and x1, 0xff
5347// ...
5348// b1:
5349// x2 = load i32
5350// x2' = and x2, 0xff
5351// ...
5352// b2:
5353// x = phi x1', x2'
5354// y = and x, 0xff
Geoff Berry5256fca2015-11-20 22:34:39 +00005355bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
Vedant Kumarb3091da2018-07-06 20:17:42 +00005356 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
Geoff Berry5256fca2015-11-20 22:34:39 +00005357 return false;
5358
Geoff Berry5d534b62017-02-21 18:53:14 +00005359 // Skip loads we've already transformed.
5360 if (Load->hasOneUse() &&
5361 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5362 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005363
5364 // Look at all uses of Load, looking through phis, to determine how many bits
5365 // of the loaded value are needed.
5366 SmallVector<Instruction *, 8> WorkList;
5367 SmallPtrSet<Instruction *, 16> Visited;
5368 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5369 for (auto *U : Load->users())
5370 WorkList.push_back(cast<Instruction>(U));
5371
5372 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5373 unsigned BitWidth = LoadResultVT.getSizeInBits();
5374 APInt DemandBits(BitWidth, 0);
5375 APInt WidestAndBits(BitWidth, 0);
5376
5377 while (!WorkList.empty()) {
5378 Instruction *I = WorkList.back();
5379 WorkList.pop_back();
5380
5381 // Break use-def graph loops.
5382 if (!Visited.insert(I).second)
5383 continue;
5384
5385 // For a PHI node, push all of its users.
5386 if (auto *Phi = dyn_cast<PHINode>(I)) {
5387 for (auto *U : Phi->users())
5388 WorkList.push_back(cast<Instruction>(U));
5389 continue;
5390 }
5391
5392 switch (I->getOpcode()) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005393 case Instruction::And: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005394 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5395 if (!AndC)
5396 return false;
5397 APInt AndBits = AndC->getValue();
5398 DemandBits |= AndBits;
5399 // Keep track of the widest and mask we see.
5400 if (AndBits.ugt(WidestAndBits))
5401 WidestAndBits = AndBits;
5402 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5403 AndsToMaybeRemove.push_back(I);
5404 break;
5405 }
5406
Eugene Zelenko900b6332017-08-29 22:32:07 +00005407 case Instruction::Shl: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005408 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5409 if (!ShlC)
5410 return false;
5411 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00005412 DemandBits.setLowBits(BitWidth - ShiftAmt);
Geoff Berry5256fca2015-11-20 22:34:39 +00005413 break;
5414 }
5415
Eugene Zelenko900b6332017-08-29 22:32:07 +00005416 case Instruction::Trunc: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005417 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5418 unsigned TruncBitWidth = TruncVT.getSizeInBits();
Craig Topperfc947bc2017-04-18 17:14:21 +00005419 DemandBits.setLowBits(TruncBitWidth);
Geoff Berry5256fca2015-11-20 22:34:39 +00005420 break;
5421 }
5422
5423 default:
5424 return false;
5425 }
5426 }
5427
5428 uint32_t ActiveBits = DemandBits.getActiveBits();
5429 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5430 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5431 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5432 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5433 // followed by an AND.
5434 // TODO: Look into removing this restriction by fixing backends to either
5435 // return false for isLoadExtLegal for i1 or have them select this pattern to
5436 // a single instruction.
5437 //
5438 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5439 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005440 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005441 WidestAndBits != DemandBits)
5442 return false;
5443
5444 LLVMContext &Ctx = Load->getType()->getContext();
5445 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5446 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5447
5448 // Reject cases that won't be matched as extloads.
5449 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5450 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5451 return false;
5452
5453 IRBuilder<> Builder(Load->getNextNode());
5454 auto *NewAnd = dyn_cast<Instruction>(
5455 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005456 // Mark this instruction as "inserted by CGP", so that other
5457 // optimizations don't touch it.
5458 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005459
5460 // Replace all uses of load with new and (except for the use of load in the
5461 // new and itself).
5462 Load->replaceAllUsesWith(NewAnd);
5463 NewAnd->setOperand(0, Load);
5464
5465 // Remove any and instructions that are now redundant.
5466 for (auto *And : AndsToMaybeRemove)
5467 // Check that the and mask is the same as the one we decided to put on the
5468 // new and.
5469 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5470 And->replaceAllUsesWith(NewAnd);
5471 if (&*CurInstIterator == And)
5472 CurInstIterator = std::next(And->getIterator());
5473 And->eraseFromParent();
5474 ++NumAndUses;
5475 }
5476
5477 ++NumAndsAdded;
5478 return true;
5479}
5480
Sanjay Patel69a50a12015-10-19 21:59:12 +00005481/// Check if V (an operand of a select instruction) is an expensive instruction
5482/// that is only used once.
5483static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5484 auto *I = dyn_cast<Instruction>(V);
5485 // If it's safe to speculatively execute, then it should not have side
5486 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005487 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5488 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005489}
5490
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005491/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005492static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005493 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005494 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005495 // If even a predictable select is cheap, then a branch can't be cheaper.
5496 if (!TLI->isPredictableSelectExpensive())
5497 return false;
5498
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005499 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005500 // whether a select is better represented as a branch.
5501
5502 // If metadata tells us that the select condition is obviously predictable,
5503 // then we want to replace the select with a branch.
5504 uint64_t TrueWeight, FalseWeight;
5505 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5506 uint64_t Max = std::max(TrueWeight, FalseWeight);
5507 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005508 if (Sum != 0) {
5509 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5510 if (Probability > TLI->getPredictableBranchThreshold())
5511 return true;
5512 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005513 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005514
5515 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5516
Sanjay Patel4e652762015-09-28 22:14:51 +00005517 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5518 // comparison condition. If the compare has more than one use, there's
5519 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005520 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005521 return false;
5522
Sanjay Patel69a50a12015-10-19 21:59:12 +00005523 // If either operand of the select is expensive and only needed on one side
5524 // of the select, we should form a branch.
5525 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5526 sinkSelectOperand(TTI, SI->getFalseValue()))
5527 return true;
5528
5529 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005530}
5531
Dehao Chen9bbb9412016-09-12 20:23:28 +00005532/// If \p isTrue is true, return the true value of \p SI, otherwise return
5533/// false value of \p SI. If the true/false value of \p SI is defined by any
5534/// select instructions in \p Selects, look through the defining select
5535/// instruction until the true/false value is not defined in \p Selects.
5536static Value *getTrueOrFalseValue(
5537 SelectInst *SI, bool isTrue,
5538 const SmallPtrSet<const Instruction *, 2> &Selects) {
5539 Value *V;
5540
5541 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5542 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005543 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005544 "The condition of DefSI does not match with SI");
5545 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5546 }
5547 return V;
5548}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005549
Nadav Rotem9d832022012-09-02 12:10:19 +00005550/// If we have a SelectInst that will likely profit from branch prediction,
5551/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005552bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00005553 // Find all consecutive select instructions that share the same condition.
5554 SmallVector<SelectInst *, 2> ASI;
5555 ASI.push_back(SI);
5556 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5557 It != SI->getParent()->end(); ++It) {
5558 SelectInst *I = dyn_cast<SelectInst>(&*It);
5559 if (I && SI->getCondition() == I->getCondition()) {
5560 ASI.push_back(I);
5561 } else {
5562 break;
5563 }
5564 }
5565
5566 SelectInst *LastSI = ASI.back();
5567 // Increment the current iterator to skip all the rest of select instructions
5568 // because they will be either "not lowered" or "all lowered" to branch.
5569 CurInstIterator = std::next(LastSI->getIterator());
5570
Nadav Rotem9d832022012-09-02 12:10:19 +00005571 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5572
5573 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00005574 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
5575 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005576 return false;
5577
Nadav Rotem9d832022012-09-02 12:10:19 +00005578 TargetLowering::SelectSupportKind SelectKind;
5579 if (VectorCond)
5580 SelectKind = TargetLowering::VectorMaskSelect;
5581 else if (SI->getType()->isVectorTy())
5582 SelectKind = TargetLowering::ScalarCondVectorVal;
5583 else
5584 SelectKind = TargetLowering::ScalarValSelect;
5585
Sanjay Pateld66607b2016-04-26 17:11:17 +00005586 if (TLI->isSelectSupported(SelectKind) &&
5587 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5588 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005589
5590 ModifiedDT = true;
5591
Sanjay Patel69a50a12015-10-19 21:59:12 +00005592 // Transform a sequence like this:
5593 // start:
5594 // %cmp = cmp uge i32 %a, %b
5595 // %sel = select i1 %cmp, i32 %c, i32 %d
5596 //
5597 // Into:
5598 // start:
5599 // %cmp = cmp uge i32 %a, %b
5600 // br i1 %cmp, label %select.true, label %select.false
5601 // select.true:
5602 // br label %select.end
5603 // select.false:
5604 // br label %select.end
5605 // select.end:
5606 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5607 //
5608 // In addition, we may sink instructions that produce %c or %d from
5609 // the entry block into the destination(s) of the new branch.
5610 // If the true or false blocks do not contain a sunken instruction, that
5611 // block and its branch may be optimized away. In that case, one side of the
5612 // first branch will point directly to select.end, and the corresponding PHI
5613 // predecessor block will be the start block.
5614
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005615 // First, we split the block containing the select into 2 blocks.
5616 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005617 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005618 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005619
Sanjay Patel69a50a12015-10-19 21:59:12 +00005620 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005621 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005622
5623 // These are the new basic blocks for the conditional branch.
5624 // At least one will become an actual new basic block.
5625 BasicBlock *TrueBlock = nullptr;
5626 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005627 BranchInst *TrueBranch = nullptr;
5628 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005629
5630 // Sink expensive instructions into the conditional blocks to avoid executing
5631 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005632 for (SelectInst *SI : ASI) {
5633 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5634 if (TrueBlock == nullptr) {
5635 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5636 EndBlock->getParent(), EndBlock);
5637 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5638 }
5639 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5640 TrueInst->moveBefore(TrueBranch);
5641 }
5642 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5643 if (FalseBlock == nullptr) {
5644 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5645 EndBlock->getParent(), EndBlock);
5646 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5647 }
5648 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5649 FalseInst->moveBefore(FalseBranch);
5650 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005651 }
5652
5653 // If there was nothing to sink, then arbitrarily choose the 'false' side
5654 // for a new input value to the PHI.
5655 if (TrueBlock == FalseBlock) {
5656 assert(TrueBlock == nullptr &&
5657 "Unexpected basic block transform while optimizing select");
5658
5659 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5660 EndBlock->getParent(), EndBlock);
5661 BranchInst::Create(EndBlock, FalseBlock);
5662 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005663
5664 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005665 // If we did not create a new block for one of the 'true' or 'false' paths
5666 // of the condition, it means that side of the branch goes to the end block
5667 // directly and the path originates from the start block from the point of
5668 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005669 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005670 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005671 TT = EndBlock;
5672 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005673 TrueBlock = StartBlock;
5674 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005675 TT = TrueBlock;
5676 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005677 FalseBlock = StartBlock;
5678 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005679 TT = TrueBlock;
5680 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005681 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005682 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005683
Dehao Chen9bbb9412016-09-12 20:23:28 +00005684 SmallPtrSet<const Instruction *, 2> INS;
5685 INS.insert(ASI.begin(), ASI.end());
5686 // Use reverse iterator because later select may use the value of the
5687 // earlier select, and we need to propagate value through earlier select
5688 // to get the PHI operand.
5689 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5690 SelectInst *SI = *It;
5691 // The select itself is replaced with a PHI Node.
5692 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5693 PN->takeName(SI);
5694 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5695 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00005696
Dehao Chen9bbb9412016-09-12 20:23:28 +00005697 SI->replaceAllUsesWith(PN);
5698 SI->eraseFromParent();
5699 INS.erase(SI);
5700 ++NumSelectsExpanded;
5701 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005702
5703 // Instruct OptimizeBlock to skip to the next block.
5704 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005705 return true;
5706}
5707
Benjamin Kramer573ff362014-03-01 17:24:40 +00005708static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005709 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5710 int SplatElem = -1;
5711 for (unsigned i = 0; i < Mask.size(); ++i) {
5712 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5713 return false;
5714 SplatElem = Mask[i];
5715 }
5716
5717 return true;
5718}
5719
5720/// Some targets have expensive vector shifts if the lanes aren't all the same
5721/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5722/// it's often worth sinking a shufflevector splat down to its use so that
5723/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005724bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005725 BasicBlock *DefBB = SVI->getParent();
5726
5727 // Only do this xform if variable vector shifts are particularly expensive.
5728 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5729 return false;
5730
5731 // We only expect better codegen by sinking a shuffle if we can recognise a
5732 // constant splat.
5733 if (!isBroadcastShuffle(SVI))
5734 return false;
5735
5736 // InsertedShuffles - Only insert a shuffle in each block once.
5737 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5738
5739 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005740 for (User *U : SVI->users()) {
5741 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005742
5743 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005744 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005745 if (UserBB == DefBB) continue;
5746
5747 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005748 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005749
5750 // Everything checks out, sink the shuffle if the user's block doesn't
5751 // already have a copy.
5752 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5753
5754 if (!InsertedShuffle) {
5755 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005756 assert(InsertPt != UserBB->end());
5757 InsertedShuffle =
5758 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5759 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005760 }
5761
Chandler Carruthcdf47882014-03-09 03:16:01 +00005762 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005763 MadeChange = true;
5764 }
5765
5766 // If we removed all uses, nuke the shuffle.
5767 if (SVI->use_empty()) {
5768 SVI->eraseFromParent();
5769 MadeChange = true;
5770 }
5771
5772 return MadeChange;
5773}
5774
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005775bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5776 if (!TLI || !DL)
5777 return false;
5778
5779 Value *Cond = SI->getCondition();
5780 Type *OldType = Cond->getType();
5781 LLVMContext &Context = Cond->getContext();
5782 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5783 unsigned RegWidth = RegType.getSizeInBits();
5784
5785 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5786 return false;
5787
5788 // If the register width is greater than the type width, expand the condition
5789 // of the switch instruction and each case constant to the width of the
5790 // register. By widening the type of the switch condition, subsequent
5791 // comparisons (for case comparisons) will not need to be extended to the
5792 // preferred register width, so we will potentially eliminate N-1 extends,
5793 // where N is the number of cases in the switch.
5794 auto *NewType = Type::getIntNTy(Context, RegWidth);
5795
5796 // Zero-extend the switch condition and case constants unless the switch
5797 // condition is a function argument that is already being sign-extended.
5798 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5799 // everything instead.
5800 Instruction::CastOps ExtType = Instruction::ZExt;
5801 if (auto *Arg = dyn_cast<Argument>(Cond))
5802 if (Arg->hasSExtAttr())
5803 ExtType = Instruction::SExt;
5804
5805 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5806 ExtInst->insertBefore(SI);
5807 SI->setCondition(ExtInst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00005808 for (auto Case : SI->cases()) {
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005809 APInt NarrowConst = Case.getCaseValue()->getValue();
5810 APInt WideConst = (ExtType == Instruction::ZExt) ?
5811 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5812 Case.setValue(ConstantInt::get(Context, WideConst));
5813 }
5814
5815 return true;
5816}
5817
Zaara Syeda3a7578c2017-05-31 17:12:38 +00005818
Quentin Colombetc32615d2014-10-31 17:52:53 +00005819namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005820
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005821/// Helper class to promote a scalar operation to a vector one.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005822/// This class is used to move downward extractelement transition.
5823/// E.g.,
5824/// a = vector_op <2 x i32>
5825/// b = extractelement <2 x i32> a, i32 0
5826/// c = scalar_op b
5827/// store c
5828///
5829/// =>
5830/// a = vector_op <2 x i32>
5831/// c = vector_op a (equivalent to scalar_op on the related lane)
5832/// * d = extractelement <2 x i32> c, i32 0
5833/// * store d
5834/// Assuming both extractelement and store can be combine, we get rid of the
5835/// transition.
5836class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005837 /// DataLayout associated with the current module.
5838 const DataLayout &DL;
5839
Quentin Colombetc32615d2014-10-31 17:52:53 +00005840 /// Used to perform some checks on the legality of vector operations.
5841 const TargetLowering &TLI;
5842
5843 /// Used to estimated the cost of the promoted chain.
5844 const TargetTransformInfo &TTI;
5845
5846 /// The transition being moved downwards.
5847 Instruction *Transition;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005848
Quentin Colombetc32615d2014-10-31 17:52:53 +00005849 /// The sequence of instructions to be promoted.
5850 SmallVector<Instruction *, 4> InstsToBePromoted;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005851
Quentin Colombetc32615d2014-10-31 17:52:53 +00005852 /// Cost of combining a store and an extract.
5853 unsigned StoreExtractCombineCost;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005854
Quentin Colombetc32615d2014-10-31 17:52:53 +00005855 /// Instruction that will be combined with the transition.
Eugene Zelenko900b6332017-08-29 22:32:07 +00005856 Instruction *CombineInst = nullptr;
Quentin Colombetc32615d2014-10-31 17:52:53 +00005857
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005858 /// The instruction that represents the current end of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005859 /// Since we are faking the promotion until we reach the end of the chain
5860 /// of computation, we need a way to get the current end of the transition.
5861 Instruction *getEndOfTransition() const {
5862 if (InstsToBePromoted.empty())
5863 return Transition;
5864 return InstsToBePromoted.back();
5865 }
5866
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005867 /// Return the index of the original value in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005868 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5869 /// c, is at index 0.
5870 unsigned getTransitionOriginalValueIdx() const {
5871 assert(isa<ExtractElementInst>(Transition) &&
5872 "Other kind of transitions are not supported yet");
5873 return 0;
5874 }
5875
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005876 /// Return the index of the index in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005877 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5878 /// is at index 1.
5879 unsigned getTransitionIdx() const {
5880 assert(isa<ExtractElementInst>(Transition) &&
5881 "Other kind of transitions are not supported yet");
5882 return 1;
5883 }
5884
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005885 /// Get the type of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005886 /// This is the type of the original value.
5887 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5888 /// transition is <2 x i32>.
5889 Type *getTransitionType() const {
5890 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5891 }
5892
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005893 /// Promote \p ToBePromoted by moving \p Def downward through.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005894 /// I.e., we have the following sequence:
5895 /// Def = Transition <ty1> a to <ty2>
5896 /// b = ToBePromoted <ty2> Def, ...
5897 /// =>
5898 /// b = ToBePromoted <ty1> a, ...
5899 /// Def = Transition <ty1> ToBePromoted to <ty2>
5900 void promoteImpl(Instruction *ToBePromoted);
5901
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005902 /// Check whether or not it is profitable to promote all the
Quentin Colombetc32615d2014-10-31 17:52:53 +00005903 /// instructions enqueued to be promoted.
5904 bool isProfitableToPromote() {
5905 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5906 unsigned Index = isa<ConstantInt>(ValIdx)
5907 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5908 : -1;
5909 Type *PromotedType = getTransitionType();
5910
5911 StoreInst *ST = cast<StoreInst>(CombineInst);
5912 unsigned AS = ST->getPointerAddressSpace();
5913 unsigned Align = ST->getAlignment();
5914 // Check if this store is supported.
5915 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005916 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5917 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005918 // If this is not supported, there is no way we can combine
5919 // the extract with the store.
5920 return false;
5921 }
5922
5923 // The scalar chain of computation has to pay for the transition
5924 // scalar to vector.
5925 // The vector chain has to account for the combining cost.
5926 uint64_t ScalarCost =
5927 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5928 uint64_t VectorCost = StoreExtractCombineCost;
5929 for (const auto &Inst : InstsToBePromoted) {
5930 // Compute the cost.
5931 // By construction, all instructions being promoted are arithmetic ones.
5932 // Moreover, one argument is a constant that can be viewed as a splat
5933 // constant.
5934 Value *Arg0 = Inst->getOperand(0);
5935 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5936 isa<ConstantFP>(Arg0);
5937 TargetTransformInfo::OperandValueKind Arg0OVK =
5938 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5939 : TargetTransformInfo::OK_AnyValue;
5940 TargetTransformInfo::OperandValueKind Arg1OVK =
5941 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5942 : TargetTransformInfo::OK_AnyValue;
5943 ScalarCost += TTI.getArithmeticInstrCost(
5944 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5945 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5946 Arg0OVK, Arg1OVK);
5947 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005948 LLVM_DEBUG(
5949 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5950 << ScalarCost << "\nVector: " << VectorCost << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00005951 return ScalarCost > VectorCost;
5952 }
5953
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005954 /// Generate a constant vector with \p Val with the same
Quentin Colombetc32615d2014-10-31 17:52:53 +00005955 /// number of elements as the transition.
5956 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005957 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005958 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5959 /// otherwise we generate a vector with as many undef as possible:
5960 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5961 /// used at the index of the extract.
5962 Value *getConstantVector(Constant *Val, bool UseSplat) const {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005963 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00005964 if (!UseSplat) {
5965 // If we cannot determine where the constant must be, we have to
5966 // use a splat constant.
5967 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5968 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5969 ExtractIdx = CstVal->getSExtValue();
5970 else
5971 UseSplat = true;
5972 }
5973
5974 unsigned End = getTransitionType()->getVectorNumElements();
5975 if (UseSplat)
5976 return ConstantVector::getSplat(End, Val);
5977
5978 SmallVector<Constant *, 4> ConstVec;
5979 UndefValue *UndefVal = UndefValue::get(Val->getType());
5980 for (unsigned Idx = 0; Idx != End; ++Idx) {
5981 if (Idx == ExtractIdx)
5982 ConstVec.push_back(Val);
5983 else
5984 ConstVec.push_back(UndefVal);
5985 }
5986 return ConstantVector::get(ConstVec);
5987 }
5988
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005989 /// Check if promoting to a vector type an operand at \p OperandIdx
Quentin Colombetc32615d2014-10-31 17:52:53 +00005990 /// in \p Use can trigger undefined behavior.
5991 static bool canCauseUndefinedBehavior(const Instruction *Use,
5992 unsigned OperandIdx) {
5993 // This is not safe to introduce undef when the operand is on
5994 // the right hand side of a division-like instruction.
5995 if (OperandIdx != 1)
5996 return false;
5997 switch (Use->getOpcode()) {
5998 default:
5999 return false;
6000 case Instruction::SDiv:
6001 case Instruction::UDiv:
6002 case Instruction::SRem:
6003 case Instruction::URem:
6004 return true;
6005 case Instruction::FDiv:
6006 case Instruction::FRem:
6007 return !Use->hasNoNaNs();
6008 }
6009 llvm_unreachable(nullptr);
6010 }
6011
6012public:
Mehdi Amini44ede332015-07-09 02:09:04 +00006013 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
6014 const TargetTransformInfo &TTI, Instruction *Transition,
6015 unsigned CombineCost)
6016 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Eugene Zelenko900b6332017-08-29 22:32:07 +00006017 StoreExtractCombineCost(CombineCost) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00006018 assert(Transition && "Do not know how to promote null");
6019 }
6020
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006021 /// Check if we can promote \p ToBePromoted to \p Type.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006022 bool canPromote(const Instruction *ToBePromoted) const {
6023 // We could support CastInst too.
6024 return isa<BinaryOperator>(ToBePromoted);
6025 }
6026
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006027 /// Check if it is profitable to promote \p ToBePromoted
Quentin Colombetc32615d2014-10-31 17:52:53 +00006028 /// by moving downward the transition through.
6029 bool shouldPromote(const Instruction *ToBePromoted) const {
6030 // Promote only if all the operands can be statically expanded.
6031 // Indeed, we do not want to introduce any new kind of transitions.
6032 for (const Use &U : ToBePromoted->operands()) {
6033 const Value *Val = U.get();
6034 if (Val == getEndOfTransition()) {
6035 // If the use is a division and the transition is on the rhs,
6036 // we cannot promote the operation, otherwise we may create a
6037 // division by zero.
6038 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
6039 return false;
6040 continue;
6041 }
6042 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
6043 !isa<ConstantFP>(Val))
6044 return false;
6045 }
6046 // Check that the resulting operation is legal.
6047 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
6048 if (!ISDOpcode)
6049 return false;
6050 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00006051 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00006052 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00006053 }
6054
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006055 /// Check whether or not \p Use can be combined
Quentin Colombetc32615d2014-10-31 17:52:53 +00006056 /// with the transition.
6057 /// I.e., is it possible to do Use(Transition) => AnotherUse?
6058 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
6059
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006060 /// Record \p ToBePromoted as part of the chain to be promoted.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006061 void enqueueForPromotion(Instruction *ToBePromoted) {
6062 InstsToBePromoted.push_back(ToBePromoted);
6063 }
6064
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006065 /// Set the instruction that will be combined with the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006066 void recordCombineInstruction(Instruction *ToBeCombined) {
6067 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
6068 CombineInst = ToBeCombined;
6069 }
6070
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006071 /// Promote all the instructions enqueued for promotion if it is
Quentin Colombetc32615d2014-10-31 17:52:53 +00006072 /// is profitable.
6073 /// \return True if the promotion happened, false otherwise.
6074 bool promote() {
6075 // Check if there is something to promote.
6076 // Right now, if we do not have anything to combine with,
6077 // we assume the promotion is not profitable.
6078 if (InstsToBePromoted.empty() || !CombineInst)
6079 return false;
6080
6081 // Check cost.
6082 if (!StressStoreExtract && !isProfitableToPromote())
6083 return false;
6084
6085 // Promote.
6086 for (auto &ToBePromoted : InstsToBePromoted)
6087 promoteImpl(ToBePromoted);
6088 InstsToBePromoted.clear();
6089 return true;
6090 }
6091};
Eugene Zelenko900b6332017-08-29 22:32:07 +00006092
6093} // end anonymous namespace
Quentin Colombetc32615d2014-10-31 17:52:53 +00006094
6095void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
6096 // At this point, we know that all the operands of ToBePromoted but Def
6097 // can be statically promoted.
6098 // For Def, we need to use its parameter in ToBePromoted:
6099 // b = ToBePromoted ty1 a
6100 // Def = Transition ty1 b to ty2
6101 // Move the transition down.
6102 // 1. Replace all uses of the promoted operation by the transition.
6103 // = ... b => = ... Def.
6104 assert(ToBePromoted->getType() == Transition->getType() &&
6105 "The type of the result of the transition does not match "
6106 "the final type");
6107 ToBePromoted->replaceAllUsesWith(Transition);
6108 // 2. Update the type of the uses.
6109 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
6110 Type *TransitionTy = getTransitionType();
6111 ToBePromoted->mutateType(TransitionTy);
6112 // 3. Update all the operands of the promoted operation with promoted
6113 // operands.
6114 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
6115 for (Use &U : ToBePromoted->operands()) {
6116 Value *Val = U.get();
6117 Value *NewVal = nullptr;
6118 if (Val == Transition)
6119 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
6120 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
6121 isa<ConstantFP>(Val)) {
6122 // Use a splat constant if it is not safe to use undef.
6123 NewVal = getConstantVector(
6124 cast<Constant>(Val),
6125 isa<UndefValue>(Val) ||
6126 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
6127 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00006128 llvm_unreachable("Did you modified shouldPromote and forgot to update "
6129 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006130 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
6131 }
Sanjay Patel674d2c22017-08-29 14:07:48 +00006132 Transition->moveAfter(ToBePromoted);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006133 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6134}
6135
6136/// Some targets can do store(extractelement) with one instruction.
6137/// Try to push the extractelement towards the stores when the target
6138/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006139bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006140 unsigned CombineCost = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006141 if (DisableStoreExtract || !TLI ||
6142 (!StressStoreExtract &&
6143 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
6144 Inst->getOperand(1), CombineCost)))
6145 return false;
6146
6147 // At this point we know that Inst is a vector to scalar transition.
6148 // Try to move it down the def-use chain, until:
6149 // - We can combine the transition with its single use
6150 // => we got rid of the transition.
6151 // - We escape the current basic block
6152 // => we would need to check that we are moving it at a cheaper place and
6153 // we do not do that for now.
6154 BasicBlock *Parent = Inst->getParent();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006155 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00006156 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006157 // If the transition has more than one use, assume this is not going to be
6158 // beneficial.
6159 while (Inst->hasOneUse()) {
6160 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006161 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006162
6163 if (ToBePromoted->getParent() != Parent) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006164 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
6165 << ToBePromoted->getParent()->getName()
6166 << ") than the transition (" << Parent->getName()
6167 << ").\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006168 return false;
6169 }
6170
6171 if (VPH.canCombine(ToBePromoted)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006172 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
6173 << "will be combined with: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006174 VPH.recordCombineInstruction(ToBePromoted);
6175 bool Changed = VPH.promote();
6176 NumStoreExtractExposed += Changed;
6177 return Changed;
6178 }
6179
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006180 LLVM_DEBUG(dbgs() << "Try promoting.\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006181 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6182 return false;
6183
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006184 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006185
6186 VPH.enqueueForPromotion(ToBePromoted);
6187 Inst = ToBePromoted;
6188 }
6189 return false;
6190}
6191
Wei Mia2f0b592016-12-22 19:44:45 +00006192/// For the instruction sequence of store below, F and I values
6193/// are bundled together as an i64 value before being stored into memory.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006194/// Sometimes it is more efficient to generate separate stores for F and I,
Wei Mia2f0b592016-12-22 19:44:45 +00006195/// which can remove the bitwise instructions or sink them to colder places.
6196///
6197/// (store (or (zext (bitcast F to i32) to i64),
6198/// (shl (zext I to i64), 32)), addr) -->
6199/// (store F, addr) and (store I, addr+4)
6200///
6201/// Similarly, splitting for other merged store can also be beneficial, like:
6202/// For pair of {i32, i32}, i64 store --> two i32 stores.
6203/// For pair of {i32, i16}, i64 store --> two i32 stores.
6204/// For pair of {i16, i16}, i32 store --> two i16 stores.
6205/// For pair of {i16, i8}, i32 store --> two i16 stores.
6206/// For pair of {i8, i8}, i16 store --> two i8 stores.
6207///
6208/// We allow each target to determine specifically which kind of splitting is
6209/// supported.
6210///
6211/// The store patterns are commonly seen from the simple code snippet below
6212/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
6213/// void goo(const std::pair<int, float> &);
6214/// hoo() {
6215/// ...
6216/// goo(std::make_pair(tmp, ftmp));
6217/// ...
6218/// }
6219///
6220/// Although we already have similar splitting in DAG Combine, we duplicate
6221/// it in CodeGenPrepare to catch the case in which pattern is across
6222/// multiple BBs. The logic in DAG Combine is kept to catch case generated
6223/// during code expansion.
6224static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
6225 const TargetLowering &TLI) {
6226 // Handle simple but common cases only.
6227 Type *StoreType = SI.getValueOperand()->getType();
6228 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6229 DL.getTypeSizeInBits(StoreType) == 0)
6230 return false;
6231
6232 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6233 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6234 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6235 DL.getTypeSizeInBits(SplitStoreType))
6236 return false;
6237
6238 // Match the following patterns:
6239 // (store (or (zext LValue to i64),
6240 // (shl (zext HValue to i64), 32)), HalfValBitSize)
6241 // or
6242 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6243 // (zext LValue to i64),
6244 // Expect both operands of OR and the first operand of SHL have only
6245 // one use.
6246 Value *LValue, *HValue;
6247 if (!match(SI.getValueOperand(),
6248 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6249 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6250 m_SpecificInt(HalfValBitSize))))))
6251 return false;
6252
6253 // Check LValue and HValue are int with size less or equal than 32.
6254 if (!LValue->getType()->isIntegerTy() ||
6255 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6256 !HValue->getType()->isIntegerTy() ||
6257 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6258 return false;
6259
6260 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6261 // as the input of target query.
6262 auto *LBC = dyn_cast<BitCastInst>(LValue);
6263 auto *HBC = dyn_cast<BitCastInst>(HValue);
6264 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6265 : EVT::getEVT(LValue->getType());
6266 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6267 : EVT::getEVT(HValue->getType());
6268 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6269 return false;
6270
6271 // Start to split store.
6272 IRBuilder<> Builder(SI.getContext());
6273 Builder.SetInsertPoint(&SI);
6274
6275 // If LValue/HValue is a bitcast in another BB, create a new one in current
6276 // BB so it may be merged with the splitted stores by dag combiner.
6277 if (LBC && LBC->getParent() != SI.getParent())
6278 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6279 if (HBC && HBC->getParent() != SI.getParent())
6280 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6281
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006282 bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
Wei Mia2f0b592016-12-22 19:44:45 +00006283 auto CreateSplitStore = [&](Value *V, bool Upper) {
6284 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6285 Value *Addr = Builder.CreateBitCast(
6286 SI.getOperand(1),
6287 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006288 if ((IsLE && Upper) || (!IsLE && !Upper))
Wei Mia2f0b592016-12-22 19:44:45 +00006289 Addr = Builder.CreateGEP(
6290 SplitStoreType, Addr,
6291 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6292 Builder.CreateAlignedStore(
6293 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6294 };
6295
6296 CreateSplitStore(LValue, false);
6297 CreateSplitStore(HValue, true);
6298
6299 // Delete the old store.
6300 SI.eraseFromParent();
6301 return true;
6302}
6303
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006304// Return true if the GEP has two operands, the first operand is of a sequential
6305// type, and the second operand is a constant.
6306static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6307 gep_type_iterator I = gep_type_begin(*GEP);
6308 return GEP->getNumOperands() == 2 &&
6309 I.isSequential() &&
6310 isa<ConstantInt>(GEP->getOperand(1));
6311}
6312
6313// Try unmerging GEPs to reduce liveness interference (register pressure) across
6314// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6315// reducing liveness interference across those edges benefits global register
6316// allocation. Currently handles only certain cases.
6317//
6318// For example, unmerge %GEPI and %UGEPI as below.
6319//
6320// ---------- BEFORE ----------
6321// SrcBlock:
6322// ...
6323// %GEPIOp = ...
6324// ...
6325// %GEPI = gep %GEPIOp, Idx
6326// ...
6327// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6328// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6329// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6330// %UGEPI)
6331//
6332// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6333// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6334// ...
6335//
6336// DstBi:
6337// ...
6338// %UGEPI = gep %GEPIOp, UIdx
6339// ...
6340// ---------------------------
6341//
6342// ---------- AFTER ----------
6343// SrcBlock:
6344// ... (same as above)
6345// (* %GEPI is still alive on the indirectbr edges)
6346// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6347// unmerging)
6348// ...
6349//
6350// DstBi:
6351// ...
6352// %UGEPI = gep %GEPI, (UIdx-Idx)
6353// ...
6354// ---------------------------
6355//
6356// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6357// no longer alive on them.
6358//
6359// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6360// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6361// not to disable further simplications and optimizations as a result of GEP
6362// merging.
6363//
6364// Note this unmerging may increase the length of the data flow critical path
6365// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6366// between the register pressure and the length of data-flow critical
6367// path. Restricting this to the uncommon IndirectBr case would minimize the
6368// impact of potentially longer critical path, if any, and the impact on compile
6369// time.
6370static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6371 const TargetTransformInfo *TTI) {
6372 BasicBlock *SrcBlock = GEPI->getParent();
6373 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6374 // (non-IndirectBr) cases exit early here.
6375 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6376 return false;
6377 // Check that GEPI is a simple gep with a single constant index.
6378 if (!GEPSequentialConstIndexed(GEPI))
6379 return false;
6380 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6381 // Check that GEPI is a cheap one.
6382 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6383 > TargetTransformInfo::TCC_Basic)
6384 return false;
6385 Value *GEPIOp = GEPI->getOperand(0);
6386 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6387 if (!isa<Instruction>(GEPIOp))
6388 return false;
6389 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6390 if (GEPIOpI->getParent() != SrcBlock)
6391 return false;
6392 // Check that GEP is used outside the block, meaning it's alive on the
6393 // IndirectBr edge(s).
6394 if (find_if(GEPI->users(), [&](User *Usr) {
6395 if (auto *I = dyn_cast<Instruction>(Usr)) {
6396 if (I->getParent() != SrcBlock) {
6397 return true;
6398 }
6399 }
6400 return false;
6401 }) == GEPI->users().end())
6402 return false;
6403 // The second elements of the GEP chains to be unmerged.
6404 std::vector<GetElementPtrInst *> UGEPIs;
6405 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6406 // on IndirectBr edges.
6407 for (User *Usr : GEPIOp->users()) {
6408 if (Usr == GEPI) continue;
6409 // Check if Usr is an Instruction. If not, give up.
6410 if (!isa<Instruction>(Usr))
6411 return false;
6412 auto *UI = cast<Instruction>(Usr);
6413 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6414 if (UI->getParent() == SrcBlock)
6415 continue;
6416 // Check if Usr is a GEP. If not, give up.
6417 if (!isa<GetElementPtrInst>(Usr))
6418 return false;
6419 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6420 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6421 // the pointer operand to it. If so, record it in the vector. If not, give
6422 // up.
6423 if (!GEPSequentialConstIndexed(UGEPI))
6424 return false;
6425 if (UGEPI->getOperand(0) != GEPIOp)
6426 return false;
6427 if (GEPIIdx->getType() !=
6428 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6429 return false;
6430 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6431 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6432 > TargetTransformInfo::TCC_Basic)
6433 return false;
6434 UGEPIs.push_back(UGEPI);
6435 }
6436 if (UGEPIs.size() == 0)
6437 return false;
6438 // Check the materializing cost of (Uidx-Idx).
6439 for (GetElementPtrInst *UGEPI : UGEPIs) {
6440 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6441 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6442 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6443 if (ImmCost > TargetTransformInfo::TCC_Basic)
6444 return false;
6445 }
6446 // Now unmerge between GEPI and UGEPIs.
6447 for (GetElementPtrInst *UGEPI : UGEPIs) {
6448 UGEPI->setOperand(0, GEPI);
6449 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6450 Constant *NewUGEPIIdx =
6451 ConstantInt::get(GEPIIdx->getType(),
6452 UGEPIIdx->getValue() - GEPIIdx->getValue());
6453 UGEPI->setOperand(1, NewUGEPIIdx);
6454 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6455 // inbounds to avoid UB.
6456 if (!GEPI->isInBounds()) {
6457 UGEPI->setIsInBounds(false);
6458 }
6459 }
6460 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6461 // alive on IndirectBr edges).
6462 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6463 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6464 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6465 return true;
6466}
6467
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006468bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00006469 // Bail out if we inserted the instruction to prevent optimizations from
6470 // stepping on each other's toes.
6471 if (InsertedInsts.count(I))
6472 return false;
6473
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006474 if (PHINode *P = dyn_cast<PHINode>(I)) {
6475 // It is possible for very late stage optimizations (such as SimplifyCFG)
6476 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6477 // trivial PHI, go ahead and zap it here.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00006478 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006479 P->replaceAllUsesWith(V);
6480 P->eraseFromParent();
6481 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00006482 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006483 }
Chris Lattneree588de2011-01-15 07:29:01 +00006484 return false;
6485 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006486
Chris Lattneree588de2011-01-15 07:29:01 +00006487 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006488 // If the source of the cast is a constant, then this should have
6489 // already been constant folded. The only reason NOT to constant fold
6490 // it is if something (e.g. LSR) was careful to place the constant
6491 // evaluation in a block other than then one that uses it (e.g. to hoist
6492 // the address of globals out of a loop). If this is the case, we don't
6493 // want to forward-subst the cast.
6494 if (isa<Constant>(CI->getOperand(0)))
6495 return false;
6496
Mehdi Amini44ede332015-07-09 02:09:04 +00006497 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00006498 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006499
Chris Lattneree588de2011-01-15 07:29:01 +00006500 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006501 /// Sink a zext or sext into its user blocks if the target type doesn't
6502 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00006503 if (TLI &&
6504 TLI->getTypeAction(CI->getContext(),
6505 TLI->getValueType(*DL, CI->getType())) ==
6506 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006507 return SinkCast(CI);
6508 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00006509 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00006510 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006511 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006512 }
Chris Lattneree588de2011-01-15 07:29:01 +00006513 return false;
6514 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006515
Chris Lattneree588de2011-01-15 07:29:01 +00006516 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00006517 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00006518 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00006519
Chris Lattneree588de2011-01-15 07:29:01 +00006520 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006521 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006522 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006523 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006524 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006525 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6526 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006527 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006528 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006529 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006530
Chris Lattneree588de2011-01-15 07:29:01 +00006531 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006532 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6533 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006534 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006535 if (TLI) {
6536 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006537 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006538 SI->getOperand(0)->getType(), AS);
6539 }
Chris Lattneree588de2011-01-15 07:29:01 +00006540 return false;
6541 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006542
Matt Arsenault02d915b2017-03-15 22:35:20 +00006543 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6544 unsigned AS = RMW->getPointerAddressSpace();
6545 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6546 RMW->getType(), AS);
6547 }
6548
6549 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6550 unsigned AS = CmpX->getPointerAddressSpace();
6551 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6552 CmpX->getCompareOperand()->getType(), AS);
6553 }
6554
Yi Jiangd069f632014-04-21 19:34:27 +00006555 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6556
Geoff Berry5d534b62017-02-21 18:53:14 +00006557 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6558 EnableAndCmpSinking && TLI)
6559 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6560
Yi Jiangd069f632014-04-21 19:34:27 +00006561 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6562 BinOp->getOpcode() == Instruction::LShr)) {
6563 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6564 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006565 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006566
6567 return false;
6568 }
6569
Chris Lattneree588de2011-01-15 07:29:01 +00006570 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006571 if (GEPI->hasAllZeroIndices()) {
6572 /// The GEP operand must be a pointer, so must its result -> BitCast
6573 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6574 GEPI->getName(), GEPI);
Vedant Kumar40399a22018-05-24 23:00:21 +00006575 NC->setDebugLoc(GEPI->getDebugLoc());
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006576 GEPI->replaceAllUsesWith(NC);
6577 GEPI->eraseFromParent();
6578 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00006579 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00006580 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006581 }
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006582 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
6583 return true;
6584 }
Chris Lattneree588de2011-01-15 07:29:01 +00006585 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006586 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006587
Chris Lattneree588de2011-01-15 07:29:01 +00006588 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006589 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006590
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006591 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006592 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006593
Tim Northoveraeb8e062014-02-19 10:02:43 +00006594 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006595 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006596
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006597 if (auto *Switch = dyn_cast<SwitchInst>(I))
6598 return optimizeSwitchInst(Switch);
6599
Quentin Colombetc32615d2014-10-31 17:52:53 +00006600 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006601 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006602
Chris Lattneree588de2011-01-15 07:29:01 +00006603 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006604}
6605
James Molloyf01488e2016-01-15 09:20:19 +00006606/// Given an OR instruction, check to see if this is a bitreverse
6607/// idiom. If so, insert the new intrinsic and return true.
6608static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6609 const TargetLowering &TLI) {
6610 if (!I.getType()->isIntegerTy() ||
6611 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6612 TLI.getValueType(DL, I.getType(), true)))
6613 return false;
6614
6615 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00006616 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00006617 return false;
6618 Instruction *LastInst = Insts.back();
6619 I.replaceAllUsesWith(LastInst);
6620 RecursivelyDeleteTriviallyDeadInstructions(&I);
6621 return true;
6622}
6623
Chris Lattnerf2836d12007-03-31 04:06:36 +00006624// In this pass we look for GEP and cast instructions that are used
6625// across basic blocks and rewrite them to improve basic-block-at-a-time
6626// selection.
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006627bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00006628 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00006629 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00006630
Chris Lattner7a277142011-01-15 07:14:54 +00006631 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006632 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006633 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006634 if (ModifiedDT)
6635 return true;
6636 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00006637
James Molloyf01488e2016-01-15 09:20:19 +00006638 bool MadeBitReverse = true;
6639 while (TLI && MadeBitReverse) {
6640 MadeBitReverse = false;
6641 for (auto &I : reverse(BB)) {
6642 if (makeBitReverse(I, *DL, *TLI)) {
6643 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00006644 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00006645 break;
6646 }
6647 }
6648 }
James Molloy3ef84c42016-01-15 10:36:01 +00006649 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00006650
Chris Lattnerf2836d12007-03-31 04:06:36 +00006651 return MadeChange;
6652}
Devang Patel53771ba2011-08-18 00:50:51 +00006653
6654// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00006655// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00006656// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006657bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00006658 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006659 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00006660 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006661 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006662 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00006663 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00006664 // Leave dbg.values that refer to an alloca alone. These
Craig Topper87e715f2017-11-07 20:56:17 +00006665 // intrinsics describe the address of a variable (= the alloca)
Adrian Prantl32da8892014-04-25 20:49:25 +00006666 // being taken. They should not be moved next to the alloca
6667 // (and to the beginning of the scope), but rather stay close to
6668 // where said address is used.
6669 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00006670 PrevNonDbgInst = Insn;
6671 continue;
6672 }
6673
6674 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6675 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00006676 // If VI is a phi in a block with an EHPad terminator, we can't insert
6677 // after it.
6678 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6679 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006680 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
6681 << *DVI << ' ' << *VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006682 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00006683 if (isa<PHINode>(VI))
6684 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6685 else
6686 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006687 MadeChange = true;
6688 ++NumDbgValueMoved;
6689 }
6690 }
6691 }
6692 return MadeChange;
6693}
Tim Northovercea0abb2014-03-29 08:22:29 +00006694
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006695/// Scale down both weights to fit into uint32_t.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006696static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6697 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006698 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006699 NewTrue = NewTrue / Scale;
6700 NewFalse = NewFalse / Scale;
6701}
6702
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006703/// Some targets prefer to split a conditional branch like:
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006704/// \code
6705/// %0 = icmp ne i32 %a, 0
6706/// %1 = icmp ne i32 %b, 0
6707/// %or.cond = or i1 %0, %1
6708/// br i1 %or.cond, label %TrueBB, label %FalseBB
6709/// \endcode
6710/// into multiple branch instructions like:
6711/// \code
6712/// bb1:
6713/// %0 = icmp ne i32 %a, 0
6714/// br i1 %0, label %TrueBB, label %bb2
6715/// bb2:
6716/// %1 = icmp ne i32 %b, 0
6717/// br i1 %1, label %TrueBB, label %FalseBB
6718/// \endcode
6719/// This usually allows instruction selection to do even further optimizations
6720/// and combine the compare with the branch instruction. Currently this is
6721/// applied for targets which have "cheap" jump instructions.
6722///
6723/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6724///
6725bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006726 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006727 return false;
6728
6729 bool MadeChange = false;
6730 for (auto &BB : F) {
6731 // Does this BB end with the following?
6732 // %cond1 = icmp|fcmp|binary instruction ...
6733 // %cond2 = icmp|fcmp|binary instruction ...
6734 // %cond.or = or|and i1 %cond1, cond2
6735 // br i1 %cond.or label %dest1, label %dest2"
6736 BinaryOperator *LogicOp;
6737 BasicBlock *TBB, *FBB;
6738 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6739 continue;
6740
Sanjay Patel42574202015-09-02 19:23:23 +00006741 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6742 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6743 continue;
6744
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006745 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006746 Value *Cond1, *Cond2;
6747 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6748 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006749 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006750 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6751 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006752 Opc = Instruction::Or;
6753 else
6754 continue;
6755
6756 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6757 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6758 continue;
6759
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006760 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006761
6762 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00006763 auto TmpBB =
6764 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6765 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006766
6767 // Update original basic block by using the first condition directly by the
6768 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006769 Br1->setCondition(Cond1);
6770 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006771
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006772 // Depending on the condition we have to either replace the true or the
6773 // false successor of the original branch instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006774 if (Opc == Instruction::And)
6775 Br1->setSuccessor(0, TmpBB);
6776 else
6777 Br1->setSuccessor(1, TmpBB);
6778
6779 // Fill in the new basic block.
6780 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006781 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6782 I->removeFromParent();
6783 I->insertBefore(Br2);
6784 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006785
6786 // Update PHI nodes in both successors. The original BB needs to be
Hiroshi Inoue6a391bb2017-06-27 10:35:37 +00006787 // replaced in one successor's PHI nodes, because the branch comes now from
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006788 // the newly generated BB (NewBB). In the other successor we need to add one
6789 // incoming edge to the PHI nodes, because both branch instructions target
6790 // now the same successor. Depending on the original branch condition
6791 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006792 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006793 // This doesn't change the successor order of the just created branch
6794 // instruction (or any other instruction).
6795 if (Opc == Instruction::Or)
6796 std::swap(TBB, FBB);
6797
6798 // Replace the old BB with the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006799 for (PHINode &PN : TBB->phis()) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006800 int i;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006801 while ((i = PN.getBasicBlockIndex(&BB)) >= 0)
6802 PN.setIncomingBlock(i, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006803 }
6804
6805 // Add another incoming edge form the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006806 for (PHINode &PN : FBB->phis()) {
6807 auto *Val = PN.getIncomingValueForBlock(&BB);
6808 PN.addIncoming(Val, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006809 }
6810
6811 // Update the branch weights (from SelectionDAGBuilder::
6812 // FindMergedConditions).
6813 if (Opc == Instruction::Or) {
6814 // Codegen X | Y as:
6815 // BB1:
6816 // jmp_if_X TBB
6817 // jmp TmpBB
6818 // TmpBB:
6819 // jmp_if_Y TBB
6820 // jmp FBB
6821 //
6822
6823 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6824 // The requirement is that
6825 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006826 // = TrueProb for original BB.
6827 // Assuming the original weights are A and B, one choice is to set BB1's
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006828 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6829 // assumes that
6830 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6831 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6832 // TmpBB, but the math is more complicated.
6833 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006834 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006835 uint64_t NewTrueWeight = TrueWeight;
6836 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6837 scaleWeights(NewTrueWeight, NewFalseWeight);
6838 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6839 .createBranchWeights(TrueWeight, FalseWeight));
6840
6841 NewTrueWeight = TrueWeight;
6842 NewFalseWeight = 2 * FalseWeight;
6843 scaleWeights(NewTrueWeight, NewFalseWeight);
6844 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6845 .createBranchWeights(TrueWeight, FalseWeight));
6846 }
6847 } else {
6848 // Codegen X & Y as:
6849 // BB1:
6850 // jmp_if_X TmpBB
6851 // jmp FBB
6852 // TmpBB:
6853 // jmp_if_Y TBB
6854 // jmp FBB
6855 //
6856 // This requires creation of TmpBB after CurBB.
6857
6858 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6859 // The requirement is that
6860 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006861 // = FalseProb for original BB.
6862 // Assuming the original weights are A and B, one choice is to set BB1's
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006863 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6864 // assumes that
6865 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6866 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006867 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006868 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6869 uint64_t NewFalseWeight = FalseWeight;
6870 scaleWeights(NewTrueWeight, NewFalseWeight);
6871 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6872 .createBranchWeights(TrueWeight, FalseWeight));
6873
6874 NewTrueWeight = 2 * TrueWeight;
6875 NewFalseWeight = FalseWeight;
6876 scaleWeights(NewTrueWeight, NewFalseWeight);
6877 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6878 .createBranchWeights(TrueWeight, FalseWeight));
6879 }
6880 }
6881
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006882 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00006883 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006884 ModifiedDT = true;
6885
6886 MadeChange = true;
6887
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006888 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6889 TmpBB->dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006890 }
6891 return MadeChange;
6892}