blob: 7d7d48b12ce8e8d95728424af0aecdbc9af0c027 [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
Guozhi Wei8c17f9a2018-08-15 22:08:26 +0000226enum ExtType {
227 ZeroExtension, // Zero extension has been seen.
228 SignExtension, // Sign extension has been seen.
229 BothExtension // This extension type is used if we saw sext after
230 // ZeroExtension had been set, or if we saw zext after
231 // SignExtension had been set. It makes the type
232 // information of a promoted instruction invalid.
233};
234
Eugene Zelenko900b6332017-08-29 22:32:07 +0000235using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
Guozhi Wei8c17f9a2018-08-15 22:08:26 +0000236using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000237using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
238using SExts = SmallVector<Instruction *, 16>;
239using ValueToSExts = DenseMap<Value *, SExts>;
240
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000241class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000242
Chris Lattner2dd09db2009-09-02 06:11:42 +0000243 class CodeGenPrepare : public FunctionPass {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000244 const TargetMachine *TM = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000245 const TargetSubtargetInfo *SubtargetInfo;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000246 const TargetLowering *TLI = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000247 const TargetRegisterInfo *TRI;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000248 const TargetTransformInfo *TTI = nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000249 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000250 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000251 std::unique_ptr<BlockFrequencyInfo> BFI;
252 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000253
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000254 /// As we scan instructions optimizing them, this is the next instruction
255 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000256 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000257
Evan Cheng0663f232011-03-21 01:19:09 +0000258 /// Keeps track of non-local addresses that have been sunk into a block.
259 /// This allows us to avoid inserting duplicate code for blocks with
Simon Dardis230f4532017-11-24 16:45:28 +0000260 /// multiple load/stores of the same address. The usage of WeakTrackingVH
261 /// enables SunkAddrs to be treated as a cache whose entries can be
262 /// invalidated if a sunken address computation has been erased.
263 ValueMap<Value*, WeakTrackingVH> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000264
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000265 /// Keeps track of all instructions inserted for the current function.
266 SetOfInstrs InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000267
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000268 /// Keeps track of the type of the related instruction before their
269 /// promotion for the current function.
270 InstrToOrigTy PromotedInsts;
271
Jun Bum Limdee55652017-04-03 19:20:07 +0000272 /// Keep track of instructions removed during promotion.
273 SetOfInstrs RemovedInsts;
274
275 /// Keep track of sext chains based on their initial value.
276 DenseMap<Value *, Instruction *> SeenChainsForSExt;
277
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000278 /// Keep track of GEPs accessing the same data structures such as structs or
279 /// arrays that are candidates to be split later because of their large
280 /// size.
281 DenseMap<
282 AssertingVH<Value>,
283 SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
284 LargeOffsetGEPMap;
285
286 /// Keep track of new GEP base after splitting the GEPs having large offset.
287 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
288
289 /// Map serial numbers to Large offset GEPs.
290 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
291
Jun Bum Limdee55652017-04-03 19:20:07 +0000292 /// Keep track of SExt promoted.
293 ValueToSExts ValToSExtendedUses;
294
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000295 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000296 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000297
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000298 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000299 bool OptSize;
300
Mehdi Amini4fe37982015-07-07 18:45:17 +0000301 /// DataLayout for the Function being processed.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000302 const DataLayout *DL = nullptr;
Mehdi Amini4fe37982015-07-07 18:45:17 +0000303
Chris Lattnerf2836d12007-03-31 04:06:36 +0000304 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000305 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000306
307 CodeGenPrepare() : FunctionPass(ID) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000308 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
309 }
Eugene Zelenko900b6332017-08-29 22:32:07 +0000310
Craig Topper4584cd52014-03-07 09:26:03 +0000311 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000312
Mehdi Amini117296c2016-10-01 02:56:57 +0000313 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000314
Craig Topper4584cd52014-03-07 09:26:03 +0000315 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000316 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000317 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000318 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000319 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000320 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000321 }
322
Chris Lattnerf2836d12007-03-31 04:06:36 +0000323 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000324 bool eliminateFallThrough(Function &F);
325 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000326 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000327 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
328 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000329 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
330 bool isPreheader);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000331 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
332 bool optimizeInst(Instruction *I, bool &ModifiedDT);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000333 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
334 Type *AccessTy, unsigned AddrSpace);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000335 bool optimizeInlineAsmInst(CallInst *CS);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000336 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000337 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000338 bool optimizeExtUses(Instruction *I);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000339 bool optimizeLoadExt(LoadInst *Load);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000340 bool optimizeSelectInst(SelectInst *SI);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000341 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
342 bool optimizeSwitchInst(SwitchInst *SI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000343 bool optimizeExtractElementInst(Instruction *Inst);
344 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
345 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000346 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
347 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
348 bool tryToPromoteExts(TypePromotionTransaction &TPT,
349 const SmallVectorImpl<Instruction *> &Exts,
350 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
351 unsigned CreatedInstsCost = 0);
Jun Bum Limdee55652017-04-03 19:20:07 +0000352 bool mergeSExts(Function &F);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000353 bool splitLargeGEPOffsets();
Jun Bum Limdee55652017-04-03 19:20:07 +0000354 bool performAddressTypePromotion(
355 Instruction *&Inst,
356 bool AllowPromotionWithoutCommonHeader,
357 bool HasPromoted, TypePromotionTransaction &TPT,
358 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000359 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000360 bool simplifyOffsetableRelocate(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000361 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000362
363} // end anonymous namespace
Devang Patel09f162c2007-05-01 21:15:47 +0000364
Devang Patel8c78a0b2007-05-03 01:11:54 +0000365char CodeGenPrepare::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000366
Matthias Braun1527baa2017-05-25 21:26:32 +0000367INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000368 "Optimize for code generation", false, false)
Dehao Chen302b69c2016-10-18 20:42:47 +0000369INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000370INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000371 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000372
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000373FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000374
Chris Lattnerf2836d12007-03-31 04:06:36 +0000375bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000376 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000377 return false;
378
Mehdi Amini4fe37982015-07-07 18:45:17 +0000379 DL = &F.getParent()->getDataLayout();
380
Chris Lattnerf2836d12007-03-31 04:06:36 +0000381 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000382 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000383 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000384 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000385
Devang Patel8f606d72011-03-24 15:35:25 +0000386 ModifiedDT = false;
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000387 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
388 TM = &TPC->getTM<TargetMachine>();
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000389 SubtargetInfo = TM->getSubtargetImpl(F);
390 TLI = SubtargetInfo->getTargetLowering();
391 TRI = SubtargetInfo->getRegisterInfo();
392 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000393 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000394 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000395 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000396 BPI.reset(new BranchProbabilityInfo(F, *LI));
397 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000398 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000399
Easwaran Raman0d55b552017-11-14 19:31:51 +0000400 ProfileSummaryInfo *PSI =
401 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen302b69c2016-10-18 20:42:47 +0000402 if (ProfileGuidedSectionPrefix) {
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000403 if (PSI->isFunctionHotInCallGraph(&F, *BFI))
Dehao Chen302b69c2016-10-18 20:42:47 +0000404 F.setSectionPrefix(".hot");
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000405 else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
Teresa Johnson720d9b42017-05-09 01:43:24 +0000406 F.setSectionPrefix(".unlikely");
Dehao Chen302b69c2016-10-18 20:42:47 +0000407 }
408
Preston Gurdcdf540d2012-09-04 18:22:17 +0000409 /// This optimization identifies DIV instructions that can be
410 /// profitably bypassed and carried out with a shorter, faster divide.
Easwaran Raman0d55b552017-11-14 19:31:51 +0000411 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
412 TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000413 const DenseMap<unsigned int, unsigned int> &BypassWidths =
414 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000415 BasicBlock* BB = &*F.begin();
416 while (BB != nullptr) {
417 // bypassSlowDivision may create new BBs, but we don't want to reapply the
418 // optimization to those blocks.
419 BasicBlock* Next = BB->getNextNode();
420 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
421 BB = Next;
422 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000423 }
424
425 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000426 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000427 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000428
Devang Patel53771ba2011-08-18 00:50:51 +0000429 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000430 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000431 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000432 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000433
Geoff Berry5d534b62017-02-21 18:53:14 +0000434 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000435 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000436
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000437 // Split some critical edges where one of the sources is an indirect branch,
438 // to help generate sane code for PHIs involving such edges.
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000439 EverMadeChange |= SplitIndirectBrCriticalEdges(F);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000440
Chris Lattnerc3748562007-04-02 01:35:34 +0000441 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000442 while (MadeChange) {
443 MadeChange = false;
Jun Bum Limdee55652017-04-03 19:20:07 +0000444 SeenChainsForSExt.clear();
445 ValToSExtendedUses.clear();
446 RemovedInsts.clear();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000447 LargeOffsetGEPMap.clear();
448 LargeOffsetGEPID.clear();
Hans Wennborg02fbc712012-09-19 07:48:16 +0000449 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000450 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000451 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000452 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000453
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000454 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000455 if (ModifiedDTOnIteration)
456 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000457 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000458 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
459 MadeChange |= mergeSExts(F);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000460 if (!LargeOffsetGEPMap.empty())
461 MadeChange |= splitLargeGEPOffsets();
Jun Bum Limdee55652017-04-03 19:20:07 +0000462
463 // Really free removed instructions during promotion.
464 for (Instruction *I : RemovedInsts)
Reid Kleckner96ab8722017-05-18 17:24:10 +0000465 I->deleteValue();
Jun Bum Limdee55652017-04-03 19:20:07 +0000466
Chris Lattnerf2836d12007-03-31 04:06:36 +0000467 EverMadeChange |= MadeChange;
468 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000469
470 SunkAddrs.clear();
471
Cameron Zwarich338d3622011-03-11 21:52:04 +0000472 if (!DisableBranchOpts) {
473 MadeChange = false;
David Stenberg23bba562018-07-02 14:23:48 +0000474 // Use a set vector to get deterministic iteration order. The order the
475 // blocks are removed may affect whether or not PHI nodes in successors
476 // are removed.
477 SmallSetVector<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000478 for (BasicBlock &BB : F) {
479 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
480 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000481 if (!MadeChange) continue;
482
483 for (SmallVectorImpl<BasicBlock*>::iterator
484 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
485 if (pred_begin(*II) == pred_end(*II))
486 WorkList.insert(*II);
487 }
488
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000489 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000490 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000491 while (!WorkList.empty()) {
David Stenberg23bba562018-07-02 14:23:48 +0000492 BasicBlock *BB = WorkList.pop_back_val();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000493 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
494
495 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000496
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000497 for (SmallVectorImpl<BasicBlock*>::iterator
498 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
499 if (pred_begin(*II) == pred_end(*II))
500 WorkList.insert(*II);
501 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000502
Nadav Rotem70409992012-08-14 05:19:07 +0000503 // Merge pairs of basic blocks with unconditional branches, connected by
504 // a single edge.
505 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000506 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000507
Cameron Zwarich338d3622011-03-11 21:52:04 +0000508 EverMadeChange |= MadeChange;
509 }
510
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000511 if (!DisableGCOpts) {
512 SmallVector<Instruction *, 2> Statepoints;
513 for (BasicBlock &BB : F)
514 for (Instruction &I : BB)
515 if (isStatepoint(I))
516 Statepoints.push_back(&I);
517 for (auto &I : Statepoints)
518 EverMadeChange |= simplifyOffsetableRelocate(*I);
519 }
520
Chris Lattnerf2836d12007-03-31 04:06:36 +0000521 return EverMadeChange;
522}
523
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000524/// Merge basic blocks which are connected by a single edge, where one of the
525/// basic blocks has a single successor pointing to the other basic block,
526/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000527bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000528 bool Changed = false;
529 // Scan all of the blocks in the function, except for the entry block.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000530 // Use a temporary array to avoid iterator being invalidated when
531 // deleting blocks.
532 SmallVector<WeakTrackingVH, 16> Blocks;
533 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
534 Blocks.push_back(&Block);
535
536 for (auto &Block : Blocks) {
537 auto *BB = cast_or_null<BasicBlock>(Block);
538 if (!BB)
539 continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000540 // If the destination block has a single pred, then this is a trivial
541 // edge, just collapse it.
542 BasicBlock *SinglePred = BB->getSinglePredecessor();
543
Evan Cheng64a223a2012-09-28 23:58:57 +0000544 // Don't merge if BB's address is taken.
545 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000546
547 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
548 if (Term && !Term->isConditional()) {
549 Changed = true;
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000550 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000551
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000552 // Merge BB into SinglePred and delete it.
553 MergeBlockIntoPredecessor(BB);
Nadav Rotem70409992012-08-14 05:19:07 +0000554 }
555 }
556 return Changed;
557}
558
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000559/// Find a destination block from BB if BB is mergeable empty block.
560BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
561 // If this block doesn't end with an uncond branch, ignore it.
562 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
563 if (!BI || !BI->isUnconditional())
564 return nullptr;
565
566 // If the instruction before the branch (skipping debug info) isn't a phi
567 // node, then other stuff is happening here.
568 BasicBlock::iterator BBI = BI->getIterator();
569 if (BBI != BB->begin()) {
570 --BBI;
571 while (isa<DbgInfoIntrinsic>(BBI)) {
572 if (BBI == BB->begin())
573 break;
574 --BBI;
575 }
576 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
577 return nullptr;
578 }
579
580 // Do not break infinite loops.
581 BasicBlock *DestBB = BI->getSuccessor(0);
582 if (DestBB == BB)
583 return nullptr;
584
585 if (!canMergeBlocks(BB, DestBB))
586 DestBB = nullptr;
587
588 return DestBB;
589}
590
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000591/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
592/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
593/// edges in ways that are non-optimal for isel. Start by eliminating these
594/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000595bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000596 SmallPtrSet<BasicBlock *, 16> Preheaders;
597 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
598 while (!LoopList.empty()) {
599 Loop *L = LoopList.pop_back_val();
600 LoopList.insert(LoopList.end(), L->begin(), L->end());
601 if (BasicBlock *Preheader = L->getLoopPreheader())
602 Preheaders.insert(Preheader);
603 }
604
Chris Lattnerc3748562007-04-02 01:35:34 +0000605 bool MadeChange = false;
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000606 // Copy blocks into a temporary array to avoid iterator invalidation issues
607 // as we remove them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000608 // Note that this intentionally skips the entry block.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000609 SmallVector<WeakTrackingVH, 16> Blocks;
610 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
611 Blocks.push_back(&Block);
612
613 for (auto &Block : Blocks) {
614 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
615 if (!BB)
616 continue;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000617 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
618 if (!DestBB ||
619 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000620 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000621
Sanjay Patelfc580a62015-09-21 23:03:16 +0000622 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000623 MadeChange = true;
624 }
625 return MadeChange;
626}
627
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000628bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
629 BasicBlock *DestBB,
630 bool isPreheader) {
631 // Do not delete loop preheaders if doing so would create a critical edge.
632 // Loop preheaders can be good locations to spill registers. If the
633 // preheader is deleted and we create a critical edge, registers may be
634 // spilled in the loop body instead.
635 if (!DisablePreheaderProtect && isPreheader &&
636 !(BB->getSinglePredecessor() &&
637 BB->getSinglePredecessor()->getSingleSuccessor()))
638 return false;
639
640 // Try to skip merging if the unique predecessor of BB is terminated by a
641 // switch or indirect branch instruction, and BB is used as an incoming block
642 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
643 // add COPY instructions in the predecessor of BB instead of BB (if it is not
644 // merged). Note that the critical edge created by merging such blocks wont be
645 // split in MachineSink because the jump table is not analyzable. By keeping
646 // such empty block (BB), ISel will place COPY instructions in BB, not in the
647 // predecessor of BB.
648 BasicBlock *Pred = BB->getUniquePredecessor();
649 if (!Pred ||
650 !(isa<SwitchInst>(Pred->getTerminator()) ||
651 isa<IndirectBrInst>(Pred->getTerminator())))
652 return true;
653
Jonas Devlieghere42243df2018-08-07 12:14:01 +0000654 if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000655 return true;
656
657 // We use a simple cost heuristic which determine skipping merging is
658 // profitable if the cost of skipping merging is less than the cost of
659 // merging : Cost(skipping merging) < Cost(merging BB), where the
660 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
661 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
662 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
663 // Freq(Pred) / Freq(BB) > 2.
664 // Note that if there are multiple empty blocks sharing the same incoming
665 // value for the PHIs in the DestBB, we consider them together. In such
666 // case, Cost(merging BB) will be the sum of their frequencies.
667
668 if (!isa<PHINode>(DestBB->begin()))
669 return true;
670
671 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
672
673 // Find all other incoming blocks from which incoming values of all PHIs in
674 // DestBB are the same as the ones from BB.
675 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
676 ++PI) {
677 BasicBlock *DestBBPred = *PI;
678 if (DestBBPred == BB)
679 continue;
680
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000681 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
682 return DestPN.getIncomingValueForBlock(BB) ==
683 DestPN.getIncomingValueForBlock(DestBBPred);
684 }))
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000685 SameIncomingValueBBs.insert(DestBBPred);
686 }
687
688 // See if all BB's incoming values are same as the value from Pred. In this
689 // case, no reason to skip merging because COPYs are expected to be place in
690 // Pred already.
691 if (SameIncomingValueBBs.count(Pred))
692 return true;
693
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000694 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
695 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
696
697 for (auto SameValueBB : SameIncomingValueBBs)
698 if (SameValueBB->getUniquePredecessor() == Pred &&
699 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
700 BBFreq += BFI->getBlockFreq(SameValueBB);
701
702 return PredFreq.getFrequency() <=
703 BBFreq.getFrequency() * FreqRatioToSkipMerge;
704}
705
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000706/// Return true if we can merge BB into DestBB if there is a single
707/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000708/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000709bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000710 const BasicBlock *DestBB) const {
711 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
712 // the successor. If there are more complex condition (e.g. preheaders),
713 // don't mess around with them.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000714 for (const PHINode &PN : BB->phis()) {
715 for (const User *U : PN.users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000716 const Instruction *UI = cast<Instruction>(U);
717 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000718 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000719 // If User is inside DestBB block and it is a PHINode then check
720 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000721 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000722 if (UI->getParent() == DestBB) {
723 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000724 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
725 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
726 if (Insn && Insn->getParent() == BB &&
727 Insn->getParent() != UPN->getIncomingBlock(I))
728 return false;
729 }
730 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000731 }
732 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000733
Chris Lattnerc3748562007-04-02 01:35:34 +0000734 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
735 // and DestBB may have conflicting incoming values for the block. If so, we
736 // can't merge the block.
737 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
738 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000739
Chris Lattnerc3748562007-04-02 01:35:34 +0000740 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000741 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000742 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
743 // It is faster to get preds from a PHI than with pred_iterator.
744 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
745 BBPreds.insert(BBPN->getIncomingBlock(i));
746 } else {
747 BBPreds.insert(pred_begin(BB), pred_end(BB));
748 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000749
Chris Lattnerc3748562007-04-02 01:35:34 +0000750 // Walk the preds of DestBB.
751 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
752 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
753 if (BBPreds.count(Pred)) { // Common predecessor?
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000754 for (const PHINode &PN : DestBB->phis()) {
755 const Value *V1 = PN.getIncomingValueForBlock(Pred);
756 const Value *V2 = PN.getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000757
Chris Lattnerc3748562007-04-02 01:35:34 +0000758 // If V2 is a phi node in BB, look up what the mapped value will be.
759 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
760 if (V2PN->getParent() == BB)
761 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000762
Chris Lattnerc3748562007-04-02 01:35:34 +0000763 // If there is a conflict, bail out.
764 if (V1 != V2) return false;
765 }
766 }
767 }
768
769 return true;
770}
771
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000772/// Eliminate a basic block that has only phi's and an unconditional branch in
773/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000774void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000775 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
776 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000777
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000778 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
779 << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000780
Chris Lattnerc3748562007-04-02 01:35:34 +0000781 // If the destination block has a single pred, then this is a trivial edge,
782 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000783 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000784 if (SinglePred != DestBB) {
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000785 assert(SinglePred == BB &&
786 "Single predecessor not the same as predecessor");
787 // Merge DestBB into SinglePred/BB and delete it.
788 MergeBlockIntoPredecessor(DestBB);
789 // Note: BB(=SinglePred) will not be deleted on this path.
790 // DestBB(=its single successor) is the one that was deleted.
791 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000792 return;
793 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000794 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000795
Chris Lattnerc3748562007-04-02 01:35:34 +0000796 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
797 // to handle the new incoming edges it is about to have.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000798 for (PHINode &PN : DestBB->phis()) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000799 // Remove the incoming value for BB, and remember it.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000800 Value *InVal = PN.removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000801
Chris Lattnerc3748562007-04-02 01:35:34 +0000802 // Two options: either the InVal is a phi node defined in BB or it is some
803 // value that dominates BB.
804 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
805 if (InValPhi && InValPhi->getParent() == BB) {
806 // Add all of the input values of the input PHI as inputs of this phi.
807 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000808 PN.addIncoming(InValPhi->getIncomingValue(i),
809 InValPhi->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000810 } else {
811 // Otherwise, add one instance of the dominating value for each edge that
812 // we will be adding.
813 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
814 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000815 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000816 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000817 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000818 PN.addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000819 }
820 }
821 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000822
Chris Lattnerc3748562007-04-02 01:35:34 +0000823 // The PHIs are now updated, change everything that refers to BB to use
824 // DestBB and remove BB.
825 BB->replaceAllUsesWith(DestBB);
826 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000827 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000828
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000829 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000830}
831
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000832// Computes a map of base pointer relocation instructions to corresponding
833// derived pointer relocation instructions given a vector of all relocate calls
834static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000835 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
836 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
837 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000838 // Collect information in two maps: one primarily for locating the base object
839 // while filling the second map; the second map is the final structure holding
840 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000841 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
842 for (auto *ThisRelocate : AllRelocateCalls) {
843 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
844 ThisRelocate->getDerivedPtrIndex());
845 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000846 }
847 for (auto &Item : RelocateIdxMap) {
848 std::pair<unsigned, unsigned> Key = Item.first;
849 if (Key.first == Key.second)
850 // Base relocation: nothing to insert
851 continue;
852
Manuel Jacob83eefa62016-01-05 04:03:00 +0000853 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000854 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000855
856 // We're iterating over RelocateIdxMap so we cannot modify it.
857 auto MaybeBase = RelocateIdxMap.find(BaseKey);
858 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000859 // TODO: We might want to insert a new base object relocate and gep off
860 // that, if there are enough derived object relocates.
861 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000862
863 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000864 }
865}
866
867// Accepts a GEP and extracts the operands into a vector provided they're all
868// small integer constants
869static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
870 SmallVectorImpl<Value *> &OffsetV) {
871 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
872 // Only accept small constant integer operands
873 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
874 if (!Op || Op->getZExtValue() > 20)
875 return false;
876 }
877
878 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
879 OffsetV.push_back(GEP->getOperand(i));
880 return true;
881}
882
883// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
884// replace, computes a replacement, and affects it.
885static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000886simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
887 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000888 bool MadeChange = false;
Serguei Katkov9e5604d2017-08-17 05:48:30 +0000889 // We must ensure the relocation of derived pointer is defined after
890 // relocation of base pointer. If we find a relocation corresponding to base
891 // defined earlier than relocation of base then we move relocation of base
892 // right before found relocation. We consider only relocation in the same
893 // basic block as relocation of base. Relocations from other basic block will
894 // be skipped by optimization and we do not care about them.
895 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
896 &*R != RelocatedBase; ++R)
897 if (auto RI = dyn_cast<GCRelocateInst>(R))
898 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
899 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
900 RelocatedBase->moveBefore(RI);
901 break;
902 }
903
Manuel Jacob83eefa62016-01-05 04:03:00 +0000904 for (GCRelocateInst *ToReplace : Targets) {
905 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000906 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000907 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000908 // A duplicate relocate call. TODO: coalesce duplicates.
909 continue;
910 }
911
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000912 if (RelocatedBase->getParent() != ToReplace->getParent()) {
913 // Base and derived relocates are in different basic blocks.
914 // In this case transform is only valid when base dominates derived
915 // relocate. However it would be too expensive to check dominance
916 // for each such relocate, so we skip the whole transformation.
917 continue;
918 }
919
Manuel Jacob83eefa62016-01-05 04:03:00 +0000920 Value *Base = ToReplace->getBasePtr();
921 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000922 if (!Derived || Derived->getPointerOperand() != Base)
923 continue;
924
925 SmallVector<Value *, 2> OffsetV;
926 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
927 continue;
928
929 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000930 assert(RelocatedBase->getNextNode() &&
931 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000932
933 // Insert after RelocatedBase
934 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000935 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000936
937 // If gc_relocate does not match the actual type, cast it to the right type.
938 // In theory, there must be a bitcast after gc_relocate if the type does not
939 // match, and we should reuse it to get the derived pointer. But it could be
940 // cases like this:
941 // bb1:
942 // ...
943 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
944 // br label %merge
945 //
946 // bb2:
947 // ...
948 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
949 // br label %merge
950 //
951 // merge:
952 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
953 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
954 //
955 // In this case, we can not find the bitcast any more. So we insert a new bitcast
956 // no matter there is already one or not. In this way, we can handle all cases, and
957 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000958 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000959 if (RelocatedBase->getType() != Base->getType()) {
960 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000961 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000962 }
David Blaikie68d535c2015-03-24 22:38:16 +0000963 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000964 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000965 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000966 // If the newly generated derived pointer's type does not match the original derived
967 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000968 Value *ActualReplacement = Replacement;
969 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000970 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000971 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000972 }
973 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000974 ToReplace->eraseFromParent();
975
976 MadeChange = true;
977 }
978 return MadeChange;
979}
980
981// Turns this:
982//
983// %base = ...
984// %ptr = gep %base + 15
985// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
986// %base' = relocate(%tok, i32 4, i32 4)
987// %ptr' = relocate(%tok, i32 4, i32 5)
988// %val = load %ptr'
989//
990// into this:
991//
992// %base = ...
993// %ptr = gep %base + 15
994// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
995// %base' = gc.relocate(%tok, i32 4, i32 4)
996// %ptr' = gep %base' + 15
997// %val = load %ptr'
998bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
999 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +00001000 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001001
1002 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +00001003 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001004 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +00001005 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001006
1007 // We need atleast one base pointer relocation + one derived pointer
1008 // relocation to mangle
1009 if (AllRelocateCalls.size() < 2)
1010 return false;
1011
1012 // RelocateInstMap is a mapping from the base relocate instruction to the
1013 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +00001014 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001015 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1016 if (RelocateInstMap.empty())
1017 return false;
1018
1019 for (auto &Item : RelocateInstMap)
1020 // Item.first is the RelocatedBase to offset against
1021 // Item.second is the vector of Targets to replace
1022 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1023 return MadeChange;
1024}
1025
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001026/// SinkCast - Sink the specified cast instruction into its user blocks
1027static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001028 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001029
Chris Lattnerf2836d12007-03-31 04:06:36 +00001030 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001031 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001032
Chris Lattnerf2836d12007-03-31 04:06:36 +00001033 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001034 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001035 UI != E; ) {
1036 Use &TheUse = UI.getUse();
1037 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001038
Chris Lattnerf2836d12007-03-31 04:06:36 +00001039 // Figure out which BB this cast is used in. For PHI's this is the
1040 // appropriate predecessor block.
1041 BasicBlock *UserBB = User->getParent();
1042 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001043 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001044 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001045
Chris Lattnerf2836d12007-03-31 04:06:36 +00001046 // Preincrement use iterator so we don't invalidate it.
1047 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001048
David Majnemer0c80e2e2016-04-27 19:36:38 +00001049 // The first insertion point of a block containing an EH pad is after the
1050 // pad. If the pad is the user, we cannot sink the cast past the pad.
1051 if (User->isEHPad())
1052 continue;
1053
Andrew Kaylord0430e82015-11-23 19:16:15 +00001054 // If the block selected to receive the cast is an EH pad that does not
1055 // allow non-PHI instructions before the terminator, we can't sink the
1056 // cast.
1057 if (UserBB->getTerminator()->isEHPad())
1058 continue;
1059
Chris Lattnerf2836d12007-03-31 04:06:36 +00001060 // If this user is in the same block as the cast, don't change the cast.
1061 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001062
Chris Lattnerf2836d12007-03-31 04:06:36 +00001063 // If we have already inserted a cast into this block, use it.
1064 CastInst *&InsertedCast = InsertedCasts[UserBB];
1065
1066 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001067 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001068 assert(InsertPt != UserBB->end());
1069 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1070 CI->getType(), "", &*InsertPt);
Vedant Kumar9374c042018-05-23 22:03:48 +00001071 InsertedCast->setDebugLoc(CI->getDebugLoc());
Chris Lattnerf2836d12007-03-31 04:06:36 +00001072 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001073
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001074 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001075 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001076 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001077 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001078 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001079
Chris Lattnerf2836d12007-03-31 04:06:36 +00001080 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001081 if (CI->use_empty()) {
Adrian Prantl261ac8b2017-11-03 21:55:03 +00001082 salvageDebugInfo(*CI);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001083 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001084 MadeChange = true;
1085 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001086
Chris Lattnerf2836d12007-03-31 04:06:36 +00001087 return MadeChange;
1088}
1089
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001090/// If the specified cast instruction is a noop copy (e.g. it's casting from
1091/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1092/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001093///
1094/// Return true if any changes are made.
Mehdi Amini44ede332015-07-09 02:09:04 +00001095static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1096 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001097 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1098 // than sinking only nop casts, but is helpful on some platforms.
1099 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1100 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1101 ASC->getDestAddressSpace()))
1102 return false;
1103 }
1104
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001105 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001106 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1107 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001108
1109 // This is an fp<->int conversion?
1110 if (SrcVT.isInteger() != DstVT.isInteger())
1111 return false;
1112
1113 // If this is an extension, it will be a zero or sign extension, which
1114 // isn't a noop.
1115 if (SrcVT.bitsLT(DstVT)) return false;
1116
1117 // If these values will be promoted, find out what they will be promoted
1118 // to. This helps us consider truncates on PPC as noop copies when they
1119 // are.
1120 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1121 TargetLowering::TypePromoteInteger)
1122 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1123 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1124 TargetLowering::TypePromoteInteger)
1125 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1126
1127 // If, after promotion, these are the same types, this is a noop copy.
1128 if (SrcVT != DstVT)
1129 return false;
1130
1131 return SinkCast(CI);
1132}
1133
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001134/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1135/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001136///
1137/// Return true if any changes were made.
1138static bool CombineUAddWithOverflow(CmpInst *CI) {
1139 Value *A, *B;
1140 Instruction *AddI;
1141 if (!match(CI,
1142 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1143 return false;
1144
1145 Type *Ty = AddI->getType();
1146 if (!isa<IntegerType>(Ty))
1147 return false;
1148
1149 // We don't want to move around uses of condition values this late, so we we
1150 // check if it is legal to create the call to the intrinsic in the basic
1151 // block containing the icmp:
1152
1153 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1154 return false;
1155
1156#ifndef NDEBUG
1157 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1158 // for now:
1159 if (AddI->hasOneUse())
1160 assert(*AddI->user_begin() == CI && "expected!");
1161#endif
1162
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001163 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001164 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1165
1166 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1167
1168 auto *UAddWithOverflow =
1169 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1170 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1171 auto *Overflow =
1172 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1173
1174 CI->replaceAllUsesWith(Overflow);
1175 AddI->replaceAllUsesWith(UAdd);
1176 CI->eraseFromParent();
1177 AddI->eraseFromParent();
1178 return true;
1179}
1180
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001181/// Sink the given CmpInst into user blocks to reduce the number of virtual
1182/// registers that must be created and coalesced. This is a clear win except on
1183/// targets with multiple condition code registers (PowerPC), where it might
1184/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001185///
1186/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001187static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001188 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001189
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001190 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001191 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001192 return false;
1193
1194 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001195 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001196
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001197 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001198 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001199 UI != E; ) {
1200 Use &TheUse = UI.getUse();
1201 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001202
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001203 // Preincrement use iterator so we don't invalidate it.
1204 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001205
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001206 // Don't bother for PHI nodes.
1207 if (isa<PHINode>(User))
1208 continue;
1209
1210 // Figure out which BB this cmp is used in.
1211 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001212
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001213 // If this user is in the same block as the cmp, don't change the cmp.
1214 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001215
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001216 // If we have already inserted a cmp into this block, use it.
1217 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1218
1219 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001220 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001221 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001222 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001223 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1224 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001225 // Propagate the debug info.
1226 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001227 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001228
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001229 // Replace a use of the cmp with a use of the new cmp.
1230 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001231 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001232 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001233 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001234
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001235 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001236 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001237 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001238 MadeChange = true;
1239 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001240
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001241 return MadeChange;
1242}
1243
Peter Zotovf87e5502016-04-03 17:11:53 +00001244static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001245 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001246 return true;
1247
1248 if (CombineUAddWithOverflow(CI))
1249 return true;
1250
1251 return false;
1252}
1253
Geoff Berry5d534b62017-02-21 18:53:14 +00001254/// Duplicate and sink the given 'and' instruction into user blocks where it is
1255/// used in a compare to allow isel to generate better code for targets where
1256/// this operation can be combined.
1257///
1258/// Return true if any changes are made.
1259static bool sinkAndCmp0Expression(Instruction *AndI,
1260 const TargetLowering &TLI,
1261 SetOfInstrs &InsertedInsts) {
1262 // Double-check that we're not trying to optimize an instruction that was
1263 // already optimized by some other part of this pass.
1264 assert(!InsertedInsts.count(AndI) &&
1265 "Attempting to optimize already optimized and instruction");
1266 (void) InsertedInsts;
1267
1268 // Nothing to do for single use in same basic block.
1269 if (AndI->hasOneUse() &&
1270 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1271 return false;
1272
1273 // Try to avoid cases where sinking/duplicating is likely to increase register
1274 // pressure.
1275 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1276 !isa<ConstantInt>(AndI->getOperand(1)) &&
1277 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1278 return false;
1279
1280 for (auto *U : AndI->users()) {
1281 Instruction *User = cast<Instruction>(U);
1282
1283 // Only sink for and mask feeding icmp with 0.
1284 if (!isa<ICmpInst>(User))
1285 return false;
1286
1287 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1288 if (!CmpC || !CmpC->isZero())
1289 return false;
1290 }
1291
1292 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1293 return false;
1294
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001295 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1296 LLVM_DEBUG(AndI->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001297
1298 // Push the 'and' into the same block as the icmp 0. There should only be
1299 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1300 // others, so we don't need to keep track of which BBs we insert into.
1301 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1302 UI != E; ) {
1303 Use &TheUse = UI.getUse();
1304 Instruction *User = cast<Instruction>(*UI);
1305
1306 // Preincrement use iterator so we don't invalidate it.
1307 ++UI;
1308
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001309 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
Geoff Berry5d534b62017-02-21 18:53:14 +00001310
1311 // Keep the 'and' in the same place if the use is already in the same block.
1312 Instruction *InsertPt =
1313 User->getParent() == AndI->getParent() ? AndI : User;
1314 Instruction *InsertedAnd =
1315 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1316 AndI->getOperand(1), "", InsertPt);
1317 // Propagate the debug info.
1318 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1319
1320 // Replace a use of the 'and' with a use of the new 'and'.
1321 TheUse = InsertedAnd;
1322 ++NumAndUses;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001323 LLVM_DEBUG(User->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001324 }
1325
1326 // We removed all uses, nuke the and.
1327 AndI->eraseFromParent();
1328 return true;
1329}
1330
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001331/// Check if the candidates could be combined with a shift instruction, which
1332/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001333/// 1. Truncate instruction
1334/// 2. And instruction and the imm is a mask of the low bits:
1335/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001336static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001337 if (!isa<TruncInst>(User)) {
1338 if (User->getOpcode() != Instruction::And ||
1339 !isa<ConstantInt>(User->getOperand(1)))
1340 return false;
1341
Quentin Colombetd4f44692014-04-22 01:20:34 +00001342 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001343
Quentin Colombetd4f44692014-04-22 01:20:34 +00001344 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001345 return false;
1346 }
1347 return true;
1348}
1349
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001350/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001351static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001352SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1353 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001354 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001355 BasicBlock *UserBB = User->getParent();
1356 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1357 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1358 bool MadeChange = false;
1359
1360 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1361 TruncE = TruncI->user_end();
1362 TruncUI != TruncE;) {
1363
1364 Use &TruncTheUse = TruncUI.getUse();
1365 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1366 // Preincrement use iterator so we don't invalidate it.
1367
1368 ++TruncUI;
1369
1370 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1371 if (!ISDOpcode)
1372 continue;
1373
Tim Northovere2239ff2014-07-29 10:20:22 +00001374 // If the use is actually a legal node, there will not be an
1375 // implicit truncate.
1376 // FIXME: always querying the result type is just an
1377 // approximation; some nodes' legality is determined by the
1378 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001379 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001380 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001381 continue;
1382
1383 // Don't bother for PHI nodes.
1384 if (isa<PHINode>(TruncUser))
1385 continue;
1386
1387 BasicBlock *TruncUserBB = TruncUser->getParent();
1388
1389 if (UserBB == TruncUserBB)
1390 continue;
1391
1392 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1393 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1394
1395 if (!InsertedShift && !InsertedTrunc) {
1396 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001397 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001398 // Sink the shift
1399 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001400 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1401 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001402 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001403 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1404 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001405
1406 // Sink the trunc
1407 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1408 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001409 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001410
1411 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001412 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001413
1414 MadeChange = true;
1415
1416 TruncTheUse = InsertedTrunc;
1417 }
1418 }
1419 return MadeChange;
1420}
1421
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001422/// Sink the shift *right* instruction into user blocks if the uses could
1423/// potentially be combined with this shift instruction and generate BitExtract
1424/// instruction. It will only be applied if the architecture supports BitExtract
1425/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001426/// BB1:
1427/// %x.extract.shift = lshr i64 %arg1, 32
1428/// BB2:
1429/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1430/// ==>
1431///
1432/// BB2:
1433/// %x.extract.shift.1 = lshr i64 %arg1, 32
1434/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1435///
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001436/// CodeGen will recognize the pattern in BB2 and generate BitExtract
Yi Jiangd069f632014-04-21 19:34:27 +00001437/// instruction.
1438/// Return true if any changes are made.
1439static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001440 const TargetLowering &TLI,
1441 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001442 BasicBlock *DefBB = ShiftI->getParent();
1443
1444 /// Only insert instructions in each block once.
1445 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1446
Mehdi Amini44ede332015-07-09 02:09:04 +00001447 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001448
1449 bool MadeChange = false;
1450 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1451 UI != E;) {
1452 Use &TheUse = UI.getUse();
1453 Instruction *User = cast<Instruction>(*UI);
1454 // Preincrement use iterator so we don't invalidate it.
1455 ++UI;
1456
1457 // Don't bother for PHI nodes.
1458 if (isa<PHINode>(User))
1459 continue;
1460
1461 if (!isExtractBitsCandidateUse(User))
1462 continue;
1463
1464 BasicBlock *UserBB = User->getParent();
1465
1466 if (UserBB == DefBB) {
1467 // If the shift and truncate instruction are in the same BB. The use of
1468 // the truncate(TruncUse) may still introduce another truncate if not
1469 // legal. In this case, we would like to sink both shift and truncate
1470 // instruction to the BB of TruncUse.
1471 // for example:
1472 // BB1:
1473 // i64 shift.result = lshr i64 opnd, imm
1474 // trunc.result = trunc shift.result to i16
1475 //
1476 // BB2:
1477 // ----> We will have an implicit truncate here if the architecture does
1478 // not have i16 compare.
1479 // cmp i16 trunc.result, opnd2
1480 //
1481 if (isa<TruncInst>(User) && shiftIsLegal
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001482 // If the type of the truncate is legal, no truncate will be
Yi Jiangd069f632014-04-21 19:34:27 +00001483 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001484 &&
1485 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001486 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001487 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001488
1489 continue;
1490 }
1491 // If we have already inserted a shift into this block, use it.
1492 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1493
1494 if (!InsertedShift) {
1495 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001496 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001497
1498 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001499 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1500 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001501 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001502 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1503 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001504
1505 MadeChange = true;
1506 }
1507
1508 // Replace a use of the shift with a use of the new shift.
1509 TheUse = InsertedShift;
1510 }
1511
1512 // If we removed all uses, nuke the shift.
1513 if (ShiftI->use_empty())
1514 ShiftI->eraseFromParent();
1515
1516 return MadeChange;
1517}
1518
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001519/// If counting leading or trailing zeros is an expensive operation and a zero
1520/// input is defined, add a check for zero to avoid calling the intrinsic.
1521///
1522/// We want to transform:
1523/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1524///
1525/// into:
1526/// entry:
1527/// %cmpz = icmp eq i64 %A, 0
1528/// br i1 %cmpz, label %cond.end, label %cond.false
1529/// cond.false:
1530/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1531/// br label %cond.end
1532/// cond.end:
1533/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1534///
1535/// If the transform is performed, return true and set ModifiedDT to true.
1536static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1537 const TargetLowering *TLI,
1538 const DataLayout *DL,
1539 bool &ModifiedDT) {
1540 if (!TLI || !DL)
1541 return false;
1542
1543 // If a zero input is undefined, it doesn't make sense to despeculate that.
1544 if (match(CountZeros->getOperand(1), m_One()))
1545 return false;
1546
1547 // If it's cheap to speculate, there's nothing to do.
1548 auto IntrinsicID = CountZeros->getIntrinsicID();
1549 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1550 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1551 return false;
1552
1553 // Only handle legal scalar cases. Anything else requires too much work.
1554 Type *Ty = CountZeros->getType();
1555 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001556 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001557 return false;
1558
1559 // The intrinsic will be sunk behind a compare against zero and branch.
1560 BasicBlock *StartBlock = CountZeros->getParent();
1561 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1562
1563 // Create another block after the count zero intrinsic. A PHI will be added
1564 // in this block to select the result of the intrinsic or the bit-width
1565 // constant if the input to the intrinsic is zero.
1566 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1567 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1568
1569 // Set up a builder to create a compare, conditional branch, and PHI.
1570 IRBuilder<> Builder(CountZeros->getContext());
1571 Builder.SetInsertPoint(StartBlock->getTerminator());
1572 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1573
1574 // Replace the unconditional branch that was created by the first split with
1575 // a compare against zero and a conditional branch.
1576 Value *Zero = Constant::getNullValue(Ty);
1577 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1578 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1579 StartBlock->getTerminator()->eraseFromParent();
1580
1581 // Create a PHI in the end block to select either the output of the intrinsic
1582 // or the bit width of the operand.
1583 Builder.SetInsertPoint(&EndBlock->front());
1584 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1585 CountZeros->replaceAllUsesWith(PN);
1586 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1587 PN->addIncoming(BitWidth, StartBlock);
1588 PN->addIncoming(CountZeros, CallBlock);
1589
1590 // We are explicitly handling the zero case, so we can set the intrinsic's
1591 // undefined zero argument to 'true'. This will also prevent reprocessing the
1592 // intrinsic; we only despeculate when a zero input is defined.
1593 CountZeros->setArgOperand(1, Builder.getTrue());
1594 ModifiedDT = true;
1595 return true;
1596}
1597
Sanjay Patel3b8974b2017-06-08 20:00:09 +00001598bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001599 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001600
Chris Lattner7a277142011-01-15 07:14:54 +00001601 // Lower inline assembly if we can.
1602 // If we found an inline asm expession, and if the target knows how to
1603 // lower it to normal LLVM code, do so now.
1604 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1605 if (TLI->ExpandInlineAsm(CI)) {
1606 // Avoid invalidating the iterator.
1607 CurInstIterator = BB->begin();
1608 // Avoid processing instructions out of order, which could cause
1609 // reuse before a value is defined.
1610 SunkAddrs.clear();
1611 return true;
1612 }
1613 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001614 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001615 return true;
1616 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001617
John Brawn0dbcd652015-03-18 12:01:59 +00001618 // Align the pointer arguments to this call if the target thinks it's a good
1619 // idea
1620 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001621 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001622 for (auto &Arg : CI->arg_operands()) {
1623 // We want to align both objects whose address is used directly and
1624 // objects whose address is used in casts and GEPs, though it only makes
1625 // sense for GEPs if the offset is a multiple of the desired alignment and
1626 // if size - offset meets the size threshold.
1627 if (!Arg->getType()->isPointerTy())
1628 continue;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001629 APInt Offset(DL->getIndexSizeInBits(
Mehdi Amini4fe37982015-07-07 18:45:17 +00001630 cast<PointerType>(Arg->getType())->getAddressSpace()),
1631 0);
1632 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001633 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001634 if ((Offset2 & (PrefAlign-1)) != 0)
1635 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001636 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001637 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1638 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001639 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001640 // Global variables can only be aligned if they are defined in this
1641 // object (i.e. they are uniquely initialized in this object), and
1642 // over-aligning global variables that have an explicit section is
1643 // forbidden.
1644 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001645 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001646 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001647 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001648 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001649 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001650 }
1651 // If this is a memcpy (or similar) then we may be able to improve the
1652 // alignment
1653 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Daniel Neilsonbe58a222018-01-31 17:24:53 +00001654 unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
1655 if (DestAlign > MI->getDestAlignment())
1656 MI->setDestAlignment(DestAlign);
1657 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1658 unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
1659 if (SrcAlign > MTI->getSourceAlignment())
1660 MTI->setSourceAlignment(SrcAlign);
1661 }
John Brawn0dbcd652015-03-18 12:01:59 +00001662 }
1663 }
1664
Philip Reamesac115ed2016-03-09 23:13:12 +00001665 // If we have a cold call site, try to sink addressing computation into the
1666 // cold block. This interacts with our handling for loads and stores to
1667 // ensure that we can fold all uses of a potential addressing computation
1668 // into their uses. TODO: generalize this to work over profiling data
1669 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1670 for (auto &Arg : CI->arg_operands()) {
1671 if (!Arg->getType()->isPointerTy())
1672 continue;
1673 unsigned AS = Arg->getType()->getPointerAddressSpace();
1674 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1675 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001676
Eric Christopher4b7948e2010-03-11 02:41:03 +00001677 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001678 if (II) {
1679 switch (II->getIntrinsicID()) {
1680 default: break;
1681 case Intrinsic::objectsize: {
1682 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00001683 ConstantInt *RetVal =
1684 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001685 // Substituting this can cause recursive simplifications, which can
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001686 // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case
1687 // this
Sanjoy Das2cbeb002017-04-26 16:37:05 +00001688 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001689 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001690 WeakTrackingVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001691
Sanjay Patel545a4562016-01-20 18:59:16 +00001692 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001693
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001694 // If the iterator instruction was recursively deleted, start over at the
1695 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001696 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001697 CurInstIterator = BB->begin();
1698 SunkAddrs.clear();
1699 }
1700 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001701 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001702 case Intrinsic::aarch64_stlxr:
1703 case Intrinsic::aarch64_stxr: {
1704 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1705 if (!ExtVal || !ExtVal->hasOneUse() ||
1706 ExtVal->getParent() == CI->getParent())
1707 return false;
1708 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1709 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001710 // Mark this instruction as "inserted by CGP", so that other
1711 // optimizations don't touch it.
1712 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001713 return true;
1714 }
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001715 case Intrinsic::launder_invariant_group:
Piotr Padlewski5b3db452018-07-02 04:49:30 +00001716 case Intrinsic::strip_invariant_group:
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001717 II->replaceAllUsesWith(II->getArgOperand(0));
1718 II->eraseFromParent();
1719 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001720
1721 case Intrinsic::cttz:
1722 case Intrinsic::ctlz:
1723 // If counting zeros is expensive, try to avoid it.
1724 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001725 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001726
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001727 if (TLI) {
1728 SmallVector<Value*, 2> PtrOps;
1729 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001730 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1731 while (!PtrOps.empty()) {
1732 Value *PtrVal = PtrOps.pop_back_val();
1733 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1734 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001735 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001736 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001737 }
Pete Cooper615fd892012-03-13 20:59:56 +00001738 }
1739
Eric Christopher4b7948e2010-03-11 02:41:03 +00001740 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001741 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001742
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001743 // Lower all default uses of _chk calls. This is very similar
1744 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001745 // to fortified library functions (e.g. __memcpy_chk) that have the default
1746 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001747 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001748 if (Value *V = Simplifier.optimizeCall(CI)) {
1749 CI->replaceAllUsesWith(V);
1750 CI->eraseFromParent();
1751 return true;
1752 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001753
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001754 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001755}
Chris Lattner1b93be52011-01-15 07:25:29 +00001756
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001757/// Look for opportunities to duplicate return instructions to the predecessor
1758/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001759/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001760/// bb0:
1761/// %tmp0 = tail call i32 @f0()
1762/// br label %return
1763/// bb1:
1764/// %tmp1 = tail call i32 @f1()
1765/// br label %return
1766/// bb2:
1767/// %tmp2 = tail call i32 @f2()
1768/// br label %return
1769/// return:
1770/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1771/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001772/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001773///
1774/// =>
1775///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001776/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001777/// bb0:
1778/// %tmp0 = tail call i32 @f0()
1779/// ret i32 %tmp0
1780/// bb1:
1781/// %tmp1 = tail call i32 @f1()
1782/// ret i32 %tmp1
1783/// bb2:
1784/// %tmp2 = tail call i32 @f2()
1785/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001786/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001787bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001788 if (!TLI)
1789 return false;
1790
Michael Kuperstein71321562016-09-07 20:29:49 +00001791 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1792 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001793 return false;
1794
Craig Topperc0196b12014-04-14 00:51:57 +00001795 PHINode *PN = nullptr;
1796 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001797 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001798 if (V) {
1799 BCI = dyn_cast<BitCastInst>(V);
1800 if (BCI)
1801 V = BCI->getOperand(0);
1802
1803 PN = dyn_cast<PHINode>(V);
1804 if (!PN)
1805 return false;
1806 }
Evan Cheng0663f232011-03-21 01:19:09 +00001807
Cameron Zwarich4649f172011-03-24 04:52:10 +00001808 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001809 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001810
Cameron Zwarich4649f172011-03-24 04:52:10 +00001811 // Make sure there are no instructions between the PHI and return, or that the
1812 // return is the first instruction in the block.
1813 if (PN) {
1814 BasicBlock::iterator BI = BB->begin();
1815 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001816 if (&*BI == BCI)
1817 // Also skip over the bitcast.
1818 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001819 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001820 return false;
1821 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001822 BasicBlock::iterator BI = BB->begin();
1823 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001824 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001825 return false;
1826 }
Evan Cheng0663f232011-03-21 01:19:09 +00001827
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001828 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1829 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001830 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001831 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001832 if (PN) {
1833 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1834 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1835 // Make sure the phi value is indeed produced by the tail call.
1836 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001837 TLI->mayBeEmittedAsTailCall(CI) &&
1838 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001839 TailCalls.push_back(CI);
1840 }
1841 } else {
1842 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001843 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001844 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001845 continue;
1846
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001847 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001848 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1849 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001850 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1851 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001852 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001853
Cameron Zwarich4649f172011-03-24 04:52:10 +00001854 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001855 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1856 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001857 TailCalls.push_back(CI);
1858 }
Evan Cheng0663f232011-03-21 01:19:09 +00001859 }
1860
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001861 bool Changed = false;
1862 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1863 CallInst *CI = TailCalls[i];
1864 CallSite CS(CI);
1865
1866 // Conservatively require the attributes of the call to match those of the
1867 // return. Ignore noalias because it doesn't affect the call sequence.
Reid Klecknerb5180542017-03-21 16:57:19 +00001868 AttributeList CalleeAttrs = CS.getAttributes();
1869 if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1870 .removeAttribute(Attribute::NoAlias) !=
1871 AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1872 .removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001873 continue;
1874
1875 // Make sure the call instruction is followed by an unconditional branch to
1876 // the return block.
1877 BasicBlock *CallBB = CI->getParent();
1878 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1879 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1880 continue;
1881
1882 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00001883 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001884 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001885 ++NumRetsDup;
1886 }
1887
1888 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001889 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001890 BB->eraseFromParent();
1891
1892 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001893}
1894
Chris Lattner728f9022008-11-25 07:09:13 +00001895//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001896// Memory Optimization
1897//===----------------------------------------------------------------------===//
1898
Chandler Carruthc8925912013-01-05 02:09:22 +00001899namespace {
1900
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001901/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00001902/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001903struct ExtAddrMode : public TargetLowering::AddrMode {
Eugene Zelenko900b6332017-08-29 22:32:07 +00001904 Value *BaseReg = nullptr;
1905 Value *ScaledReg = nullptr;
John Brawn736bf002017-10-03 13:08:22 +00001906 Value *OriginalValue = nullptr;
1907
1908 enum FieldName {
1909 NoField = 0x00,
1910 BaseRegField = 0x01,
1911 BaseGVField = 0x02,
1912 BaseOffsField = 0x04,
1913 ScaledRegField = 0x08,
1914 ScaleField = 0x10,
1915 MultipleFields = 0xff
1916 };
Eugene Zelenko900b6332017-08-29 22:32:07 +00001917
1918 ExtAddrMode() = default;
1919
Chandler Carruthc8925912013-01-05 02:09:22 +00001920 void print(raw_ostream &OS) const;
1921 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001922
John Brawn736bf002017-10-03 13:08:22 +00001923 FieldName compare(const ExtAddrMode &other) {
1924 // First check that the types are the same on each field, as differing types
1925 // is something we can't cope with later on.
1926 if (BaseReg && other.BaseReg &&
1927 BaseReg->getType() != other.BaseReg->getType())
1928 return MultipleFields;
1929 if (BaseGV && other.BaseGV &&
1930 BaseGV->getType() != other.BaseGV->getType())
1931 return MultipleFields;
1932 if (ScaledReg && other.ScaledReg &&
1933 ScaledReg->getType() != other.ScaledReg->getType())
1934 return MultipleFields;
1935
1936 // Check each field to see if it differs.
1937 unsigned Result = NoField;
1938 if (BaseReg != other.BaseReg)
1939 Result |= BaseRegField;
1940 if (BaseGV != other.BaseGV)
1941 Result |= BaseGVField;
1942 if (BaseOffs != other.BaseOffs)
1943 Result |= BaseOffsField;
1944 if (ScaledReg != other.ScaledReg)
1945 Result |= ScaledRegField;
1946 // Don't count 0 as being a different scale, because that actually means
1947 // unscaled (which will already be counted by having no ScaledReg).
1948 if (Scale && other.Scale && Scale != other.Scale)
1949 Result |= ScaleField;
1950
1951 if (countPopulation(Result) > 1)
1952 return MultipleFields;
1953 else
1954 return static_cast<FieldName>(Result);
1955 }
1956
John Brawn4b476482017-11-27 11:29:15 +00001957 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
1958 // with no offset.
John Brawn736bf002017-10-03 13:08:22 +00001959 bool isTrivial() {
John Brawn4b476482017-11-27 11:29:15 +00001960 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
1961 // trivial if at most one of these terms is nonzero, except that BaseGV and
1962 // BaseReg both being zero actually means a null pointer value, which we
1963 // consider to be 'non-zero' here.
1964 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
Chandler Carruthc8925912013-01-05 02:09:22 +00001965 }
John Brawn70cdb5b2017-11-24 14:10:45 +00001966
1967 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
1968 switch (Field) {
1969 default:
1970 return nullptr;
1971 case BaseRegField:
1972 return BaseReg;
1973 case BaseGVField:
1974 return BaseGV;
1975 case ScaledRegField:
1976 return ScaledReg;
1977 case BaseOffsField:
1978 return ConstantInt::get(IntPtrTy, BaseOffs);
1979 }
1980 }
1981
1982 void SetCombinedField(FieldName Field, Value *V,
1983 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
1984 switch (Field) {
1985 default:
1986 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
1987 break;
1988 case ExtAddrMode::BaseRegField:
1989 BaseReg = V;
1990 break;
1991 case ExtAddrMode::BaseGVField:
1992 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
1993 // in the BaseReg field.
1994 assert(BaseReg == nullptr);
1995 BaseReg = V;
1996 BaseGV = nullptr;
1997 break;
1998 case ExtAddrMode::ScaledRegField:
1999 ScaledReg = V;
2000 // If we have a mix of scaled and unscaled addrmodes then we want scale
2001 // to be the scale and not zero.
2002 if (!Scale)
2003 for (const ExtAddrMode &AM : AddrModes)
2004 if (AM.Scale) {
2005 Scale = AM.Scale;
2006 break;
2007 }
2008 break;
2009 case ExtAddrMode::BaseOffsField:
2010 // The offset is no longer a constant, so it goes in ScaledReg with a
2011 // scale of 1.
2012 assert(ScaledReg == nullptr);
2013 ScaledReg = V;
2014 Scale = 1;
2015 BaseOffs = 0;
2016 break;
2017 }
2018 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002019};
2020
Eugene Zelenko900b6332017-08-29 22:32:07 +00002021} // end anonymous namespace
2022
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002023#ifndef NDEBUG
2024static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2025 AM.print(OS);
2026 return OS;
2027}
2028#endif
2029
Aaron Ballman615eb472017-10-15 14:32:27 +00002030#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthc8925912013-01-05 02:09:22 +00002031void ExtAddrMode::print(raw_ostream &OS) const {
2032 bool NeedPlus = false;
2033 OS << "[";
2034 if (BaseGV) {
2035 OS << (NeedPlus ? " + " : "")
2036 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002037 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002038 NeedPlus = true;
2039 }
2040
Richard Trieuc0f91212014-05-30 03:15:17 +00002041 if (BaseOffs) {
2042 OS << (NeedPlus ? " + " : "")
2043 << BaseOffs;
2044 NeedPlus = true;
2045 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002046
2047 if (BaseReg) {
2048 OS << (NeedPlus ? " + " : "")
2049 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002050 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002051 NeedPlus = true;
2052 }
2053 if (Scale) {
2054 OS << (NeedPlus ? " + " : "")
2055 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002056 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002057 }
2058
2059 OS << ']';
2060}
2061
Yaron Kereneb2a2542016-01-29 20:50:44 +00002062LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002063 print(dbgs());
2064 dbgs() << '\n';
2065}
2066#endif
2067
Eugene Zelenko900b6332017-08-29 22:32:07 +00002068namespace {
2069
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002070/// This class provides transaction based operation on the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002071/// Every change made through this class is recorded in the internal state and
2072/// can be undone (rollback) until commit is called.
2073class TypePromotionTransaction {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002074 /// This represents the common interface of the individual transaction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002075 /// Each class implements the logic for doing one specific modification on
2076 /// the IR via the TypePromotionTransaction.
2077 class TypePromotionAction {
2078 protected:
2079 /// The Instruction modified.
2080 Instruction *Inst;
2081
2082 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002083 /// Constructor of the action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002084 /// The constructor performs the related action on the IR.
2085 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2086
Eugene Zelenko900b6332017-08-29 22:32:07 +00002087 virtual ~TypePromotionAction() = default;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002088
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002089 /// Undo the modification done by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002090 /// When this method is called, the IR must be in the same state as it was
2091 /// before this action was applied.
2092 /// \pre Undoing the action works if and only if the IR is in the exact same
2093 /// state as it was directly after this action was applied.
2094 virtual void undo() = 0;
2095
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002096 /// Advocate every change made by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002097 /// When the results on the IR of the action are to be kept, it is important
2098 /// to call this function, otherwise hidden information may be kept forever.
2099 virtual void commit() {
2100 // Nothing to be done, this action is not doing anything.
2101 }
2102 };
2103
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002104 /// Utility to remember the position of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002105 class InsertionHandler {
2106 /// Position of an instruction.
2107 /// Either an instruction:
2108 /// - Is the first in a basic block: BB is used.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002109 /// - Has a previous instruction: PrevInst is used.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002110 union {
2111 Instruction *PrevInst;
2112 BasicBlock *BB;
2113 } Point;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002114
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002115 /// Remember whether or not the instruction had a previous instruction.
2116 bool HasPrevInstruction;
2117
2118 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002119 /// Record the position of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002120 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002121 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002122 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2123 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002124 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002125 else
2126 Point.BB = Inst->getParent();
2127 }
2128
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002129 /// Insert \p Inst at the recorded position.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002130 void insert(Instruction *Inst) {
2131 if (HasPrevInstruction) {
2132 if (Inst->getParent())
2133 Inst->removeFromParent();
2134 Inst->insertAfter(Point.PrevInst);
2135 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002136 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002137 if (Inst->getParent())
2138 Inst->moveBefore(Position);
2139 else
2140 Inst->insertBefore(Position);
2141 }
2142 }
2143 };
2144
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002145 /// Move an instruction before another.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002146 class InstructionMoveBefore : public TypePromotionAction {
2147 /// Original position of the instruction.
2148 InsertionHandler Position;
2149
2150 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002151 /// Move \p Inst before \p Before.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002152 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2153 : TypePromotionAction(Inst), Position(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002154 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
2155 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002156 Inst->moveBefore(Before);
2157 }
2158
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002159 /// Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002160 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002161 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002162 Position.insert(Inst);
2163 }
2164 };
2165
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002166 /// Set the operand of an instruction with a new value.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002167 class OperandSetter : public TypePromotionAction {
2168 /// Original operand of the instruction.
2169 Value *Origin;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002170
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002171 /// Index of the modified instruction.
2172 unsigned Idx;
2173
2174 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002175 /// Set \p Idx operand of \p Inst with \p NewVal.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002176 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2177 : TypePromotionAction(Inst), Idx(Idx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002178 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2179 << "for:" << *Inst << "\n"
2180 << "with:" << *NewVal << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002181 Origin = Inst->getOperand(Idx);
2182 Inst->setOperand(Idx, NewVal);
2183 }
2184
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002185 /// Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002186 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002187 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2188 << "for: " << *Inst << "\n"
2189 << "with: " << *Origin << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002190 Inst->setOperand(Idx, Origin);
2191 }
2192 };
2193
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002194 /// Hide the operands of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002195 /// Do as if this instruction was not using any of its operands.
2196 class OperandsHider : public TypePromotionAction {
2197 /// The list of original operands.
2198 SmallVector<Value *, 4> OriginalValues;
2199
2200 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002201 /// Remove \p Inst from the uses of the operands of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002202 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002203 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002204 unsigned NumOpnds = Inst->getNumOperands();
2205 OriginalValues.reserve(NumOpnds);
2206 for (unsigned It = 0; It < NumOpnds; ++It) {
2207 // Save the current operand.
2208 Value *Val = Inst->getOperand(It);
2209 OriginalValues.push_back(Val);
2210 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002211 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002212 // that we are not willing to pay.
2213 Inst->setOperand(It, UndefValue::get(Val->getType()));
2214 }
2215 }
2216
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002217 /// Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002218 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002219 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002220 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2221 Inst->setOperand(It, OriginalValues[It]);
2222 }
2223 };
2224
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002225 /// Build a truncate instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002226 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002227 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002228
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002229 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002230 /// Build a truncate instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002231 /// result.
2232 /// trunc Opnd to Ty.
2233 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2234 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002235 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002236 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002237 }
2238
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002239 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002240 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002241
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002242 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002243 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002244 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002245 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2246 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002247 }
2248 };
2249
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002250 /// Build a sign extension instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002251 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002252 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002253
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002254 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002255 /// Build a sign extension instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002256 /// result.
2257 /// sext Opnd to Ty.
2258 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002259 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002260 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002261 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002262 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002263 }
2264
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002265 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002266 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002267
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002268 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002269 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002270 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002271 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2272 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002273 }
2274 };
2275
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002276 /// Build a zero extension instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002277 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002278 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002279
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002280 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002281 /// Build a zero extension instruction of \p Opnd producing a \p Ty
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002282 /// result.
2283 /// zext Opnd to Ty.
2284 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002285 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002286 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002287 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002288 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002289 }
2290
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002291 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002292 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002293
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002294 /// Remove the built instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002295 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002296 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002297 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2298 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002299 }
2300 };
2301
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002302 /// Mutate an instruction to another type.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002303 class TypeMutator : public TypePromotionAction {
2304 /// Record the original type.
2305 Type *OrigTy;
2306
2307 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002308 /// Mutate the type of \p Inst into \p NewTy.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002309 TypeMutator(Instruction *Inst, Type *NewTy)
2310 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002311 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2312 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002313 Inst->mutateType(NewTy);
2314 }
2315
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002316 /// Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002317 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002318 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2319 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002320 Inst->mutateType(OrigTy);
2321 }
2322 };
2323
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002324 /// Replace the uses of an instruction by another instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002325 class UsesReplacer : public TypePromotionAction {
2326 /// Helper structure to keep track of the replaced uses.
2327 struct InstructionAndIdx {
2328 /// The instruction using the instruction.
2329 Instruction *Inst;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002330
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002331 /// The index where this instruction is used for Inst.
2332 unsigned Idx;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002333
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002334 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2335 : Inst(Inst), Idx(Idx) {}
2336 };
2337
2338 /// Keep track of the original uses (pair Instruction, Index).
2339 SmallVector<InstructionAndIdx, 4> OriginalUses;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002340
2341 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002342
2343 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002344 /// Replace all the use of \p Inst by \p New.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002345 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002346 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2347 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002348 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002349 for (Use &U : Inst->uses()) {
2350 Instruction *UserI = cast<Instruction>(U.getUser());
2351 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002352 }
2353 // Now, we can replace the uses.
2354 Inst->replaceAllUsesWith(New);
2355 }
2356
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002357 /// Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002358 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002359 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002360 for (use_iterator UseIt = OriginalUses.begin(),
2361 EndIt = OriginalUses.end();
2362 UseIt != EndIt; ++UseIt) {
2363 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2364 }
2365 }
2366 };
2367
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002368 /// Remove an instruction from the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002369 class InstructionRemover : public TypePromotionAction {
2370 /// Original position of the instruction.
2371 InsertionHandler Inserter;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002372
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002373 /// Helper structure to hide all the link to the instruction. In other
2374 /// words, this helps to do as if the instruction was removed.
2375 OperandsHider Hider;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002376
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002377 /// Keep track of the uses replaced, if any.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002378 UsesReplacer *Replacer = nullptr;
2379
Jun Bum Limdee55652017-04-03 19:20:07 +00002380 /// Keep track of instructions removed.
2381 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002382
2383 public:
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002384 /// Remove all reference of \p Inst and optionally replace all its
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002385 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002386 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002387 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002388 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2389 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002390 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Eugene Zelenko900b6332017-08-29 22:32:07 +00002391 RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002392 if (New)
2393 Replacer = new UsesReplacer(Inst, New);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002394 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002395 RemovedInsts.insert(Inst);
2396 /// The instructions removed here will be freed after completing
2397 /// optimizeBlock() for all blocks as we need to keep track of the
2398 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002399 Inst->removeFromParent();
2400 }
2401
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002402 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002403
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002404 /// Resurrect the instruction and reassign it to the proper uses if
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002405 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002406 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002407 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002408 Inserter.insert(Inst);
2409 if (Replacer)
2410 Replacer->undo();
2411 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002412 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002413 }
2414 };
2415
2416public:
2417 /// Restoration point.
2418 /// The restoration point is a pointer to an action instead of an iterator
2419 /// because the iterator may be invalidated but not the pointer.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002420 using ConstRestorationPt = const TypePromotionAction *;
Jun Bum Limdee55652017-04-03 19:20:07 +00002421
2422 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2423 : RemovedInsts(RemovedInsts) {}
2424
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002425 /// Advocate every changes made in that transaction.
2426 void commit();
Eugene Zelenko900b6332017-08-29 22:32:07 +00002427
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002428 /// Undo all the changes made after the given point.
2429 void rollback(ConstRestorationPt Point);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002430
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002431 /// Get the current restoration point.
2432 ConstRestorationPt getRestorationPoint() const;
2433
2434 /// \name API for IR modification with state keeping to support rollback.
2435 /// @{
2436 /// Same as Instruction::setOperand.
2437 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002438
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002439 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002440 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002441
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002442 /// Same as Value::replaceAllUsesWith.
2443 void replaceAllUsesWith(Instruction *Inst, Value *New);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002444
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002445 /// Same as Value::mutateType.
2446 void mutateType(Instruction *Inst, Type *NewTy);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002447
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002448 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002449 Value *createTrunc(Instruction *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002450
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002451 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002452 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002453
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002454 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002455 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002456
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002457 /// Same as Instruction::moveBefore.
2458 void moveBefore(Instruction *Inst, Instruction *Before);
2459 /// @}
2460
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002461private:
2462 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002463 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002464
2465 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2466
Jun Bum Limdee55652017-04-03 19:20:07 +00002467 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002468};
2469
Eugene Zelenko900b6332017-08-29 22:32:07 +00002470} // end anonymous namespace
2471
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002472void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2473 Value *NewVal) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002474 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2475 Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002476}
2477
2478void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2479 Value *NewVal) {
2480 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002481 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2482 Inst, RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002483}
2484
2485void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2486 Value *New) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002487 Actions.push_back(
2488 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002489}
2490
2491void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002492 Actions.push_back(
2493 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002494}
2495
Quentin Colombetac55b152014-09-16 22:36:07 +00002496Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2497 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002498 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002499 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002500 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002501 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002502}
2503
Quentin Colombetac55b152014-09-16 22:36:07 +00002504Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2505 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002506 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002507 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002508 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002509 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002510}
2511
Quentin Colombetac55b152014-09-16 22:36:07 +00002512Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2513 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002514 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002515 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002516 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002517 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002518}
2519
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002520void TypePromotionTransaction::moveBefore(Instruction *Inst,
2521 Instruction *Before) {
2522 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002523 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2524 Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002525}
2526
2527TypePromotionTransaction::ConstRestorationPt
2528TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002529 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002530}
2531
2532void TypePromotionTransaction::commit() {
2533 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002534 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002535 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002536 Actions.clear();
2537}
2538
2539void TypePromotionTransaction::rollback(
2540 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002541 while (!Actions.empty() && Point != Actions.back().get()) {
2542 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002543 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002544 }
2545}
2546
Eugene Zelenko900b6332017-08-29 22:32:07 +00002547namespace {
2548
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002549/// A helper class for matching addressing modes.
Chandler Carruthc8925912013-01-05 02:09:22 +00002550///
2551/// This encapsulates the logic for matching the target-legal addressing modes.
2552class AddressingModeMatcher {
2553 SmallVectorImpl<Instruction*> &AddrModeInsts;
2554 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002555 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002556 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002557
2558 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2559 /// the memory instruction that we're computing this address for.
2560 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002561 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002562 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002563
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002564 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002565 /// part of the return value of this addressing mode matching stuff.
2566 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002567
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002568 /// The instructions inserted by other CodeGenPrepare optimizations.
2569 const SetOfInstrs &InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002570
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002571 /// A map from the instructions to their type before promotion.
2572 InstrToOrigTy &PromotedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002573
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002574 /// The ongoing transaction where every action should be registered.
2575 TypePromotionTransaction &TPT;
2576
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002577 // A GEP which has too large offset to be folded into the addressing mode.
2578 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
2579
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002580 /// This is set to true when we should not do profitability checks.
2581 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002582 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002583
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002584 AddressingModeMatcher(
2585 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
2586 const TargetRegisterInfo &TRI, Type *AT, unsigned AS, Instruction *MI,
2587 ExtAddrMode &AM, const SetOfInstrs &InsertedInsts,
2588 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
2589 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002590 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002591 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2592 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002593 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002594 IgnoreProfitability = false;
2595 }
Stephen Lin837bba12013-07-15 17:55:02 +00002596
Eugene Zelenko900b6332017-08-29 22:32:07 +00002597public:
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002598 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002599 /// give an access type of AccessTy. This returns a list of involved
2600 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002601 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002602 /// optimizations.
2603 /// \p PromotedInsts maps the instructions to their type before promotion.
2604 /// \p The ongoing transaction where every action should be registered.
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002605 static ExtAddrMode
2606 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
2607 SmallVectorImpl<Instruction *> &AddrModeInsts,
2608 const TargetLowering &TLI, const TargetRegisterInfo &TRI,
2609 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
2610 TypePromotionTransaction &TPT,
2611 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002612 ExtAddrMode Result;
2613
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002614 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002615 MemoryInst, Result, InsertedInsts,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002616 PromotedInsts, TPT, LargeOffsetGEP)
2617 .matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002618 (void)Success; assert(Success && "Couldn't select *anything*?");
2619 return Result;
2620 }
Eugene Zelenko900b6332017-08-29 22:32:07 +00002621
Chandler Carruthc8925912013-01-05 02:09:22 +00002622private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002623 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
Fangrui Songcb0bab82018-07-16 18:51:40 +00002624 bool matchAddr(Value *Addr, unsigned Depth);
2625 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002626 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002627 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002628 ExtAddrMode &AMBefore,
2629 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002630 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2631 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002632 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002633};
2634
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002635/// Keep track of simplification of Phi nodes.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002636/// Accept the set of all phi nodes and erase phi node from this set
2637/// if it is simplified.
2638class SimplificationTracker {
2639 DenseMap<Value *, Value *> Storage;
2640 const SimplifyQuery &SQ;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002641 // Tracks newly created Phi nodes. We use a SetVector to get deterministic
2642 // order when iterating over the set in MatchPhiSet.
2643 SmallSetVector<PHINode *, 32> AllPhiNodes;
2644 // Tracks newly created Select nodes.
2645 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002646
2647public:
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002648 SimplificationTracker(const SimplifyQuery &sq)
2649 : SQ(sq) {}
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002650
2651 Value *Get(Value *V) {
2652 do {
2653 auto SV = Storage.find(V);
2654 if (SV == Storage.end())
2655 return V;
2656 V = SV->second;
2657 } while (true);
2658 }
2659
2660 Value *Simplify(Value *Val) {
2661 SmallVector<Value *, 32> WorkList;
2662 SmallPtrSet<Value *, 32> Visited;
2663 WorkList.push_back(Val);
2664 while (!WorkList.empty()) {
2665 auto P = WorkList.pop_back_val();
2666 if (!Visited.insert(P).second)
2667 continue;
2668 if (auto *PI = dyn_cast<Instruction>(P))
2669 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
2670 for (auto *U : PI->users())
2671 WorkList.push_back(cast<Value>(U));
2672 Put(PI, V);
2673 PI->replaceAllUsesWith(V);
2674 if (auto *PHI = dyn_cast<PHINode>(PI))
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002675 AllPhiNodes.remove(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002676 if (auto *Select = dyn_cast<SelectInst>(PI))
2677 AllSelectNodes.erase(Select);
2678 PI->eraseFromParent();
2679 }
2680 }
2681 return Get(Val);
2682 }
2683
2684 void Put(Value *From, Value *To) {
2685 Storage.insert({ From, To });
2686 }
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002687
2688 void ReplacePhi(PHINode *From, PHINode *To) {
2689 Value* OldReplacement = Get(From);
2690 while (OldReplacement != From) {
2691 From = To;
2692 To = dyn_cast<PHINode>(OldReplacement);
2693 OldReplacement = Get(From);
2694 }
2695 assert(Get(To) == To && "Replacement PHI node is already replaced.");
2696 Put(From, To);
2697 From->replaceAllUsesWith(To);
2698 AllPhiNodes.remove(From);
2699 From->eraseFromParent();
2700 }
2701
2702 SmallSetVector<PHINode *, 32>& newPhiNodes() { return AllPhiNodes; }
2703
2704 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
2705
2706 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
2707
2708 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
2709
2710 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
2711
2712 void destroyNewNodes(Type *CommonType) {
2713 // For safe erasing, replace the uses with dummy value first.
2714 auto Dummy = UndefValue::get(CommonType);
2715 for (auto I : AllPhiNodes) {
2716 I->replaceAllUsesWith(Dummy);
2717 I->eraseFromParent();
2718 }
2719 AllPhiNodes.clear();
2720 for (auto I : AllSelectNodes) {
2721 I->replaceAllUsesWith(Dummy);
2722 I->eraseFromParent();
2723 }
2724 AllSelectNodes.clear();
2725 }
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002726};
2727
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002728/// A helper class for combining addressing modes.
John Brawn736bf002017-10-03 13:08:22 +00002729class AddressingModeCombiner {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002730 typedef std::pair<Value *, BasicBlock *> ValueInBB;
2731 typedef DenseMap<ValueInBB, Value *> FoldAddrToValueMapping;
2732 typedef std::pair<PHINode *, PHINode *> PHIPair;
2733
John Brawn736bf002017-10-03 13:08:22 +00002734private:
2735 /// The addressing modes we've collected.
2736 SmallVector<ExtAddrMode, 16> AddrModes;
2737
2738 /// The field in which the AddrModes differ, when we have more than one.
2739 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
2740
2741 /// Are the AddrModes that we have all just equal to their original values?
2742 bool AllAddrModesTrivial = true;
2743
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002744 /// Common Type for all different fields in addressing modes.
2745 Type *CommonType;
2746
2747 /// SimplifyQuery for simplifyInstruction utility.
2748 const SimplifyQuery &SQ;
2749
2750 /// Original Address.
2751 ValueInBB Original;
2752
John Brawn736bf002017-10-03 13:08:22 +00002753public:
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002754 AddressingModeCombiner(const SimplifyQuery &_SQ, ValueInBB OriginalValue)
2755 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
2756
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002757 /// Get the combined AddrMode
John Brawn736bf002017-10-03 13:08:22 +00002758 const ExtAddrMode &getAddrMode() const {
2759 return AddrModes[0];
2760 }
2761
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002762 /// Add a new AddrMode if it's compatible with the AddrModes we already
John Brawn736bf002017-10-03 13:08:22 +00002763 /// have.
2764 /// \return True iff we succeeded in doing so.
2765 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
2766 // Take note of if we have any non-trivial AddrModes, as we need to detect
2767 // when all AddrModes are trivial as then we would introduce a phi or select
2768 // which just duplicates what's already there.
2769 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
2770
2771 // If this is the first addrmode then everything is fine.
2772 if (AddrModes.empty()) {
2773 AddrModes.emplace_back(NewAddrMode);
2774 return true;
2775 }
2776
2777 // Figure out how different this is from the other address modes, which we
2778 // can do just by comparing against the first one given that we only care
2779 // about the cumulative difference.
2780 ExtAddrMode::FieldName ThisDifferentField =
2781 AddrModes[0].compare(NewAddrMode);
2782 if (DifferentField == ExtAddrMode::NoField)
2783 DifferentField = ThisDifferentField;
2784 else if (DifferentField != ThisDifferentField)
2785 DifferentField = ExtAddrMode::MultipleFields;
2786
Serguei Katkov17e57942018-01-23 12:07:49 +00002787 // If NewAddrMode differs in more than one dimension we cannot handle it.
2788 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
2789
2790 // If Scale Field is different then we reject.
2791 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
2792
Serguei Katkov4d1dd6b2018-01-09 04:37:06 +00002793 // We also must reject the case when base offset is different and
2794 // scale reg is not null, we cannot handle this case due to merge of
2795 // different offsets will be used as ScaleReg.
Serguei Katkov17e57942018-01-23 12:07:49 +00002796 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
2797 !NewAddrMode.ScaledReg);
John Brawn736bf002017-10-03 13:08:22 +00002798
Serguei Katkov17e57942018-01-23 12:07:49 +00002799 // We also must reject the case when GV is different and BaseReg installed
2800 // due to we want to use base reg as a merge of GV values.
2801 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
2802 !NewAddrMode.HasBaseReg);
2803
2804 // Even if NewAddMode is the same we still need to collect it due to
2805 // original value is different. And later we will need all original values
2806 // as anchors during finding the common Phi node.
2807 if (CanHandle)
2808 AddrModes.emplace_back(NewAddrMode);
2809 else
2810 AddrModes.clear();
2811
2812 return CanHandle;
John Brawn736bf002017-10-03 13:08:22 +00002813 }
2814
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002815 /// Combine the addressing modes we've collected into a single
John Brawn736bf002017-10-03 13:08:22 +00002816 /// addressing mode.
2817 /// \return True iff we successfully combined them or we only had one so
2818 /// didn't need to combine them anyway.
2819 bool combineAddrModes() {
2820 // If we have no AddrModes then they can't be combined.
2821 if (AddrModes.size() == 0)
2822 return false;
2823
2824 // A single AddrMode can trivially be combined.
Serguei Katkov505359f2017-11-20 05:42:36 +00002825 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
John Brawn736bf002017-10-03 13:08:22 +00002826 return true;
2827
2828 // If the AddrModes we collected are all just equal to the value they are
2829 // derived from then combining them wouldn't do anything useful.
2830 if (AllAddrModesTrivial)
2831 return false;
2832
John Brawn70cdb5b2017-11-24 14:10:45 +00002833 if (!addrModeCombiningAllowed())
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002834 return false;
2835
2836 // Build a map between <original value, basic block where we saw it> to
2837 // value of base register.
Serguei Katkov50364592017-11-29 05:51:26 +00002838 // Bail out if there is no common type.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002839 FoldAddrToValueMapping Map;
Serguei Katkov50364592017-11-29 05:51:26 +00002840 if (!initializeMap(Map))
2841 return false;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002842
2843 Value *CommonValue = findCommon(Map);
2844 if (CommonValue)
John Brawn70cdb5b2017-11-24 14:10:45 +00002845 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002846 return CommonValue != nullptr;
2847 }
2848
2849private:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002850 /// Initialize Map with anchor values. For address seen in some BB
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002851 /// we set the value of different field saw in this address.
2852 /// If address is not an instruction than basic block is set to null.
2853 /// At the same time we find a common type for different field we will
2854 /// use to create new Phi/Select nodes. Keep it in CommonType field.
Serguei Katkov50364592017-11-29 05:51:26 +00002855 /// Return false if there is no common type found.
2856 bool initializeMap(FoldAddrToValueMapping &Map) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002857 // Keep track of keys where the value is null. We will need to replace it
2858 // with constant null when we know the common type.
2859 SmallVector<ValueInBB, 2> NullValue;
John Brawn70cdb5b2017-11-24 14:10:45 +00002860 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002861 for (auto &AM : AddrModes) {
2862 BasicBlock *BB = nullptr;
2863 if (Instruction *I = dyn_cast<Instruction>(AM.OriginalValue))
2864 BB = I->getParent();
2865
John Brawn70cdb5b2017-11-24 14:10:45 +00002866 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002867 if (DV) {
Serguei Katkov50364592017-11-29 05:51:26 +00002868 auto *Type = DV->getType();
2869 if (CommonType && CommonType != Type)
2870 return false;
2871 CommonType = Type;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002872 Map[{ AM.OriginalValue, BB }] = DV;
2873 } else {
2874 NullValue.push_back({ AM.OriginalValue, BB });
2875 }
2876 }
2877 assert(CommonType && "At least one non-null value must be!");
2878 for (auto VIBB : NullValue)
2879 Map[VIBB] = Constant::getNullValue(CommonType);
Serguei Katkov50364592017-11-29 05:51:26 +00002880 return true;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002881 }
2882
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002883 /// We have mapping between value A and basic block where value A
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002884 /// seen to other value B where B was a field in addressing mode represented
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002885 /// by A. Also we have an original value C representing an address in some
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002886 /// basic block. Traversing from C through phi and selects we ended up with
2887 /// A's in a map. This utility function tries to find a value V which is a
2888 /// field in addressing mode C and traversing through phi nodes and selects
2889 /// we will end up in corresponded values B in a map.
2890 /// The utility will create a new Phi/Selects if needed.
2891 // The simple example looks as follows:
2892 // BB1:
2893 // p1 = b1 + 40
2894 // br cond BB2, BB3
2895 // BB2:
2896 // p2 = b2 + 40
2897 // br BB3
2898 // BB3:
2899 // p = phi [p1, BB1], [p2, BB2]
2900 // v = load p
2901 // Map is
2902 // <p1, BB1> -> b1
2903 // <p2, BB2> -> b2
2904 // Request is
2905 // <p, BB3> -> ?
2906 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3
2907 Value *findCommon(FoldAddrToValueMapping &Map) {
Eric Christopherd72f78e2018-01-09 23:25:38 +00002908 // Tracks the simplification of newly created phi nodes. The reason we use
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002909 // this mapping is because we will add new created Phi nodes in AddrToBase.
2910 // Simplification of Phi nodes is recursive, so some Phi node may
2911 // be simplified after we added it to AddrToBase.
2912 // Using this mapping we can find the current value in AddrToBase.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002913 SimplificationTracker ST(SQ);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002914
2915 // First step, DFS to create PHI nodes for all intermediate blocks.
2916 // Also fill traverse order for the second step.
2917 SmallVector<ValueInBB, 32> TraverseOrder;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002918 InsertPlaceholders(Map, TraverseOrder, ST);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002919
2920 // Second Step, fill new nodes by merged values and simplify if possible.
2921 FillPlaceholders(Map, TraverseOrder, ST);
2922
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002923 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
2924 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002925 return nullptr;
2926 }
2927
2928 // Now we'd like to match New Phi nodes to existed ones.
2929 unsigned PhiNotMatchedCount = 0;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002930 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
2931 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002932 return nullptr;
2933 }
2934
2935 auto *Result = ST.Get(Map.find(Original)->second);
2936 if (Result) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002937 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
2938 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002939 }
2940 return Result;
2941 }
2942
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002943 /// Try to match PHI node to Candidate.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002944 /// Matcher tracks the matched Phi nodes.
2945 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002946 SmallSetVector<PHIPair, 8> &Matcher,
2947 SmallSetVector<PHINode *, 32> &PhiNodesToMatch) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002948 SmallVector<PHIPair, 8> WorkList;
2949 Matcher.insert({ PHI, Candidate });
2950 WorkList.push_back({ PHI, Candidate });
2951 SmallSet<PHIPair, 8> Visited;
2952 while (!WorkList.empty()) {
2953 auto Item = WorkList.pop_back_val();
2954 if (!Visited.insert(Item).second)
2955 continue;
2956 // We iterate over all incoming values to Phi to compare them.
2957 // If values are different and both of them Phi and the first one is a
2958 // Phi we added (subject to match) and both of them is in the same basic
2959 // block then we can match our pair if values match. So we state that
2960 // these values match and add it to work list to verify that.
2961 for (auto B : Item.first->blocks()) {
2962 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
2963 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
2964 if (FirstValue == SecondValue)
2965 continue;
2966
2967 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
2968 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
2969
2970 // One of them is not Phi or
2971 // The first one is not Phi node from the set we'd like to match or
2972 // Phi nodes from different basic blocks then
2973 // we will not be able to match.
2974 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
2975 FirstPhi->getParent() != SecondPhi->getParent())
2976 return false;
2977
2978 // If we already matched them then continue.
2979 if (Matcher.count({ FirstPhi, SecondPhi }))
2980 continue;
2981 // So the values are different and does not match. So we need them to
2982 // match.
2983 Matcher.insert({ FirstPhi, SecondPhi });
2984 // But me must check it.
2985 WorkList.push_back({ FirstPhi, SecondPhi });
2986 }
2987 }
2988 return true;
2989 }
2990
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002991 /// For the given set of PHI nodes (in the SimplificationTracker) try
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002992 /// to find their equivalents.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002993 /// Returns false if this matching fails and creation of new Phi is disabled.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002994 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002995 unsigned &PhiNotMatchedCount) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002996 // Use a SetVector for Matched to make sure we do replacements (ReplacePhi)
2997 // in a deterministic order below.
2998 SmallSetVector<PHIPair, 8> Matched;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002999 SmallPtrSet<PHINode *, 8> WillNotMatch;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003000 SmallSetVector<PHINode *, 32> &PhiNodesToMatch = ST.newPhiNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003001 while (PhiNodesToMatch.size()) {
3002 PHINode *PHI = *PhiNodesToMatch.begin();
3003
3004 // Add us, if no Phi nodes in the basic block we do not match.
3005 WillNotMatch.clear();
3006 WillNotMatch.insert(PHI);
3007
3008 // Traverse all Phis until we found equivalent or fail to do that.
3009 bool IsMatched = false;
3010 for (auto &P : PHI->getParent()->phis()) {
3011 if (&P == PHI)
3012 continue;
3013 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3014 break;
3015 // If it does not match, collect all Phi nodes from matcher.
3016 // if we end up with no match, them all these Phi nodes will not match
3017 // later.
3018 for (auto M : Matched)
3019 WillNotMatch.insert(M.first);
3020 Matched.clear();
3021 }
3022 if (IsMatched) {
Serguei Katkova20e05b2018-03-12 03:50:07 +00003023 // Replace all matched values and erase them.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003024 for (auto MV : Matched)
3025 ST.ReplacePhi(MV.first, MV.second);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003026 Matched.clear();
3027 continue;
3028 }
3029 // If we are not allowed to create new nodes then bail out.
3030 if (!AllowNewPhiNodes)
3031 return false;
3032 // Just remove all seen values in matcher. They will not match anything.
3033 PhiNotMatchedCount += WillNotMatch.size();
3034 for (auto *P : WillNotMatch)
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003035 PhiNodesToMatch.remove(P);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003036 }
3037 return true;
3038 }
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003039 /// Fill the placeholder with values from predecessors and simplify it.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003040 void FillPlaceholders(FoldAddrToValueMapping &Map,
3041 SmallVectorImpl<ValueInBB> &TraverseOrder,
3042 SimplificationTracker &ST) {
3043 while (!TraverseOrder.empty()) {
3044 auto Current = TraverseOrder.pop_back_val();
3045 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
3046 Value *CurrentValue = Current.first;
3047 BasicBlock *CurrentBlock = Current.second;
3048 Value *V = Map[Current];
3049
3050 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3051 // CurrentValue also must be Select.
3052 auto *CurrentSelect = cast<SelectInst>(CurrentValue);
3053 auto *TrueValue = CurrentSelect->getTrueValue();
3054 ValueInBB TrueItem = { TrueValue, isa<Instruction>(TrueValue)
3055 ? CurrentBlock
3056 : nullptr };
3057 assert(Map.find(TrueItem) != Map.end() && "No True Value!");
Serguei Katkovb0b67a82017-12-18 04:25:07 +00003058 Select->setTrueValue(ST.Get(Map[TrueItem]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003059 auto *FalseValue = CurrentSelect->getFalseValue();
3060 ValueInBB FalseItem = { FalseValue, isa<Instruction>(FalseValue)
3061 ? CurrentBlock
3062 : nullptr };
3063 assert(Map.find(FalseItem) != Map.end() && "No False Value!");
Serguei Katkovb0b67a82017-12-18 04:25:07 +00003064 Select->setFalseValue(ST.Get(Map[FalseItem]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003065 } else {
3066 // Must be a Phi node then.
3067 PHINode *PHI = cast<PHINode>(V);
3068 // Fill the Phi node with values from predecessors.
3069 bool IsDefinedInThisBB =
3070 cast<Instruction>(CurrentValue)->getParent() == CurrentBlock;
3071 auto *CurrentPhi = dyn_cast<PHINode>(CurrentValue);
3072 for (auto B : predecessors(CurrentBlock)) {
3073 Value *PV = IsDefinedInThisBB
3074 ? CurrentPhi->getIncomingValueForBlock(B)
3075 : CurrentValue;
3076 ValueInBB item = { PV, isa<Instruction>(PV) ? B : nullptr };
3077 assert(Map.find(item) != Map.end() && "No predecessor Value!");
3078 PHI->addIncoming(ST.Get(Map[item]), B);
3079 }
3080 }
3081 // Simplify if possible.
3082 Map[Current] = ST.Simplify(V);
3083 }
3084 }
3085
3086 /// Starting from value recursively iterates over predecessors up to known
3087 /// ending values represented in a map. For each traversed block inserts
3088 /// a placeholder Phi or Select.
3089 /// Reports all new created Phi/Select nodes by adding them to set.
3090 /// Also reports and order in what basic blocks have been traversed.
3091 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3092 SmallVectorImpl<ValueInBB> &TraverseOrder,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003093 SimplificationTracker &ST) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003094 SmallVector<ValueInBB, 32> Worklist;
3095 assert((isa<PHINode>(Original.first) || isa<SelectInst>(Original.first)) &&
3096 "Address must be a Phi or Select node");
3097 auto *Dummy = UndefValue::get(CommonType);
3098 Worklist.push_back(Original);
3099 while (!Worklist.empty()) {
3100 auto Current = Worklist.pop_back_val();
3101 // If value is not an instruction it is something global, constant,
3102 // parameter and we can say that this value is observable in any block.
3103 // Set block to null to denote it.
3104 // Also please take into account that it is how we build anchors.
3105 if (!isa<Instruction>(Current.first))
3106 Current.second = nullptr;
3107 // if it is already visited or it is an ending value then skip it.
3108 if (Map.find(Current) != Map.end())
3109 continue;
3110 TraverseOrder.push_back(Current);
3111
3112 Value *CurrentValue = Current.first;
3113 BasicBlock *CurrentBlock = Current.second;
3114 // CurrentValue must be a Phi node or select. All others must be covered
3115 // by anchors.
3116 Instruction *CurrentI = cast<Instruction>(CurrentValue);
3117 bool IsDefinedInThisBB = CurrentI->getParent() == CurrentBlock;
3118
Vedant Kumare0b5f862018-05-10 23:01:54 +00003119 unsigned PredCount = pred_size(CurrentBlock);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003120 // if Current Value is not defined in this basic block we are interested
3121 // in values in predecessors.
3122 if (!IsDefinedInThisBB) {
3123 assert(PredCount && "Unreachable block?!");
3124 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3125 &CurrentBlock->front());
3126 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003127 ST.insertNewPhi(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003128 // Add all predecessors in work list.
3129 for (auto B : predecessors(CurrentBlock))
3130 Worklist.push_back({ CurrentValue, B });
3131 continue;
3132 }
3133 // Value is defined in this basic block.
3134 if (SelectInst *OrigSelect = dyn_cast<SelectInst>(CurrentI)) {
3135 // Is it OK to get metadata from OrigSelect?!
3136 // Create a Select placeholder with dummy value.
3137 SelectInst *Select =
3138 SelectInst::Create(OrigSelect->getCondition(), Dummy, Dummy,
3139 OrigSelect->getName(), OrigSelect, OrigSelect);
3140 Map[Current] = Select;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003141 ST.insertNewSelect(Select);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003142 // We are interested in True and False value in this basic block.
3143 Worklist.push_back({ OrigSelect->getTrueValue(), CurrentBlock });
3144 Worklist.push_back({ OrigSelect->getFalseValue(), CurrentBlock });
3145 } else {
3146 // It must be a Phi node then.
3147 auto *CurrentPhi = cast<PHINode>(CurrentI);
3148 // Create new Phi node for merge of bases.
3149 assert(PredCount && "Unreachable block?!");
3150 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3151 &CurrentBlock->front());
3152 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003153 ST.insertNewPhi(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003154
3155 // Add all predecessors in work list.
3156 for (auto B : predecessors(CurrentBlock))
3157 Worklist.push_back({ CurrentPhi->getIncomingValueForBlock(B), B });
3158 }
3159 }
John Brawn736bf002017-10-03 13:08:22 +00003160 }
John Brawn70cdb5b2017-11-24 14:10:45 +00003161
3162 bool addrModeCombiningAllowed() {
3163 if (DisableComplexAddrModes)
3164 return false;
3165 switch (DifferentField) {
3166 default:
3167 return false;
3168 case ExtAddrMode::BaseRegField:
3169 return AddrSinkCombineBaseReg;
3170 case ExtAddrMode::BaseGVField:
3171 return AddrSinkCombineBaseGV;
3172 case ExtAddrMode::BaseOffsField:
3173 return AddrSinkCombineBaseOffs;
3174 case ExtAddrMode::ScaledRegField:
3175 return AddrSinkCombineScaledReg;
3176 }
3177 }
John Brawn736bf002017-10-03 13:08:22 +00003178};
Eugene Zelenko900b6332017-08-29 22:32:07 +00003179} // end anonymous namespace
3180
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003181/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003182/// Return true and update AddrMode if this addr mode is legal for the target,
3183/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003184bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003185 unsigned Depth) {
3186 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3187 // mode. Just process that directly.
3188 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003189 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003190
Chandler Carruthc8925912013-01-05 02:09:22 +00003191 // If the scale is 0, it takes nothing to add this.
3192 if (Scale == 0)
3193 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003194
Chandler Carruthc8925912013-01-05 02:09:22 +00003195 // If we already have a scale of this value, we can add to it, otherwise, we
3196 // need an available scale field.
3197 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3198 return false;
3199
3200 ExtAddrMode TestAddrMode = AddrMode;
3201
3202 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3203 // [A+B + A*7] -> [B+A*8].
3204 TestAddrMode.Scale += Scale;
3205 TestAddrMode.ScaledReg = ScaleReg;
3206
3207 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003208 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003209 return false;
3210
3211 // It was legal, so commit it.
3212 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003213
Chandler Carruthc8925912013-01-05 02:09:22 +00003214 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3215 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3216 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003217 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003218 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3219 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3220 TestAddrMode.ScaledReg = AddLHS;
3221 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003222
Chandler Carruthc8925912013-01-05 02:09:22 +00003223 // If this addressing mode is legal, commit it and remember that we folded
3224 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003225 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003226 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3227 AddrMode = TestAddrMode;
3228 return true;
3229 }
3230 }
3231
3232 // Otherwise, not (x+c)*scale, just return what we have.
3233 return true;
3234}
3235
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003236/// This is a little filter, which returns true if an addressing computation
3237/// involving I might be folded into a load/store accessing it.
3238/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003239/// the set of instructions that MatchOperationAddr can.
3240static bool MightBeFoldableInst(Instruction *I) {
3241 switch (I->getOpcode()) {
3242 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003243 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003244 // Don't touch identity bitcasts.
3245 if (I->getType() == I->getOperand(0)->getType())
3246 return false;
Vedant Kumarb3091da2018-07-06 20:17:42 +00003247 return I->getType()->isIntOrPtrTy();
Chandler Carruthc8925912013-01-05 02:09:22 +00003248 case Instruction::PtrToInt:
3249 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3250 return true;
3251 case Instruction::IntToPtr:
3252 // We know the input is intptr_t, so this is foldable.
3253 return true;
3254 case Instruction::Add:
3255 return true;
3256 case Instruction::Mul:
3257 case Instruction::Shl:
3258 // Can only handle X*C and X << C.
3259 return isa<ConstantInt>(I->getOperand(1));
3260 case Instruction::GetElementPtr:
3261 return true;
3262 default:
3263 return false;
3264 }
3265}
3266
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003267/// Check whether or not \p Val is a legal instruction for \p TLI.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003268/// \note \p Val is assumed to be the product of some type promotion.
3269/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3270/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003271static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3272 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003273 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3274 if (!PromotedInst)
3275 return false;
3276 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3277 // If the ISDOpcode is undefined, it was undefined before the promotion.
3278 if (!ISDOpcode)
3279 return true;
3280 // Otherwise, check if the promoted instruction is legal or not.
3281 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003282 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003283}
3284
Eugene Zelenko900b6332017-08-29 22:32:07 +00003285namespace {
3286
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003287/// Hepler class to perform type promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003288class TypePromotionHelper {
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003289 /// Utility function to add a promoted instruction \p ExtOpnd to
3290 /// \p PromotedInsts and record the type of extension we have seen.
3291 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
3292 Instruction *ExtOpnd,
3293 bool IsSExt) {
3294 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3295 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
3296 if (It != PromotedInsts.end()) {
3297 // If the new extension is same as original, the information in
3298 // PromotedInsts[ExtOpnd] is still correct.
3299 if (It->second.getInt() == ExtTy)
3300 return;
3301
3302 // Now the new extension is different from old extension, we make
3303 // the type information invalid by setting extension type to
3304 // BothExtension.
3305 ExtTy = BothExtension;
3306 }
3307 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
3308 }
3309
3310 /// Utility function to query the original type of instruction \p Opnd
3311 /// with a matched extension type. If the extension doesn't match, we
3312 /// cannot use the information we had on the original type.
3313 /// BothExtension doesn't match any extension type.
3314 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
3315 Instruction *Opnd,
3316 bool IsSExt) {
3317 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3318 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3319 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
3320 return It->second.getPointer();
3321 return nullptr;
3322 }
3323
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003324 /// Utility function to check whether or not a sign or zero extension
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003325 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3326 /// either using the operands of \p Inst or promoting \p Inst.
3327 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003328 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003329 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003330 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003331 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003332 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003333 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003334 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003335 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3336 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003337
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003338 /// Utility function to determine if \p OpIdx should be promoted when
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003339 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003340 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003341 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003342 }
3343
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003344 /// Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003345 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003346 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003347 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003348 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003349 /// Newly added extensions are inserted in \p Exts.
3350 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003351 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003352 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003353 static Value *promoteOperandForTruncAndAnyExt(
3354 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003355 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003356 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003357 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003358
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003359 /// Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003360 /// operand is promotable and is not a supported trunc or sext.
3361 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003362 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003363 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003364 /// Newly added extensions are inserted in \p Exts.
3365 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003366 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003367 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003368 static Value *promoteOperandForOther(Instruction *Ext,
3369 TypePromotionTransaction &TPT,
3370 InstrToOrigTy &PromotedInsts,
3371 unsigned &CreatedInstsCost,
3372 SmallVectorImpl<Instruction *> *Exts,
3373 SmallVectorImpl<Instruction *> *Truncs,
3374 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003375
3376 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003377 static Value *signExtendOperandForOther(
3378 Instruction *Ext, TypePromotionTransaction &TPT,
3379 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3380 SmallVectorImpl<Instruction *> *Exts,
3381 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3382 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3383 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003384 }
3385
3386 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003387 static Value *zeroExtendOperandForOther(
3388 Instruction *Ext, TypePromotionTransaction &TPT,
3389 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3390 SmallVectorImpl<Instruction *> *Exts,
3391 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3392 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3393 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003394 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003395
3396public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003397 /// Type for the utility function that promotes the operand of Ext.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003398 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3399 InstrToOrigTy &PromotedInsts,
3400 unsigned &CreatedInstsCost,
3401 SmallVectorImpl<Instruction *> *Exts,
3402 SmallVectorImpl<Instruction *> *Truncs,
3403 const TargetLowering &TLI);
3404
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003405 /// Given a sign/zero extend instruction \p Ext, return the appropriate
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003406 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003407 /// \return NULL if no promotable action is possible with the current
3408 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003409 /// \p InsertedInsts keeps track of all the instructions inserted by the
3410 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003411 /// because we do not want to promote these instructions as CodeGenPrepare
3412 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3413 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003414 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003415 const TargetLowering &TLI,
3416 const InstrToOrigTy &PromotedInsts);
3417};
3418
Eugene Zelenko900b6332017-08-29 22:32:07 +00003419} // end anonymous namespace
3420
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003421bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003422 Type *ConsideredExtType,
3423 const InstrToOrigTy &PromotedInsts,
3424 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003425 // The promotion helper does not know how to deal with vector types yet.
3426 // To be able to fix that, we would need to fix the places where we
3427 // statically extend, e.g., constants and such.
3428 if (Inst->getType()->isVectorTy())
3429 return false;
3430
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003431 // We can always get through zext.
3432 if (isa<ZExtInst>(Inst))
3433 return true;
3434
3435 // sext(sext) is ok too.
3436 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003437 return true;
3438
3439 // We can get through binary operator, if it is legal. In other words, the
3440 // binary operator must have a nuw or nsw flag.
3441 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3442 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003443 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3444 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003445 return true;
3446
Guozhi Weic4c6b542018-06-05 21:03:52 +00003447 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
3448 if ((Inst->getOpcode() == Instruction::And ||
3449 Inst->getOpcode() == Instruction::Or))
3450 return true;
3451
3452 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
3453 if (Inst->getOpcode() == Instruction::Xor) {
3454 const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1));
3455 // Make sure it is not a NOT.
3456 if (Cst && !Cst->getValue().isAllOnesValue())
3457 return true;
3458 }
3459
3460 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
3461 // It may change a poisoned value into a regular value, like
3462 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
3463 // poisoned value regular value
3464 // It should be OK since undef covers valid value.
3465 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
3466 return true;
3467
3468 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
3469 // It may change a poisoned value into a regular value, like
3470 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
3471 // poisoned value regular value
3472 // It should be OK since undef covers valid value.
3473 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
3474 const Instruction *ExtInst =
3475 dyn_cast<const Instruction>(*Inst->user_begin());
3476 if (ExtInst->hasOneUse()) {
3477 const Instruction *AndInst =
3478 dyn_cast<const Instruction>(*ExtInst->user_begin());
3479 if (AndInst && AndInst->getOpcode() == Instruction::And) {
3480 const ConstantInt *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
3481 if (Cst &&
3482 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
3483 return true;
3484 }
3485 }
3486 }
3487
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003488 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003489 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003490 if (!isa<TruncInst>(Inst))
3491 return false;
3492
3493 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003494 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003495 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003496 if (!OpndVal->getType()->isIntegerTy() ||
3497 OpndVal->getType()->getIntegerBitWidth() >
3498 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003499 return false;
3500
3501 // If the operand of the truncate is not an instruction, we will not have
3502 // any information on the dropped bits.
3503 // (Actually we could for constant but it is not worth the extra logic).
3504 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3505 if (!Opnd)
3506 return false;
3507
3508 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003509 // I.e., check that trunc just drops extended bits of the same kind of
3510 // the extension.
3511 // #1 get the type of the operand and check the kind of the extended bits.
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003512 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
3513 if (OpndType)
3514 ;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003515 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3516 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003517 else
3518 return false;
3519
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003520 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003521 return Inst->getType()->getIntegerBitWidth() >=
3522 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003523}
3524
3525TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003526 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003527 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003528 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3529 "Unexpected instruction type");
3530 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3531 Type *ExtTy = Ext->getType();
3532 bool IsSExt = isa<SExtInst>(Ext);
3533 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003534 // get through.
3535 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003536 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003537 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003538
3539 // Do not promote if the operand has been added by codegenprepare.
3540 // Otherwise, it means we are undoing an optimization that is likely to be
3541 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003542 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003543 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003544
3545 // SExt or Trunc instructions.
3546 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003547 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3548 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003549 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003550
3551 // Regular instruction.
3552 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003553 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003554 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003555 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003556}
3557
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003558Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003559 Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003560 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003561 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003562 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003563 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3564 // get through it and this method should not be called.
3565 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003566 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003567 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003568 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003569 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003570 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003571 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003572 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003573 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3574 TPT.replaceAllUsesWith(SExt, ZExt);
3575 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003576 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003577 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003578 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3579 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003580 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3581 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003582 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003583
3584 // Remove dead code.
3585 if (SExtOpnd->use_empty())
3586 TPT.eraseInstruction(SExtOpnd);
3587
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003588 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003589 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003590 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003591 if (ExtInst) {
3592 if (Exts)
3593 Exts->push_back(ExtInst);
3594 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3595 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003596 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003597 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003598
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003599 // At this point we have: ext ty opnd to ty.
3600 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3601 Value *NextVal = ExtInst->getOperand(0);
3602 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003603 return NextVal;
3604}
3605
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003606Value *TypePromotionHelper::promoteOperandForOther(
3607 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003608 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003609 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003610 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3611 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003612 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003613 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003614 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003615 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003616 if (!ExtOpnd->hasOneUse()) {
3617 // ExtOpnd will be promoted.
3618 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003619 // promoted version.
3620 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003621 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003622 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
Quentin Colombetac55b152014-09-16 22:36:07 +00003623 // Insert it just after the definition.
Sanjay Patel674d2c22017-08-29 14:07:48 +00003624 ITrunc->moveAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003625 if (Truncs)
3626 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003627 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003628
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003629 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003630 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003631 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003632 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003633 }
3634
3635 // Get through the Instruction:
3636 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003637 // 2. Replace the uses of Ext by Inst.
3638 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003639
3640 // Remember the original type of the instruction before promotion.
3641 // This is useful to know that the high bits are sign extended bits.
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003642 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003643 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003644 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003645 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003646 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003647 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003648 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003649
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003650 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003651 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003652 ++OpIdx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003653 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003654 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3655 !shouldExtOperand(ExtOpnd, OpIdx)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003656 LLVM_DEBUG(dbgs() << "No need to propagate\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003657 continue;
3658 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003659 // Check if we can statically extend the operand.
3660 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003661 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003662 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003663 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3664 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3665 : Cst->getValue().zext(BitWidth);
3666 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003667 continue;
3668 }
3669 // UndefValue are typed, so we have to statically sign extend them.
3670 if (isa<UndefValue>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003671 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003672 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003673 continue;
3674 }
3675
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003676 // Otherwise we have to explicitly sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003677 // Check if Ext was reused to extend an operand.
3678 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003679 // If yes, create a new one.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003680 LLVM_DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003681 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3682 : TPT.createZExt(Ext, Opnd, Ext->getType());
3683 if (!isa<Instruction>(ValForExtOpnd)) {
3684 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3685 continue;
3686 }
3687 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003688 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003689 if (Exts)
3690 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003691 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003692
3693 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003694 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3695 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003696 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003697 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003698 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003699 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003700 if (ExtForOpnd == Ext) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003701 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003702 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003703 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003704 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003705}
3706
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003707/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003708/// \p NewCost gives the cost of extension instructions created by the
3709/// promotion.
3710/// \p OldCost gives the cost of extension instructions before the promotion
3711/// plus the number of instructions that have been
3712/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003713/// \p PromotedOperand is the value that has been promoted.
3714/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003715bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003716 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003717 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
3718 << '\n');
Quentin Colombet1b274f92015-03-10 21:48:15 +00003719 // The cost of the new extensions is greater than the cost of the
3720 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003721 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003722 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003723 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003724 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003725 return true;
3726 // The promotion is neutral but it may help folding the sign extension in
3727 // loads for instance.
3728 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003729 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003730}
3731
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003732/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003733/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003734/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003735/// If \p MovedAway is not NULL, it contains the information of whether or
3736/// not AddrInst has to be folded into the addressing mode on success.
3737/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3738/// because it has been moved away.
3739/// Thus AddrInst must not be added in the matched instructions.
3740/// This state can happen when AddrInst is a sext, since it may be moved away.
3741/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3742/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003743bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003744 unsigned Depth,
3745 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003746 // Avoid exponential behavior on extremely deep expression trees.
3747 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003748
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003749 // By default, all matched instructions stay in place.
3750 if (MovedAway)
3751 *MovedAway = false;
3752
Chandler Carruthc8925912013-01-05 02:09:22 +00003753 switch (Opcode) {
3754 case Instruction::PtrToInt:
3755 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003756 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003757 case Instruction::IntToPtr: {
3758 auto AS = AddrInst->getType()->getPointerAddressSpace();
3759 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003760 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003761 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003762 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003763 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003764 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003765 case Instruction::BitCast:
3766 // BitCast is always a noop, and we can handle it as long as it is
3767 // int->int or pointer->pointer (we don't want int<->fp or something).
Vedant Kumarb3091da2018-07-06 20:17:42 +00003768 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
Chandler Carruthc8925912013-01-05 02:09:22 +00003769 // Don't touch identity bitcasts. These were probably put here by LSR,
3770 // and we don't want to mess around with them. Assume it knows what it
3771 // is doing.
3772 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003773 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003774 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003775 case Instruction::AddrSpaceCast: {
3776 unsigned SrcAS
3777 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3778 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3779 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003780 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003781 return false;
3782 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003783 case Instruction::Add: {
3784 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3785 ExtAddrMode BackupAddrMode = AddrMode;
3786 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003787 // Start a transaction at this point.
3788 // The LHS may match but not the RHS.
3789 // Therefore, we need a higher level restoration point to undo partially
3790 // matched operation.
3791 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3792 TPT.getRestorationPoint();
3793
Sanjay Patelfc580a62015-09-21 23:03:16 +00003794 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3795 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003796 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003797
Chandler Carruthc8925912013-01-05 02:09:22 +00003798 // Restore the old addr mode info.
3799 AddrMode = BackupAddrMode;
3800 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003801 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003802
Chandler Carruthc8925912013-01-05 02:09:22 +00003803 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003804 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3805 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003806 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003807
Chandler Carruthc8925912013-01-05 02:09:22 +00003808 // Otherwise we definitely can't merge the ADD in.
3809 AddrMode = BackupAddrMode;
3810 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003811 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003812 break;
3813 }
3814 //case Instruction::Or:
3815 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3816 //break;
3817 case Instruction::Mul:
3818 case Instruction::Shl: {
3819 // Can only handle X*C and X << C.
3820 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Philip Reames9c3cbee2017-10-30 23:59:51 +00003821 if (!RHS || RHS->getBitWidth() > 64)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003822 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003823 int64_t Scale = RHS->getSExtValue();
3824 if (Opcode == Instruction::Shl)
3825 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003826
Sanjay Patelfc580a62015-09-21 23:03:16 +00003827 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003828 }
3829 case Instruction::GetElementPtr: {
3830 // Scan the GEP. We check it if it contains constant offsets and at most
3831 // one variable offset.
3832 int VariableOperand = -1;
3833 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003834
Chandler Carruthc8925912013-01-05 02:09:22 +00003835 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003836 gep_type_iterator GTI = gep_type_begin(AddrInst);
3837 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003838 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003839 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003840 unsigned Idx =
3841 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3842 ConstantOffset += SL->getElementOffset(Idx);
3843 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003844 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003845 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
Simon Pilgrimee82a792018-08-13 12:10:09 +00003846 const APInt &CVal = CI->getValue();
3847 if (CVal.getMinSignedBits() <= 64) {
3848 ConstantOffset += CVal.getSExtValue() * TypeSize;
3849 continue;
3850 }
3851 }
3852 if (TypeSize) { // Scales of zero don't do anything.
Chandler Carruthc8925912013-01-05 02:09:22 +00003853 // We only allow one variable index at the moment.
3854 if (VariableOperand != -1)
3855 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003856
Chandler Carruthc8925912013-01-05 02:09:22 +00003857 // Remember the variable index.
3858 VariableOperand = i;
3859 VariableScale = TypeSize;
3860 }
3861 }
3862 }
Stephen Lin837bba12013-07-15 17:55:02 +00003863
Chandler Carruthc8925912013-01-05 02:09:22 +00003864 // A common case is for the GEP to only do a constant offset. In this case,
3865 // just add it to the disp field and check validity.
3866 if (VariableOperand == -1) {
3867 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003868 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003869 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003870 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003871 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003872 return true;
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00003873 } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
3874 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
3875 ConstantOffset > 0) {
3876 // Record GEPs with non-zero offsets as candidates for splitting in the
3877 // event that the offset cannot fit into the r+i addressing mode.
3878 // Simple and common case that only one GEP is used in calculating the
3879 // address for the memory access.
3880 Value *Base = AddrInst->getOperand(0);
3881 auto *BaseI = dyn_cast<Instruction>(Base);
3882 auto *GEP = cast<GetElementPtrInst>(AddrInst);
3883 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
3884 (BaseI && !isa<CastInst>(BaseI) &&
3885 !isa<GetElementPtrInst>(BaseI))) {
3886 // If the base is an instruction, make sure the GEP is not in the same
3887 // basic block as the base. If the base is an argument or global
3888 // value, make sure the GEP is not in the entry block. Otherwise,
3889 // instruction selection can undo the split. Also make sure the
3890 // parent block allows inserting non-PHI instructions before the
3891 // terminator.
3892 BasicBlock *Parent =
3893 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
3894 if (GEP->getParent() != Parent && !Parent->getTerminator()->isEHPad())
3895 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
3896 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003897 }
3898 AddrMode.BaseOffs -= ConstantOffset;
3899 return false;
3900 }
3901
3902 // Save the valid addressing mode in case we can't match.
3903 ExtAddrMode BackupAddrMode = AddrMode;
3904 unsigned OldSize = AddrModeInsts.size();
3905
3906 // See if the scale and offset amount is valid for this target.
3907 AddrMode.BaseOffs += ConstantOffset;
3908
3909 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003910 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003911 // If it couldn't be matched, just stuff the value in a register.
3912 if (AddrMode.HasBaseReg) {
3913 AddrMode = BackupAddrMode;
3914 AddrModeInsts.resize(OldSize);
3915 return false;
3916 }
3917 AddrMode.HasBaseReg = true;
3918 AddrMode.BaseReg = AddrInst->getOperand(0);
3919 }
3920
3921 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003922 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003923 Depth)) {
3924 // If it couldn't be matched, try stuffing the base into a register
3925 // instead of matching it, and retrying the match of the scale.
3926 AddrMode = BackupAddrMode;
3927 AddrModeInsts.resize(OldSize);
3928 if (AddrMode.HasBaseReg)
3929 return false;
3930 AddrMode.HasBaseReg = true;
3931 AddrMode.BaseReg = AddrInst->getOperand(0);
3932 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003933 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003934 VariableScale, Depth)) {
3935 // If even that didn't work, bail.
3936 AddrMode = BackupAddrMode;
3937 AddrModeInsts.resize(OldSize);
3938 return false;
3939 }
3940 }
3941
3942 return true;
3943 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003944 case Instruction::SExt:
3945 case Instruction::ZExt: {
3946 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3947 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003948 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003949
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003950 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003951 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003952 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003953 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003954 if (!TPH)
3955 return false;
3956
3957 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3958 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003959 unsigned CreatedInstsCost = 0;
3960 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003961 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003962 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003963 // SExt has been moved away.
3964 // Thus either it will be rematched later in the recursive calls or it is
3965 // gone. Anyway, we must not fold it into the addressing mode at this point.
3966 // E.g.,
3967 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003968 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003969 // addr = gep base, idx
3970 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003971 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003972 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3973 // addr = gep base, op <- match
3974 if (MovedAway)
3975 *MovedAway = true;
3976
3977 assert(PromotedOperand &&
3978 "TypePromotionHelper should have filtered out those cases");
3979
3980 ExtAddrMode BackupAddrMode = AddrMode;
3981 unsigned OldSize = AddrModeInsts.size();
3982
Sanjay Patelfc580a62015-09-21 23:03:16 +00003983 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003984 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003985 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003986 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003987 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003988 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003989 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003990 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003991 AddrMode = BackupAddrMode;
3992 AddrModeInsts.resize(OldSize);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003993 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003994 TPT.rollback(LastKnownGood);
3995 return false;
3996 }
3997 return true;
3998 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003999 }
4000 return false;
4001}
4002
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004003/// If we can, try to add the value of 'Addr' into the current addressing mode.
4004/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4005/// unmodified. This assumes that Addr is either a pointer type or intptr_t
4006/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00004007///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004008bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004009 // Start a transaction at this point that we will rollback if the matching
4010 // fails.
4011 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4012 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00004013 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4014 // Fold in immediates if legal for the target.
4015 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004016 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004017 return true;
4018 AddrMode.BaseOffs -= CI->getSExtValue();
4019 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4020 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00004021 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004022 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004023 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004024 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00004025 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004026 }
4027 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4028 ExtAddrMode BackupAddrMode = AddrMode;
4029 unsigned OldSize = AddrModeInsts.size();
4030
4031 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004032 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004033 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004034 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004035 // to check here.
4036 if (MovedAway)
4037 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004038 // Okay, it's possible to fold this. Check to see if it is actually
4039 // *profitable* to do so. We use a simple cost model to avoid increasing
4040 // register pressure too much.
4041 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00004042 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004043 AddrModeInsts.push_back(I);
4044 return true;
4045 }
Stephen Lin837bba12013-07-15 17:55:02 +00004046
Chandler Carruthc8925912013-01-05 02:09:22 +00004047 // It isn't profitable to do this, roll back.
4048 //cerr << "NOT FOLDING: " << *I;
4049 AddrMode = BackupAddrMode;
4050 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004051 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004052 }
4053 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00004054 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00004055 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004056 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004057 } else if (isa<ConstantPointerNull>(Addr)) {
4058 // Null pointer gets folded without affecting the addressing mode.
4059 return true;
4060 }
4061
4062 // Worse case, the target should support [reg] addressing modes. :)
4063 if (!AddrMode.HasBaseReg) {
4064 AddrMode.HasBaseReg = true;
4065 AddrMode.BaseReg = Addr;
4066 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004067 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004068 return true;
4069 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00004070 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004071 }
4072
4073 // If the base register is already taken, see if we can do [r+r].
4074 if (AddrMode.Scale == 0) {
4075 AddrMode.Scale = 1;
4076 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004077 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004078 return true;
4079 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00004080 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004081 }
4082 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004083 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004084 return false;
4085}
4086
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004087/// Check to see if all uses of OpVal by the specified inline asm call are due
4088/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00004089static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004090 const TargetLowering &TLI,
4091 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00004092 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00004093 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004094 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004095 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004096
Chandler Carruthc8925912013-01-05 02:09:22 +00004097 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4098 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00004099
Chandler Carruthc8925912013-01-05 02:09:22 +00004100 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004101 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00004102
4103 // If this asm operand is our Value*, and if it isn't an indirect memory
4104 // operand, we can't fold it!
4105 if (OpInfo.CallOperandVal == OpVal &&
4106 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4107 !OpInfo.isIndirect))
4108 return false;
4109 }
4110
4111 return true;
4112}
4113
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004114// Max number of memory uses to look at before aborting the search to conserve
4115// compile time.
4116static constexpr int MaxMemoryUsesToScan = 20;
4117
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004118/// Recursively walk all the uses of I until we find a memory use.
4119/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00004120/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00004121static bool FindAllMemoryUses(
4122 Instruction *I,
4123 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004124 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4125 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004126 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00004127 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00004128 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004129
Chandler Carruthc8925912013-01-05 02:09:22 +00004130 // If this is an obviously unfoldable instruction, bail out.
4131 if (!MightBeFoldableInst(I))
4132 return true;
4133
Philip Reamesac115ed2016-03-09 23:13:12 +00004134 const bool OptSize = I->getFunction()->optForSize();
4135
Chandler Carruthc8925912013-01-05 02:09:22 +00004136 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004137 for (Use &U : I->uses()) {
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004138 // Conservatively return true if we're seeing a large number or a deep chain
4139 // of users. This avoids excessive compilation times in pathological cases.
4140 if (SeenInsts++ >= MaxMemoryUsesToScan)
4141 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004142
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004143 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthcdf47882014-03-09 03:16:01 +00004144 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4145 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00004146 continue;
4147 }
Stephen Lin837bba12013-07-15 17:55:02 +00004148
Chandler Carruthcdf47882014-03-09 03:16:01 +00004149 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4150 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00004151 if (opNo != StoreInst::getPointerOperandIndex())
4152 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00004153 MemoryUses.push_back(std::make_pair(SI, opNo));
4154 continue;
4155 }
Stephen Lin837bba12013-07-15 17:55:02 +00004156
Matt Arsenault02d915b2017-03-15 22:35:20 +00004157 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4158 unsigned opNo = U.getOperandNo();
4159 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4160 return true; // Storing addr, not into addr.
4161 MemoryUses.push_back(std::make_pair(RMW, opNo));
4162 continue;
4163 }
4164
4165 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4166 unsigned opNo = U.getOperandNo();
4167 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4168 return true; // Storing addr, not into addr.
4169 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4170 continue;
4171 }
4172
Chandler Carruthcdf47882014-03-09 03:16:01 +00004173 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004174 // If this is a cold call, we can sink the addressing calculation into
4175 // the cold path. See optimizeCallInst
4176 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4177 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004178
Chandler Carruthc8925912013-01-05 02:09:22 +00004179 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4180 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004181
Chandler Carruthc8925912013-01-05 02:09:22 +00004182 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004183 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004184 return true;
4185 continue;
4186 }
Stephen Lin837bba12013-07-15 17:55:02 +00004187
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004188 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4189 SeenInsts))
Chandler Carruthc8925912013-01-05 02:09:22 +00004190 return true;
4191 }
4192
4193 return false;
4194}
4195
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004196/// Return true if Val is already known to be live at the use site that we're
4197/// folding it into. If so, there is no cost to include it in the addressing
4198/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4199/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004200bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004201 Value *KnownLive2) {
4202 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004203 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004204 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004205
Chandler Carruthc8925912013-01-05 02:09:22 +00004206 // All values other than instructions and arguments (e.g. constants) are live.
4207 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004208
Chandler Carruthc8925912013-01-05 02:09:22 +00004209 // If Val is a constant sized alloca in the entry block, it is live, this is
4210 // true because it is just a reference to the stack/frame pointer, which is
4211 // live for the whole function.
4212 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4213 if (AI->isStaticAlloca())
4214 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004215
Chandler Carruthc8925912013-01-05 02:09:22 +00004216 // Check to see if this value is already used in the memory instruction's
4217 // block. If so, it's already live into the block at the very least, so we
4218 // can reasonably fold it.
4219 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4220}
4221
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004222/// It is possible for the addressing mode of the machine to fold the specified
4223/// instruction into a load or store that ultimately uses it.
4224/// However, the specified instruction has multiple uses.
4225/// Given this, it may actually increase register pressure to fold it
4226/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004227///
4228/// X = ...
4229/// Y = X+1
4230/// use(Y) -> nonload/store
4231/// Z = Y+1
4232/// load Z
4233///
4234/// In this case, Y has multiple uses, and can be folded into the load of Z
4235/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4236/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4237/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4238/// number of computations either.
4239///
4240/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4241/// X was live across 'load Z' for other reasons, we actually *would* want to
4242/// fold the addressing mode in the Z case. This would make Y die earlier.
4243bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004244isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004245 ExtAddrMode &AMAfter) {
4246 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004247
Chandler Carruthc8925912013-01-05 02:09:22 +00004248 // AMBefore is the addressing mode before this instruction was folded into it,
4249 // and AMAfter is the addressing mode after the instruction was folded. Get
4250 // the set of registers referenced by AMAfter and subtract out those
4251 // referenced by AMBefore: this is the set of values which folding in this
4252 // address extends the lifetime of.
4253 //
4254 // Note that there are only two potential values being referenced here,
4255 // BaseReg and ScaleReg (global addresses are always available, as are any
4256 // folded immediates).
4257 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004258
Chandler Carruthc8925912013-01-05 02:09:22 +00004259 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4260 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004261 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004262 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004263 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004264 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004265
4266 // If folding this instruction (and it's subexprs) didn't extend any live
4267 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004268 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004269 return true;
4270
Philip Reamesac115ed2016-03-09 23:13:12 +00004271 // If all uses of this instruction can have the address mode sunk into them,
4272 // we can remove the addressing mode and effectively trade one live register
4273 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004274 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004275 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4276 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004277 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004278 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004279
Chandler Carruthc8925912013-01-05 02:09:22 +00004280 // Now that we know that all uses of this instruction are part of a chain of
4281 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004282 // into a memory use, loop over each of these memory operation uses and see
4283 // if they could *actually* fold the instruction. The assumption is that
4284 // addressing modes are cheap and that duplicating the computation involved
4285 // many times is worthwhile, even on a fastpath. For sinking candidates
4286 // (i.e. cold call sites), this serves as a way to prevent excessive code
4287 // growth since most architectures have some reasonable small and fast way to
4288 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004289 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4290 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4291 Instruction *User = MemoryUses[i].first;
4292 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004293
Chandler Carruthc8925912013-01-05 02:09:22 +00004294 // Get the access type of this use. If the use isn't a pointer, we don't
4295 // know what it accesses.
4296 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004297 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4298 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004299 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004300 Type *AddressAccessTy = AddrTy->getElementType();
4301 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004302
Chandler Carruthc8925912013-01-05 02:09:22 +00004303 // Do a match against the root of this address, ignoring profitability. This
4304 // will tell us if the addressing mode for the memory operation will
4305 // *actually* cover the shared instruction.
4306 ExtAddrMode Result;
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004307 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4308 0);
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004309 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4310 TPT.getRestorationPoint();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004311 AddressingModeMatcher Matcher(
4312 MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result,
4313 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Chandler Carruthc8925912013-01-05 02:09:22 +00004314 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004315 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004316 (void)Success; assert(Success && "Couldn't select *anything*?");
4317
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004318 // The match was to check the profitability, the changes made are not
4319 // part of the original matcher. Therefore, they should be dropped
4320 // otherwise the original matcher will not present the right state.
4321 TPT.rollback(LastKnownGood);
4322
Chandler Carruthc8925912013-01-05 02:09:22 +00004323 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004324 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004325 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004326
Chandler Carruthc8925912013-01-05 02:09:22 +00004327 MatchedAddrModeInsts.clear();
4328 }
Stephen Lin837bba12013-07-15 17:55:02 +00004329
Chandler Carruthc8925912013-01-05 02:09:22 +00004330 return true;
4331}
4332
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004333/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004334/// different basic block than BB.
4335static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4336 if (Instruction *I = dyn_cast<Instruction>(V))
4337 return I->getParent() != BB;
4338 return false;
4339}
4340
Philip Reamesac115ed2016-03-09 23:13:12 +00004341/// Sink addressing mode computation immediate before MemoryInst if doing so
4342/// can be done without increasing register pressure. The need for the
4343/// register pressure constraint means this can end up being an all or nothing
4344/// decision for all uses of the same addressing computation.
4345///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004346/// Load and Store Instructions often have addressing modes that can do
4347/// significant amounts of computation. As such, instruction selection will try
4348/// to get the load or store to do as much computation as possible for the
4349/// program. The problem is that isel can only see within a single block. As
4350/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004351///
4352/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004353/// operands. It's also used to sink addressing computations feeding into cold
4354/// call sites into their (cold) basic block.
4355///
4356/// The motivation for handling sinking into cold blocks is that doing so can
4357/// both enable other address mode sinking (by satisfying the register pressure
4358/// constraint above), and reduce register pressure globally (by removing the
4359/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004360bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004361 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004362 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004363
4364 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004365 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004366 SmallVector<Value*, 8> worklist;
4367 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004368 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004369
John Brawneb83c752017-10-03 13:04:15 +00004370 // Use a worklist to iteratively look through PHI and select nodes, and
4371 // ensure that the addressing mode obtained from the non-PHI/select roots of
John Brawn736bf002017-10-03 13:08:22 +00004372 // the graph are compatible.
John Brawneb83c752017-10-03 13:04:15 +00004373 bool PhiOrSelectSeen = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004374 SmallVector<Instruction*, 16> AddrModeInsts;
Serguei Katkovaee63752017-11-05 07:59:02 +00004375 const SimplifyQuery SQ(*DL, TLInfo);
4376 AddressingModeCombiner AddrModes(SQ, { Addr, MemoryInst->getParent() });
Jun Bum Limdee55652017-04-03 19:20:07 +00004377 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004378 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4379 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004380 while (!worklist.empty()) {
4381 Value *V = worklist.back();
4382 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004383
Serguei Katkov4ea855e2017-07-19 04:49:17 +00004384 // We allow traversing cyclic Phi nodes.
4385 // In case of success after this loop we ensure that traversing through
4386 // Phi nodes ends up with all cases to compute address of the form
4387 // BaseGV + Base + Scale * Index + Offset
4388 // where Scale and Offset are constans and BaseGV, Base and Index
4389 // are exactly the same Values in all cases.
4390 // It means that BaseGV, Scale and Offset dominate our memory instruction
4391 // and have the same value as they had in address computation represented
4392 // as Phi. So we can safely sink address computation to memory instruction.
4393 if (!Visited.insert(V).second)
4394 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00004395
Owen Anderson8ba5f392010-11-27 08:15:55 +00004396 // For a PHI node, push all of its incoming values.
4397 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004398 for (Value *IncValue : P->incoming_values())
4399 worklist.push_back(IncValue);
John Brawneb83c752017-10-03 13:04:15 +00004400 PhiOrSelectSeen = true;
4401 continue;
4402 }
4403 // Similar for select.
4404 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4405 worklist.push_back(SI->getFalseValue());
4406 worklist.push_back(SI->getTrueValue());
4407 PhiOrSelectSeen = true;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004408 continue;
4409 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004410
Philip Reamesac115ed2016-03-09 23:13:12 +00004411 // For non-PHIs, determine the addressing mode being computed. Note that
4412 // the result may differ depending on what other uses our candidate
4413 // addressing instructions might have.
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004414 AddrModeInsts.clear();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004415 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4416 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004417 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004418 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004419 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004420
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004421 GetElementPtrInst *GEP = LargeOffsetGEP.first;
4422 if (GEP && GEP->getParent() != MemoryInst->getParent() &&
4423 !NewGEPBases.count(GEP)) {
4424 // If splitting the underlying data structure can reduce the offset of a
4425 // GEP, collect the GEP. Skip the GEPs that are the new bases of
4426 // previously split data structures.
4427 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
4428 if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
4429 LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
4430 }
4431
4432 NewAddrMode.OriginalValue = V;
John Brawn736bf002017-10-03 13:08:22 +00004433 if (!AddrModes.addNewAddrMode(NewAddrMode))
4434 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004435 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004436
John Brawn736bf002017-10-03 13:08:22 +00004437 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4438 // or we have multiple but either couldn't combine them or combining them
4439 // wouldn't do anything useful, bail out now.
4440 if (!AddrModes.combineAddrModes()) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004441 TPT.rollback(LastKnownGood);
4442 return false;
4443 }
4444 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004445
John Brawn736bf002017-10-03 13:08:22 +00004446 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4447 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4448
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004449 // If all the instructions matched are already in this BB, don't do anything.
John Brawneb83c752017-10-03 13:04:15 +00004450 // If we saw a Phi node then it is not local definitely, and if we saw a select
4451 // then we want to push the address calculation past it even if it's already
4452 // in this BB.
4453 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
Justin Lebar838c7f52016-11-21 22:49:11 +00004454 return IsNonLocalValue(V, MemoryInst->getParent());
Serguei Katkov0b7b59a2017-07-11 06:24:44 +00004455 })) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004456 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
4457 << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004458 return false;
4459 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004460
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004461 // Insert this computation right after this user. Since our caller is
4462 // scanning from the top of the BB to the bottom, reuse of the expr are
4463 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004464 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004465
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004466 // Now that we determined the addressing expression we want to use and know
4467 // that we have to sink it into this block. Check to see if we have already
Simon Dardis230f4532017-11-24 16:45:28 +00004468 // done this for some other load/store instr in this block. If so, reuse
4469 // the computation. Before attempting reuse, check if the address is valid
4470 // as it may have been erased.
4471
4472 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
4473
4474 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004475 if (SunkAddr) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004476 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
4477 << " for " << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004478 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004479 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004480 } else if (AddrSinkUsingGEPs ||
David Blaikie8ad9a972018-03-28 22:28:50 +00004481 (!AddrSinkUsingGEPs.getNumOccurrences() && TM && TTI->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004482 // By default, we use the GEP-based method when AA is used later. This
4483 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004484 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4485 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004486 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004487 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004488
4489 // First, find the pointer.
4490 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4491 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004492 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004493 }
4494
4495 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4496 // We can't add more than one pointer together, nor can we scale a
4497 // pointer (both of which seem meaningless).
4498 if (ResultPtr || AddrMode.Scale != 1)
4499 return false;
4500
4501 ResultPtr = AddrMode.ScaledReg;
4502 AddrMode.Scale = 0;
4503 }
4504
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004505 // It is only safe to sign extend the BaseReg if we know that the math
4506 // required to create it did not overflow before we extend it. Since
4507 // the original IR value was tossed in favor of a constant back when
4508 // the AddrMode was created we need to bail out gracefully if widths
4509 // do not match instead of extending it.
4510 //
4511 // (See below for code to add the scale.)
4512 if (AddrMode.Scale) {
4513 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4514 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4515 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4516 return false;
4517 }
4518
Hal Finkelc3998302014-04-12 00:59:48 +00004519 if (AddrMode.BaseGV) {
4520 if (ResultPtr)
4521 return false;
4522
4523 ResultPtr = AddrMode.BaseGV;
4524 }
4525
4526 // If the real base value actually came from an inttoptr, then the matcher
4527 // will look through it and provide only the integer value. In that case,
4528 // use it here.
Keno Fischer05e4ac22017-06-29 20:28:59 +00004529 if (!DL->isNonIntegralPointerType(Addr->getType())) {
4530 if (!ResultPtr && AddrMode.BaseReg) {
4531 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4532 "sunkaddr");
4533 AddrMode.BaseReg = nullptr;
4534 } else if (!ResultPtr && AddrMode.Scale == 1) {
4535 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4536 "sunkaddr");
4537 AddrMode.Scale = 0;
4538 }
Hal Finkelc3998302014-04-12 00:59:48 +00004539 }
4540
4541 if (!ResultPtr &&
4542 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4543 SunkAddr = Constant::getNullValue(Addr->getType());
4544 } else if (!ResultPtr) {
4545 return false;
4546 } else {
4547 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004548 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4549 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004550
4551 // Start with the base register. Do this first so that subsequent address
4552 // matching finds it last, which will prevent it from trying to match it
4553 // as the scaled value in case it happens to be a mul. That would be
4554 // problematic if we've sunk a different mul for the scale, because then
4555 // we'd end up sinking both muls.
4556 if (AddrMode.BaseReg) {
4557 Value *V = AddrMode.BaseReg;
4558 if (V->getType() != IntPtrTy)
4559 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4560
4561 ResultIndex = V;
4562 }
4563
4564 // Add the scale value.
4565 if (AddrMode.Scale) {
4566 Value *V = AddrMode.ScaledReg;
4567 if (V->getType() == IntPtrTy) {
4568 // done.
Hal Finkelc3998302014-04-12 00:59:48 +00004569 } else {
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004570 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4571 cast<IntegerType>(V->getType())->getBitWidth() &&
4572 "We can't transform if ScaledReg is too narrow");
4573 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004574 }
4575
4576 if (AddrMode.Scale != 1)
4577 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4578 "sunkaddr");
4579 if (ResultIndex)
4580 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4581 else
4582 ResultIndex = V;
4583 }
4584
4585 // Add in the Base Offset if present.
4586 if (AddrMode.BaseOffs) {
4587 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4588 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004589 // We need to add this separately from the scale above to help with
4590 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004591 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004592 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004593 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004594 }
4595
4596 ResultIndex = V;
4597 }
4598
4599 if (!ResultIndex) {
4600 SunkAddr = ResultPtr;
4601 } else {
4602 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004603 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004604 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004605 }
4606
4607 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004608 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004609 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004610 } else {
Keno Fischer05e4ac22017-06-29 20:28:59 +00004611 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4612 // non-integral pointers, so in that case bail out now.
4613 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4614 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4615 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4616 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4617 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4618 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4619 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4620 (AddrMode.BaseGV &&
4621 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4622 return false;
4623
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004624 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4625 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004626 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004627 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004628
4629 // Start with the base register. Do this first so that subsequent address
4630 // matching finds it last, which will prevent it from trying to match it
4631 // as the scaled value in case it happens to be a mul. That would be
4632 // problematic if we've sunk a different mul for the scale, because then
4633 // we'd end up sinking both muls.
4634 if (AddrMode.BaseReg) {
4635 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004636 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004637 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004638 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004639 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004640 Result = V;
4641 }
4642
4643 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004644 if (AddrMode.Scale) {
4645 Value *V = AddrMode.ScaledReg;
4646 if (V->getType() == IntPtrTy) {
4647 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004648 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004649 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004650 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4651 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004652 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004653 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004654 // It is only safe to sign extend the BaseReg if we know that the math
4655 // required to create it did not overflow before we extend it. Since
4656 // the original IR value was tossed in favor of a constant back when
4657 // the AddrMode was created we need to bail out gracefully if widths
4658 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004659 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004660 if (I && (Result != AddrMode.BaseReg))
4661 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004662 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004663 }
4664 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004665 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4666 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004667 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004668 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004669 else
4670 Result = V;
4671 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004672
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004673 // Add in the BaseGV if present.
4674 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004675 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004676 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004677 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004678 else
4679 Result = V;
4680 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004681
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004682 // Add in the Base Offset if present.
4683 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004684 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004685 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004686 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004687 else
4688 Result = V;
4689 }
4690
Craig Topperc0196b12014-04-14 00:51:57 +00004691 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004692 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004693 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004694 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004695 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004696
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004697 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Simon Dardis230f4532017-11-24 16:45:28 +00004698 // Store the newly computed address into the cache. In the case we reused a
4699 // value, this should be idempotent.
4700 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004701
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004702 // If we have no uses, recursively delete the value and all dead instructions
4703 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004704 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004705 // This can cause recursive deletion, which can invalidate our iterator.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004706 // Use a WeakTrackingVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004707 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004708 WeakTrackingVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004709 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004710
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004711 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004712
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004713 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004714 // If the iterator instruction was recursively deleted, start over at the
4715 // start of the block.
4716 CurInstIterator = BB->begin();
4717 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004718 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004719 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004720 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004721 return true;
4722}
4723
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004724/// If there are any memory operands, use OptimizeMemoryInst to sink their
4725/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004726bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004727 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004728
Eric Christopher11e4df72015-02-26 22:38:43 +00004729 const TargetRegisterInfo *TRI =
Sanjay Patel4137d512017-06-07 14:29:52 +00004730 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004731 TargetLowering::AsmOperandInfoVector TargetConstraints =
4732 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004733 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004734 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4735 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004736
Evan Cheng1da25002008-02-26 02:42:37 +00004737 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004738 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004739
Eli Friedman666bbe32008-02-26 18:37:49 +00004740 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4741 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004742 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004743 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004744 } else if (OpInfo.Type == InlineAsm::isInput)
4745 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004746 }
4747
4748 return MadeChange;
4749}
4750
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004751/// Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004752/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00004753static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4754 assert(!Val->use_empty() && "Input must have at least one use");
4755 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004756 bool IsSExt = isa<SExtInst>(FirstUser);
4757 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00004758 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004759 const Instruction *UI = cast<Instruction>(U);
4760 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4761 return false;
4762 Type *CurTy = UI->getType();
4763 // Same input and output types: Same instruction after CSE.
4764 if (CurTy == ExtTy)
4765 continue;
4766
4767 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00004768 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004769 // b = sext ty1 a to ty2
4770 // c = sext ty1 a to ty3
4771 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00004772 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004773 // b = sext ty1 a to ty2
4774 // c = sext ty2 b to ty3
4775 // However, the last sext is not free.
4776 if (IsSExt)
4777 return false;
4778
4779 // This is a ZExt, maybe this is free to extend from one type to another.
4780 // In that case, we would not account for a different use.
4781 Type *NarrowTy;
4782 Type *LargeTy;
4783 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4784 CurTy->getScalarType()->getIntegerBitWidth()) {
4785 NarrowTy = CurTy;
4786 LargeTy = ExtTy;
4787 } else {
4788 NarrowTy = ExtTy;
4789 LargeTy = CurTy;
4790 }
4791
4792 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4793 return false;
4794 }
4795 // All uses are the same or can be derived from one another for free.
4796 return true;
4797}
4798
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004799/// Try to speculatively promote extensions in \p Exts and continue
Jun Bum Lim42301012017-03-17 19:05:21 +00004800/// promoting through newly promoted operands recursively as far as doing so is
4801/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4802/// When some promotion happened, \p TPT contains the proper state to revert
4803/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004804///
Jun Bum Lim42301012017-03-17 19:05:21 +00004805/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00004806bool CodeGenPrepare::tryToPromoteExts(
4807 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4808 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4809 unsigned CreatedInstsCost) {
4810 bool Promoted = false;
4811
4812 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004813 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004814 // Early check if we directly have ext(load).
4815 if (isa<LoadInst>(I->getOperand(0))) {
4816 ProfitablyMovedExts.push_back(I);
4817 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004818 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004819
4820 // Check whether or not we want to do any promotion. The reason we have
4821 // this check inside the for loop is to catch the case where an extension
4822 // is directly fed by a load because in such case the extension can be moved
4823 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004824 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00004825 return false;
4826
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004827 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00004828 TypePromotionHelper::Action TPH =
4829 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004830 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00004831 if (!TPH) {
4832 // Save the current extension as we cannot move up through its operand.
4833 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004834 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00004835 }
4836
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004837 // Save the current state.
4838 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4839 TPT.getRestorationPoint();
4840 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004841 unsigned NewCreatedInstsCost = 0;
4842 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004843 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004844 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4845 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004846 assert(PromotedVal &&
4847 "TypePromotionHelper should have filtered out those cases");
4848
4849 // We would be able to merge only one extension in a load.
4850 // Therefore, if we have more than 1 new extension we heuristically
4851 // cut this search path, because it means we degrade the code quality.
4852 // With exactly 2, the transformation is neutral, because we will merge
4853 // one extension but leave one. However, we optimistically keep going,
4854 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004855 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004856 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00004857 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004858 TotalCreatedInstsCost =
4859 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004860 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004861 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004862 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004863 // This promotion is not profitable, rollback to the previous state, and
4864 // save the current extension in ProfitablyMovedExts as the latest
4865 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004866 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00004867 ProfitablyMovedExts.push_back(I);
4868 continue;
4869 }
4870 // Continue promoting NewExts as far as doing so is profitable.
4871 SmallVector<Instruction *, 2> NewlyMovedExts;
4872 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4873 bool NewPromoted = false;
4874 for (auto ExtInst : NewlyMovedExts) {
4875 Instruction *MovedExt = cast<Instruction>(ExtInst);
4876 Value *ExtOperand = MovedExt->getOperand(0);
4877 // If we have reached to a load, we need this extra profitability check
4878 // as it could potentially be merged into an ext(load).
4879 if (isa<LoadInst>(ExtOperand) &&
4880 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4881 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
4882 continue;
4883
4884 ProfitablyMovedExts.push_back(MovedExt);
4885 NewPromoted = true;
4886 }
4887
4888 // If none of speculative promotions for NewExts is profitable, rollback
4889 // and save the current extension (I) as the last profitable extension.
4890 if (!NewPromoted) {
4891 TPT.rollback(LastKnownGood);
4892 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004893 continue;
4894 }
4895 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00004896 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004897 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004898 return Promoted;
4899}
4900
Jun Bum Limdee55652017-04-03 19:20:07 +00004901/// Merging redundant sexts when one is dominating the other.
4902bool CodeGenPrepare::mergeSExts(Function &F) {
4903 DominatorTree DT(F);
4904 bool Changed = false;
4905 for (auto &Entry : ValToSExtendedUses) {
4906 SExts &Insts = Entry.second;
4907 SExts CurPts;
4908 for (Instruction *Inst : Insts) {
4909 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
4910 Inst->getOperand(0) != Entry.first)
4911 continue;
4912 bool inserted = false;
4913 for (auto &Pt : CurPts) {
4914 if (DT.dominates(Inst, Pt)) {
4915 Pt->replaceAllUsesWith(Inst);
4916 RemovedInsts.insert(Pt);
4917 Pt->removeFromParent();
4918 Pt = Inst;
4919 inserted = true;
4920 Changed = true;
4921 break;
4922 }
4923 if (!DT.dominates(Pt, Inst))
4924 // Give up if we need to merge in a common dominator as the
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00004925 // experiments show it is not profitable.
Jun Bum Limdee55652017-04-03 19:20:07 +00004926 continue;
4927 Inst->replaceAllUsesWith(Pt);
4928 RemovedInsts.insert(Inst);
4929 Inst->removeFromParent();
4930 inserted = true;
4931 Changed = true;
4932 break;
4933 }
4934 if (!inserted)
4935 CurPts.push_back(Inst);
4936 }
4937 }
4938 return Changed;
4939}
4940
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004941// Spliting large data structures so that the GEPs accessing them can have
4942// smaller offsets so that they can be sunk to the same blocks as their users.
4943// For example, a large struct starting from %base is splitted into two parts
4944// where the second part starts from %new_base.
4945//
4946// Before:
4947// BB0:
4948// %base =
4949//
4950// BB1:
4951// %gep0 = gep %base, off0
4952// %gep1 = gep %base, off1
4953// %gep2 = gep %base, off2
4954//
4955// BB2:
4956// %load1 = load %gep0
4957// %load2 = load %gep1
4958// %load3 = load %gep2
4959//
4960// After:
4961// BB0:
4962// %base =
4963// %new_base = gep %base, off0
4964//
4965// BB1:
4966// %new_gep0 = %new_base
4967// %new_gep1 = gep %new_base, off1 - off0
4968// %new_gep2 = gep %new_base, off2 - off0
4969//
4970// BB2:
4971// %load1 = load i32, i32* %new_gep0
4972// %load2 = load i32, i32* %new_gep1
4973// %load3 = load i32, i32* %new_gep2
4974//
4975// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
4976// their offsets are smaller enough to fit into the addressing mode.
4977bool CodeGenPrepare::splitLargeGEPOffsets() {
4978 bool Changed = false;
4979 for (auto &Entry : LargeOffsetGEPMap) {
4980 Value *OldBase = Entry.first;
4981 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
4982 &LargeOffsetGEPs = Entry.second;
4983 auto compareGEPOffset =
4984 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
4985 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
4986 if (LHS.first == RHS.first)
4987 return false;
4988 if (LHS.second != RHS.second)
4989 return LHS.second < RHS.second;
4990 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
4991 };
4992 // Sorting all the GEPs of the same data structures based on the offsets.
4993 llvm::sort(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end(),
4994 compareGEPOffset);
4995 LargeOffsetGEPs.erase(
4996 std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()),
4997 LargeOffsetGEPs.end());
4998 // Skip if all the GEPs have the same offsets.
4999 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
5000 continue;
5001 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
5002 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
5003 Value *NewBaseGEP = nullptr;
5004
5005 auto LargeOffsetGEP = LargeOffsetGEPs.begin();
5006 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
5007 GetElementPtrInst *GEP = LargeOffsetGEP->first;
5008 int64_t Offset = LargeOffsetGEP->second;
5009 if (Offset != BaseOffset) {
5010 TargetLowering::AddrMode AddrMode;
5011 AddrMode.BaseOffs = Offset - BaseOffset;
5012 // The result type of the GEP might not be the type of the memory
5013 // access.
5014 if (!TLI->isLegalAddressingMode(*DL, AddrMode,
5015 GEP->getResultElementType(),
5016 GEP->getAddressSpace())) {
5017 // We need to create a new base if the offset to the current base is
5018 // too large to fit into the addressing mode. So, a very large struct
5019 // may be splitted into several parts.
5020 BaseGEP = GEP;
5021 BaseOffset = Offset;
5022 NewBaseGEP = nullptr;
5023 }
5024 }
5025
5026 // Generate a new GEP to replace the current one.
5027 IRBuilder<> Builder(GEP);
5028 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
5029 Type *I8PtrTy =
5030 Builder.getInt8PtrTy(GEP->getType()->getPointerAddressSpace());
5031 Type *I8Ty = Builder.getInt8Ty();
5032
5033 if (!NewBaseGEP) {
5034 // Create a new base if we don't have one yet. Find the insertion
5035 // pointer for the new base first.
5036 BasicBlock::iterator NewBaseInsertPt;
5037 BasicBlock *NewBaseInsertBB;
5038 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
5039 // If the base of the struct is an instruction, the new base will be
5040 // inserted close to it.
5041 NewBaseInsertBB = BaseI->getParent();
5042 if (isa<PHINode>(BaseI))
5043 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5044 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
5045 NewBaseInsertBB =
5046 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
5047 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5048 } else
5049 NewBaseInsertPt = std::next(BaseI->getIterator());
5050 } else {
5051 // If the current base is an argument or global value, the new base
5052 // will be inserted to the entry block.
5053 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
5054 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5055 }
5056 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
5057 // Create a new base.
5058 Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset);
5059 NewBaseGEP = OldBase;
5060 if (NewBaseGEP->getType() != I8PtrTy)
5061 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
5062 NewBaseGEP =
5063 NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep");
5064 NewGEPBases.insert(NewBaseGEP);
5065 }
5066
5067 Value *NewGEP = NewBaseGEP;
5068 if (Offset == BaseOffset) {
5069 if (GEP->getType() != I8PtrTy)
5070 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5071 } else {
5072 // Calculate the new offset for the new GEP.
5073 Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset);
5074 NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index);
5075
5076 if (GEP->getType() != I8PtrTy)
5077 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5078 }
5079 GEP->replaceAllUsesWith(NewGEP);
5080 LargeOffsetGEPID.erase(GEP);
5081 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
5082 GEP->eraseFromParent();
5083 Changed = true;
5084 }
5085 }
5086 return Changed;
5087}
5088
Jun Bum Lim42301012017-03-17 19:05:21 +00005089/// Return true, if an ext(load) can be formed from an extension in
5090/// \p MovedExts.
5091bool CodeGenPrepare::canFormExtLd(
5092 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
5093 Instruction *&Inst, bool HasPromoted) {
5094 for (auto *MovedExtInst : MovedExts) {
5095 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
5096 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
5097 Inst = MovedExtInst;
5098 break;
5099 }
5100 }
5101 if (!LI)
5102 return false;
5103
5104 // If they're already in the same block, there's nothing to do.
5105 // Make the cheap checks first if we did not promote.
5106 // If we promoted, we need to check if it is indeed profitable.
5107 if (!HasPromoted && LI->getParent() == Inst->getParent())
5108 return false;
5109
Haicheng Wuabdef9e2017-07-15 02:12:16 +00005110 return TLI->isExtLoad(LI, Inst, *DL);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005111}
5112
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005113/// Move a zext or sext fed by a load into the same basic block as the load,
5114/// unless conditions are unfavorable. This allows SelectionDAG to fold the
5115/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00005116///
Jun Bum Limdee55652017-04-03 19:20:07 +00005117/// E.g.,
5118/// \code
5119/// %ld = load i32* %addr
5120/// %add = add nuw i32 %ld, 4
5121/// %zext = zext i32 %add to i64
5122// \endcode
5123/// =>
5124/// \code
5125/// %ld = load i32* %addr
5126/// %zext = zext i32 %ld to i64
5127/// %add = add nuw i64 %zext, 4
5128/// \encode
5129/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
5130/// allow us to match zext(load i32*) to i64.
5131///
5132/// Also, try to promote the computations used to obtain a sign extended
5133/// value used into memory accesses.
5134/// E.g.,
5135/// \code
5136/// a = add nsw i32 b, 3
5137/// d = sext i32 a to i64
5138/// e = getelementptr ..., i64 d
5139/// \endcode
5140/// =>
5141/// \code
5142/// f = sext i32 b to i64
5143/// a = add nsw i64 f, 3
5144/// e = getelementptr ..., i64 a
5145/// \endcode
5146///
5147/// \p Inst[in/out] the extension may be modified during the process if some
5148/// promotions apply.
5149bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
5150 // ExtLoad formation and address type promotion infrastructure requires TLI to
5151 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00005152 if (!TLI)
5153 return false;
5154
Jun Bum Limdee55652017-04-03 19:20:07 +00005155 bool AllowPromotionWithoutCommonHeader = false;
5156 /// See if it is an interesting sext operations for the address type
5157 /// promotion before trying to promote it, e.g., the ones with the right
5158 /// type and used in memory accesses.
5159 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
5160 *Inst, AllowPromotionWithoutCommonHeader);
5161 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005162 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00005163 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005164 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00005165 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
5166 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00005167
Jun Bum Limdee55652017-04-03 19:20:07 +00005168 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00005169
Dan Gohman99429a02009-10-16 20:59:35 +00005170 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005171 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00005172 Instruction *ExtFedByLoad;
5173
5174 // Try to promote a chain of computation if it allows to form an extended
5175 // load.
5176 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
5177 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
5178 TPT.commit();
5179 // Move the extend into the same block as the load
Sanjay Patel674d2c22017-08-29 14:07:48 +00005180 ExtFedByLoad->moveAfter(LI);
Jun Bum Limdee55652017-04-03 19:20:07 +00005181 // CGP does not check if the zext would be speculatively executed when moved
5182 // to the same basic block as the load. Preserving its original location
5183 // would pessimize the debugging experience, as well as negatively impact
5184 // the quality of sample pgo. We don't want to use "line 0" as that has a
5185 // size cost in the line-table section and logically the zext can be seen as
5186 // part of the load. Therefore we conservatively reuse the same debug
5187 // location for the load and the zext.
5188 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
5189 ++NumExtsMoved;
5190 Inst = ExtFedByLoad;
5191 return true;
5192 }
5193
5194 // Continue promoting SExts if known as considerable depending on targets.
5195 if (ATPConsiderable &&
5196 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
5197 HasPromoted, TPT, SpeculativelyMovedExts))
5198 return true;
5199
5200 TPT.rollback(LastKnownGood);
5201 return false;
5202}
5203
5204// Perform address type promotion if doing so is profitable.
5205// If AllowPromotionWithoutCommonHeader == false, we should find other sext
5206// instructions that sign extended the same initial value. However, if
5207// AllowPromotionWithoutCommonHeader == true, we expect promoting the
5208// extension is just profitable.
5209bool CodeGenPrepare::performAddressTypePromotion(
5210 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
5211 bool HasPromoted, TypePromotionTransaction &TPT,
5212 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
5213 bool Promoted = false;
5214 SmallPtrSet<Instruction *, 1> UnhandledExts;
5215 bool AllSeenFirst = true;
5216 for (auto I : SpeculativelyMovedExts) {
5217 Value *HeadOfChain = I->getOperand(0);
5218 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
5219 SeenChainsForSExt.find(HeadOfChain);
5220 // If there is an unhandled SExt which has the same header, try to promote
5221 // it as well.
5222 if (AlreadySeen != SeenChainsForSExt.end()) {
5223 if (AlreadySeen->second != nullptr)
5224 UnhandledExts.insert(AlreadySeen->second);
5225 AllSeenFirst = false;
5226 }
5227 }
5228
5229 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
5230 SpeculativelyMovedExts.size() == 1)) {
5231 TPT.commit();
5232 if (HasPromoted)
5233 Promoted = true;
5234 for (auto I : SpeculativelyMovedExts) {
5235 Value *HeadOfChain = I->getOperand(0);
5236 SeenChainsForSExt[HeadOfChain] = nullptr;
5237 ValToSExtendedUses[HeadOfChain].push_back(I);
5238 }
5239 // Update Inst as promotion happen.
5240 Inst = SpeculativelyMovedExts.pop_back_val();
5241 } else {
5242 // This is the first chain visited from the header, keep the current chain
5243 // as unhandled. Defer to promote this until we encounter another SExt
5244 // chain derived from the same header.
5245 for (auto I : SpeculativelyMovedExts) {
5246 Value *HeadOfChain = I->getOperand(0);
5247 SeenChainsForSExt[HeadOfChain] = Inst;
5248 }
Dan Gohman99429a02009-10-16 20:59:35 +00005249 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005250 }
Dan Gohman99429a02009-10-16 20:59:35 +00005251
Jun Bum Limdee55652017-04-03 19:20:07 +00005252 if (!AllSeenFirst && !UnhandledExts.empty())
5253 for (auto VisitedSExt : UnhandledExts) {
5254 if (RemovedInsts.count(VisitedSExt))
5255 continue;
5256 TypePromotionTransaction TPT(RemovedInsts);
5257 SmallVector<Instruction *, 1> Exts;
5258 SmallVector<Instruction *, 2> Chains;
5259 Exts.push_back(VisitedSExt);
5260 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
5261 TPT.commit();
5262 if (HasPromoted)
5263 Promoted = true;
5264 for (auto I : Chains) {
5265 Value *HeadOfChain = I->getOperand(0);
5266 // Mark this as handled.
5267 SeenChainsForSExt[HeadOfChain] = nullptr;
5268 ValToSExtendedUses[HeadOfChain].push_back(I);
5269 }
5270 }
5271 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00005272}
5273
Sanjay Patelfc580a62015-09-21 23:03:16 +00005274bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00005275 BasicBlock *DefBB = I->getParent();
5276
Bob Wilsonff714f92010-09-21 21:44:14 +00005277 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00005278 // other uses of the source with result of extension.
5279 Value *Src = I->getOperand(0);
5280 if (Src->hasOneUse())
5281 return false;
5282
Evan Cheng2011df42007-12-13 07:50:36 +00005283 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00005284 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00005285 return false;
5286
Evan Cheng7bc89422007-12-12 00:51:06 +00005287 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00005288 // this block.
5289 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00005290 return false;
5291
Evan Chengd3d80172007-12-05 23:58:20 +00005292 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005293 for (User *U : I->users()) {
5294 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00005295
5296 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005297 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00005298 if (UserBB == DefBB) continue;
5299 DefIsLiveOut = true;
5300 break;
5301 }
5302 if (!DefIsLiveOut)
5303 return false;
5304
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00005305 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005306 for (User *U : Src->users()) {
5307 Instruction *UI = cast<Instruction>(U);
5308 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00005309 if (UserBB == DefBB) continue;
5310 // Be conservative. We don't want this xform to end up introducing
5311 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005312 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00005313 return false;
5314 }
5315
Evan Chengd3d80172007-12-05 23:58:20 +00005316 // InsertedTruncs - Only insert one trunc in each block once.
5317 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5318
5319 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005320 for (Use &U : Src->uses()) {
5321 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00005322
5323 // Figure out which BB this ext is used in.
5324 BasicBlock *UserBB = User->getParent();
5325 if (UserBB == DefBB) continue;
5326
5327 // Both src and def are live in this block. Rewrite the use.
5328 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5329
5330 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00005331 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005332 assert(InsertPt != UserBB->end());
5333 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005334 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00005335 }
5336
5337 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005338 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00005339 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00005340 MadeChange = true;
5341 }
5342
5343 return MadeChange;
5344}
5345
Geoff Berry5256fca2015-11-20 22:34:39 +00005346// Find loads whose uses only use some of the loaded value's bits. Add an "and"
5347// just after the load if the target can fold this into one extload instruction,
5348// with the hope of eliminating some of the other later "and" instructions using
5349// the loaded value. "and"s that are made trivially redundant by the insertion
5350// of the new "and" are removed by this function, while others (e.g. those whose
5351// path from the load goes through a phi) are left for isel to potentially
5352// remove.
5353//
5354// For example:
5355//
5356// b0:
5357// x = load i32
5358// ...
5359// b1:
5360// y = and x, 0xff
5361// z = use y
5362//
5363// becomes:
5364//
5365// b0:
5366// x = load i32
5367// x' = and x, 0xff
5368// ...
5369// b1:
5370// z = use x'
5371//
5372// whereas:
5373//
5374// b0:
5375// x1 = load i32
5376// ...
5377// b1:
5378// x2 = load i32
5379// ...
5380// b2:
5381// x = phi x1, x2
5382// y = and x, 0xff
5383//
5384// becomes (after a call to optimizeLoadExt for each load):
5385//
5386// b0:
5387// x1 = load i32
5388// x1' = and x1, 0xff
5389// ...
5390// b1:
5391// x2 = load i32
5392// x2' = and x2, 0xff
5393// ...
5394// b2:
5395// x = phi x1', x2'
5396// y = and x, 0xff
Geoff Berry5256fca2015-11-20 22:34:39 +00005397bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
Vedant Kumarb3091da2018-07-06 20:17:42 +00005398 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
Geoff Berry5256fca2015-11-20 22:34:39 +00005399 return false;
5400
Geoff Berry5d534b62017-02-21 18:53:14 +00005401 // Skip loads we've already transformed.
5402 if (Load->hasOneUse() &&
5403 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5404 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005405
5406 // Look at all uses of Load, looking through phis, to determine how many bits
5407 // of the loaded value are needed.
5408 SmallVector<Instruction *, 8> WorkList;
5409 SmallPtrSet<Instruction *, 16> Visited;
5410 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5411 for (auto *U : Load->users())
5412 WorkList.push_back(cast<Instruction>(U));
5413
5414 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5415 unsigned BitWidth = LoadResultVT.getSizeInBits();
5416 APInt DemandBits(BitWidth, 0);
5417 APInt WidestAndBits(BitWidth, 0);
5418
5419 while (!WorkList.empty()) {
5420 Instruction *I = WorkList.back();
5421 WorkList.pop_back();
5422
5423 // Break use-def graph loops.
5424 if (!Visited.insert(I).second)
5425 continue;
5426
5427 // For a PHI node, push all of its users.
5428 if (auto *Phi = dyn_cast<PHINode>(I)) {
5429 for (auto *U : Phi->users())
5430 WorkList.push_back(cast<Instruction>(U));
5431 continue;
5432 }
5433
5434 switch (I->getOpcode()) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005435 case Instruction::And: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005436 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5437 if (!AndC)
5438 return false;
5439 APInt AndBits = AndC->getValue();
5440 DemandBits |= AndBits;
5441 // Keep track of the widest and mask we see.
5442 if (AndBits.ugt(WidestAndBits))
5443 WidestAndBits = AndBits;
5444 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5445 AndsToMaybeRemove.push_back(I);
5446 break;
5447 }
5448
Eugene Zelenko900b6332017-08-29 22:32:07 +00005449 case Instruction::Shl: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005450 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5451 if (!ShlC)
5452 return false;
5453 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00005454 DemandBits.setLowBits(BitWidth - ShiftAmt);
Geoff Berry5256fca2015-11-20 22:34:39 +00005455 break;
5456 }
5457
Eugene Zelenko900b6332017-08-29 22:32:07 +00005458 case Instruction::Trunc: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005459 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5460 unsigned TruncBitWidth = TruncVT.getSizeInBits();
Craig Topperfc947bc2017-04-18 17:14:21 +00005461 DemandBits.setLowBits(TruncBitWidth);
Geoff Berry5256fca2015-11-20 22:34:39 +00005462 break;
5463 }
5464
5465 default:
5466 return false;
5467 }
5468 }
5469
5470 uint32_t ActiveBits = DemandBits.getActiveBits();
5471 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5472 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5473 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5474 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5475 // followed by an AND.
5476 // TODO: Look into removing this restriction by fixing backends to either
5477 // return false for isLoadExtLegal for i1 or have them select this pattern to
5478 // a single instruction.
5479 //
5480 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5481 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005482 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005483 WidestAndBits != DemandBits)
5484 return false;
5485
5486 LLVMContext &Ctx = Load->getType()->getContext();
5487 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5488 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5489
5490 // Reject cases that won't be matched as extloads.
5491 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5492 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5493 return false;
5494
5495 IRBuilder<> Builder(Load->getNextNode());
5496 auto *NewAnd = dyn_cast<Instruction>(
5497 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005498 // Mark this instruction as "inserted by CGP", so that other
5499 // optimizations don't touch it.
5500 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005501
5502 // Replace all uses of load with new and (except for the use of load in the
5503 // new and itself).
5504 Load->replaceAllUsesWith(NewAnd);
5505 NewAnd->setOperand(0, Load);
5506
5507 // Remove any and instructions that are now redundant.
5508 for (auto *And : AndsToMaybeRemove)
5509 // Check that the and mask is the same as the one we decided to put on the
5510 // new and.
5511 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5512 And->replaceAllUsesWith(NewAnd);
5513 if (&*CurInstIterator == And)
5514 CurInstIterator = std::next(And->getIterator());
5515 And->eraseFromParent();
5516 ++NumAndUses;
5517 }
5518
5519 ++NumAndsAdded;
5520 return true;
5521}
5522
Sanjay Patel69a50a12015-10-19 21:59:12 +00005523/// Check if V (an operand of a select instruction) is an expensive instruction
5524/// that is only used once.
5525static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5526 auto *I = dyn_cast<Instruction>(V);
5527 // If it's safe to speculatively execute, then it should not have side
5528 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005529 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5530 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005531}
5532
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005533/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005534static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005535 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005536 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005537 // If even a predictable select is cheap, then a branch can't be cheaper.
5538 if (!TLI->isPredictableSelectExpensive())
5539 return false;
5540
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005541 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005542 // whether a select is better represented as a branch.
5543
5544 // If metadata tells us that the select condition is obviously predictable,
5545 // then we want to replace the select with a branch.
5546 uint64_t TrueWeight, FalseWeight;
5547 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5548 uint64_t Max = std::max(TrueWeight, FalseWeight);
5549 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005550 if (Sum != 0) {
5551 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5552 if (Probability > TLI->getPredictableBranchThreshold())
5553 return true;
5554 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005555 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005556
5557 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5558
Sanjay Patel4e652762015-09-28 22:14:51 +00005559 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5560 // comparison condition. If the compare has more than one use, there's
5561 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005562 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005563 return false;
5564
Sanjay Patel69a50a12015-10-19 21:59:12 +00005565 // If either operand of the select is expensive and only needed on one side
5566 // of the select, we should form a branch.
5567 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5568 sinkSelectOperand(TTI, SI->getFalseValue()))
5569 return true;
5570
5571 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005572}
5573
Dehao Chen9bbb9412016-09-12 20:23:28 +00005574/// If \p isTrue is true, return the true value of \p SI, otherwise return
5575/// false value of \p SI. If the true/false value of \p SI is defined by any
5576/// select instructions in \p Selects, look through the defining select
5577/// instruction until the true/false value is not defined in \p Selects.
5578static Value *getTrueOrFalseValue(
5579 SelectInst *SI, bool isTrue,
5580 const SmallPtrSet<const Instruction *, 2> &Selects) {
5581 Value *V;
5582
5583 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5584 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005585 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005586 "The condition of DefSI does not match with SI");
5587 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5588 }
5589 return V;
5590}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005591
Nadav Rotem9d832022012-09-02 12:10:19 +00005592/// If we have a SelectInst that will likely profit from branch prediction,
5593/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005594bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Vedant Kumarfbc38732018-08-21 23:42:23 +00005595 // If branch conversion isn't desirable, exit early.
5596 if (DisableSelectToBranch || OptSize || !TLI)
5597 return false;
5598
Dehao Chen9bbb9412016-09-12 20:23:28 +00005599 // Find all consecutive select instructions that share the same condition.
5600 SmallVector<SelectInst *, 2> ASI;
5601 ASI.push_back(SI);
Vedant Kumar00e75582018-08-21 23:42:38 +00005602 for (Instruction *NextInst = SI->getNextNonDebugInstruction();
5603 NextInst != SI->getParent()->getTerminator();
5604 NextInst = NextInst->getNextNonDebugInstruction()) {
5605 SelectInst *I = dyn_cast<SelectInst>(NextInst);
Dehao Chen9bbb9412016-09-12 20:23:28 +00005606 if (I && SI->getCondition() == I->getCondition()) {
5607 ASI.push_back(I);
5608 } else {
5609 break;
5610 }
5611 }
5612
5613 SelectInst *LastSI = ASI.back();
5614 // Increment the current iterator to skip all the rest of select instructions
5615 // because they will be either "not lowered" or "all lowered" to branch.
5616 CurInstIterator = std::next(LastSI->getIterator());
5617
Nadav Rotem9d832022012-09-02 12:10:19 +00005618 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5619
5620 // Can we convert the 'select' to CF ?
Vedant Kumarfbc38732018-08-21 23:42:23 +00005621 if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005622 return false;
5623
Nadav Rotem9d832022012-09-02 12:10:19 +00005624 TargetLowering::SelectSupportKind SelectKind;
5625 if (VectorCond)
5626 SelectKind = TargetLowering::VectorMaskSelect;
5627 else if (SI->getType()->isVectorTy())
5628 SelectKind = TargetLowering::ScalarCondVectorVal;
5629 else
5630 SelectKind = TargetLowering::ScalarValSelect;
5631
Sanjay Pateld66607b2016-04-26 17:11:17 +00005632 if (TLI->isSelectSupported(SelectKind) &&
5633 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5634 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005635
5636 ModifiedDT = true;
5637
Sanjay Patel69a50a12015-10-19 21:59:12 +00005638 // Transform a sequence like this:
5639 // start:
5640 // %cmp = cmp uge i32 %a, %b
5641 // %sel = select i1 %cmp, i32 %c, i32 %d
5642 //
5643 // Into:
5644 // start:
5645 // %cmp = cmp uge i32 %a, %b
5646 // br i1 %cmp, label %select.true, label %select.false
5647 // select.true:
5648 // br label %select.end
5649 // select.false:
5650 // br label %select.end
5651 // select.end:
5652 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5653 //
5654 // In addition, we may sink instructions that produce %c or %d from
5655 // the entry block into the destination(s) of the new branch.
5656 // If the true or false blocks do not contain a sunken instruction, that
5657 // block and its branch may be optimized away. In that case, one side of the
5658 // first branch will point directly to select.end, and the corresponding PHI
5659 // predecessor block will be the start block.
5660
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005661 // First, we split the block containing the select into 2 blocks.
5662 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005663 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005664 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005665
Sanjay Patel69a50a12015-10-19 21:59:12 +00005666 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005667 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005668
5669 // These are the new basic blocks for the conditional branch.
5670 // At least one will become an actual new basic block.
5671 BasicBlock *TrueBlock = nullptr;
5672 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005673 BranchInst *TrueBranch = nullptr;
5674 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005675
5676 // Sink expensive instructions into the conditional blocks to avoid executing
5677 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005678 for (SelectInst *SI : ASI) {
5679 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5680 if (TrueBlock == nullptr) {
5681 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5682 EndBlock->getParent(), EndBlock);
5683 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5684 }
5685 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5686 TrueInst->moveBefore(TrueBranch);
5687 }
5688 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5689 if (FalseBlock == nullptr) {
5690 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5691 EndBlock->getParent(), EndBlock);
5692 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5693 }
5694 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5695 FalseInst->moveBefore(FalseBranch);
5696 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005697 }
5698
5699 // If there was nothing to sink, then arbitrarily choose the 'false' side
5700 // for a new input value to the PHI.
5701 if (TrueBlock == FalseBlock) {
5702 assert(TrueBlock == nullptr &&
5703 "Unexpected basic block transform while optimizing select");
5704
5705 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5706 EndBlock->getParent(), EndBlock);
5707 BranchInst::Create(EndBlock, FalseBlock);
5708 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005709
5710 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005711 // If we did not create a new block for one of the 'true' or 'false' paths
5712 // of the condition, it means that side of the branch goes to the end block
5713 // directly and the path originates from the start block from the point of
5714 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005715 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005716 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005717 TT = EndBlock;
5718 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005719 TrueBlock = StartBlock;
5720 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005721 TT = TrueBlock;
5722 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005723 FalseBlock = StartBlock;
5724 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005725 TT = TrueBlock;
5726 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005727 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005728 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005729
Dehao Chen9bbb9412016-09-12 20:23:28 +00005730 SmallPtrSet<const Instruction *, 2> INS;
5731 INS.insert(ASI.begin(), ASI.end());
5732 // Use reverse iterator because later select may use the value of the
5733 // earlier select, and we need to propagate value through earlier select
5734 // to get the PHI operand.
5735 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5736 SelectInst *SI = *It;
5737 // The select itself is replaced with a PHI Node.
5738 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5739 PN->takeName(SI);
5740 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5741 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00005742
Dehao Chen9bbb9412016-09-12 20:23:28 +00005743 SI->replaceAllUsesWith(PN);
5744 SI->eraseFromParent();
5745 INS.erase(SI);
5746 ++NumSelectsExpanded;
5747 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005748
5749 // Instruct OptimizeBlock to skip to the next block.
5750 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005751 return true;
5752}
5753
Benjamin Kramer573ff362014-03-01 17:24:40 +00005754static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005755 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5756 int SplatElem = -1;
5757 for (unsigned i = 0; i < Mask.size(); ++i) {
5758 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5759 return false;
5760 SplatElem = Mask[i];
5761 }
5762
5763 return true;
5764}
5765
5766/// Some targets have expensive vector shifts if the lanes aren't all the same
5767/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5768/// it's often worth sinking a shufflevector splat down to its use so that
5769/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005770bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005771 BasicBlock *DefBB = SVI->getParent();
5772
5773 // Only do this xform if variable vector shifts are particularly expensive.
5774 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5775 return false;
5776
5777 // We only expect better codegen by sinking a shuffle if we can recognise a
5778 // constant splat.
5779 if (!isBroadcastShuffle(SVI))
5780 return false;
5781
5782 // InsertedShuffles - Only insert a shuffle in each block once.
5783 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5784
5785 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005786 for (User *U : SVI->users()) {
5787 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005788
5789 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005790 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005791 if (UserBB == DefBB) continue;
5792
5793 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005794 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005795
5796 // Everything checks out, sink the shuffle if the user's block doesn't
5797 // already have a copy.
5798 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5799
5800 if (!InsertedShuffle) {
5801 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005802 assert(InsertPt != UserBB->end());
5803 InsertedShuffle =
5804 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5805 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005806 }
5807
Chandler Carruthcdf47882014-03-09 03:16:01 +00005808 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005809 MadeChange = true;
5810 }
5811
5812 // If we removed all uses, nuke the shuffle.
5813 if (SVI->use_empty()) {
5814 SVI->eraseFromParent();
5815 MadeChange = true;
5816 }
5817
5818 return MadeChange;
5819}
5820
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005821bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5822 if (!TLI || !DL)
5823 return false;
5824
5825 Value *Cond = SI->getCondition();
5826 Type *OldType = Cond->getType();
5827 LLVMContext &Context = Cond->getContext();
5828 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5829 unsigned RegWidth = RegType.getSizeInBits();
5830
5831 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5832 return false;
5833
5834 // If the register width is greater than the type width, expand the condition
5835 // of the switch instruction and each case constant to the width of the
5836 // register. By widening the type of the switch condition, subsequent
5837 // comparisons (for case comparisons) will not need to be extended to the
5838 // preferred register width, so we will potentially eliminate N-1 extends,
5839 // where N is the number of cases in the switch.
5840 auto *NewType = Type::getIntNTy(Context, RegWidth);
5841
5842 // Zero-extend the switch condition and case constants unless the switch
5843 // condition is a function argument that is already being sign-extended.
5844 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5845 // everything instead.
5846 Instruction::CastOps ExtType = Instruction::ZExt;
5847 if (auto *Arg = dyn_cast<Argument>(Cond))
5848 if (Arg->hasSExtAttr())
5849 ExtType = Instruction::SExt;
5850
5851 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5852 ExtInst->insertBefore(SI);
5853 SI->setCondition(ExtInst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00005854 for (auto Case : SI->cases()) {
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005855 APInt NarrowConst = Case.getCaseValue()->getValue();
5856 APInt WideConst = (ExtType == Instruction::ZExt) ?
5857 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5858 Case.setValue(ConstantInt::get(Context, WideConst));
5859 }
5860
5861 return true;
5862}
5863
Zaara Syeda3a7578c2017-05-31 17:12:38 +00005864
Quentin Colombetc32615d2014-10-31 17:52:53 +00005865namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005866
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005867/// Helper class to promote a scalar operation to a vector one.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005868/// This class is used to move downward extractelement transition.
5869/// E.g.,
5870/// a = vector_op <2 x i32>
5871/// b = extractelement <2 x i32> a, i32 0
5872/// c = scalar_op b
5873/// store c
5874///
5875/// =>
5876/// a = vector_op <2 x i32>
5877/// c = vector_op a (equivalent to scalar_op on the related lane)
5878/// * d = extractelement <2 x i32> c, i32 0
5879/// * store d
5880/// Assuming both extractelement and store can be combine, we get rid of the
5881/// transition.
5882class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005883 /// DataLayout associated with the current module.
5884 const DataLayout &DL;
5885
Quentin Colombetc32615d2014-10-31 17:52:53 +00005886 /// Used to perform some checks on the legality of vector operations.
5887 const TargetLowering &TLI;
5888
5889 /// Used to estimated the cost of the promoted chain.
5890 const TargetTransformInfo &TTI;
5891
5892 /// The transition being moved downwards.
5893 Instruction *Transition;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005894
Quentin Colombetc32615d2014-10-31 17:52:53 +00005895 /// The sequence of instructions to be promoted.
5896 SmallVector<Instruction *, 4> InstsToBePromoted;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005897
Quentin Colombetc32615d2014-10-31 17:52:53 +00005898 /// Cost of combining a store and an extract.
5899 unsigned StoreExtractCombineCost;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005900
Quentin Colombetc32615d2014-10-31 17:52:53 +00005901 /// Instruction that will be combined with the transition.
Eugene Zelenko900b6332017-08-29 22:32:07 +00005902 Instruction *CombineInst = nullptr;
Quentin Colombetc32615d2014-10-31 17:52:53 +00005903
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005904 /// The instruction that represents the current end of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005905 /// Since we are faking the promotion until we reach the end of the chain
5906 /// of computation, we need a way to get the current end of the transition.
5907 Instruction *getEndOfTransition() const {
5908 if (InstsToBePromoted.empty())
5909 return Transition;
5910 return InstsToBePromoted.back();
5911 }
5912
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005913 /// Return the index of the original value in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005914 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5915 /// c, is at index 0.
5916 unsigned getTransitionOriginalValueIdx() const {
5917 assert(isa<ExtractElementInst>(Transition) &&
5918 "Other kind of transitions are not supported yet");
5919 return 0;
5920 }
5921
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005922 /// Return the index of the index in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005923 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5924 /// is at index 1.
5925 unsigned getTransitionIdx() const {
5926 assert(isa<ExtractElementInst>(Transition) &&
5927 "Other kind of transitions are not supported yet");
5928 return 1;
5929 }
5930
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005931 /// Get the type of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005932 /// This is the type of the original value.
5933 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5934 /// transition is <2 x i32>.
5935 Type *getTransitionType() const {
5936 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5937 }
5938
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005939 /// Promote \p ToBePromoted by moving \p Def downward through.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005940 /// I.e., we have the following sequence:
5941 /// Def = Transition <ty1> a to <ty2>
5942 /// b = ToBePromoted <ty2> Def, ...
5943 /// =>
5944 /// b = ToBePromoted <ty1> a, ...
5945 /// Def = Transition <ty1> ToBePromoted to <ty2>
5946 void promoteImpl(Instruction *ToBePromoted);
5947
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005948 /// Check whether or not it is profitable to promote all the
Quentin Colombetc32615d2014-10-31 17:52:53 +00005949 /// instructions enqueued to be promoted.
5950 bool isProfitableToPromote() {
5951 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5952 unsigned Index = isa<ConstantInt>(ValIdx)
5953 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5954 : -1;
5955 Type *PromotedType = getTransitionType();
5956
5957 StoreInst *ST = cast<StoreInst>(CombineInst);
5958 unsigned AS = ST->getPointerAddressSpace();
5959 unsigned Align = ST->getAlignment();
5960 // Check if this store is supported.
5961 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005962 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5963 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005964 // If this is not supported, there is no way we can combine
5965 // the extract with the store.
5966 return false;
5967 }
5968
5969 // The scalar chain of computation has to pay for the transition
5970 // scalar to vector.
5971 // The vector chain has to account for the combining cost.
5972 uint64_t ScalarCost =
5973 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5974 uint64_t VectorCost = StoreExtractCombineCost;
5975 for (const auto &Inst : InstsToBePromoted) {
5976 // Compute the cost.
5977 // By construction, all instructions being promoted are arithmetic ones.
5978 // Moreover, one argument is a constant that can be viewed as a splat
5979 // constant.
5980 Value *Arg0 = Inst->getOperand(0);
5981 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5982 isa<ConstantFP>(Arg0);
5983 TargetTransformInfo::OperandValueKind Arg0OVK =
5984 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5985 : TargetTransformInfo::OK_AnyValue;
5986 TargetTransformInfo::OperandValueKind Arg1OVK =
5987 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5988 : TargetTransformInfo::OK_AnyValue;
5989 ScalarCost += TTI.getArithmeticInstrCost(
5990 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5991 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5992 Arg0OVK, Arg1OVK);
5993 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005994 LLVM_DEBUG(
5995 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5996 << ScalarCost << "\nVector: " << VectorCost << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00005997 return ScalarCost > VectorCost;
5998 }
5999
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006000 /// Generate a constant vector with \p Val with the same
Quentin Colombetc32615d2014-10-31 17:52:53 +00006001 /// number of elements as the transition.
6002 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00006003 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006004 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
6005 /// otherwise we generate a vector with as many undef as possible:
6006 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
6007 /// used at the index of the extract.
6008 Value *getConstantVector(Constant *Val, bool UseSplat) const {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006009 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006010 if (!UseSplat) {
6011 // If we cannot determine where the constant must be, we have to
6012 // use a splat constant.
6013 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
6014 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
6015 ExtractIdx = CstVal->getSExtValue();
6016 else
6017 UseSplat = true;
6018 }
6019
6020 unsigned End = getTransitionType()->getVectorNumElements();
6021 if (UseSplat)
6022 return ConstantVector::getSplat(End, Val);
6023
6024 SmallVector<Constant *, 4> ConstVec;
6025 UndefValue *UndefVal = UndefValue::get(Val->getType());
6026 for (unsigned Idx = 0; Idx != End; ++Idx) {
6027 if (Idx == ExtractIdx)
6028 ConstVec.push_back(Val);
6029 else
6030 ConstVec.push_back(UndefVal);
6031 }
6032 return ConstantVector::get(ConstVec);
6033 }
6034
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006035 /// Check if promoting to a vector type an operand at \p OperandIdx
Quentin Colombetc32615d2014-10-31 17:52:53 +00006036 /// in \p Use can trigger undefined behavior.
6037 static bool canCauseUndefinedBehavior(const Instruction *Use,
6038 unsigned OperandIdx) {
6039 // This is not safe to introduce undef when the operand is on
6040 // the right hand side of a division-like instruction.
6041 if (OperandIdx != 1)
6042 return false;
6043 switch (Use->getOpcode()) {
6044 default:
6045 return false;
6046 case Instruction::SDiv:
6047 case Instruction::UDiv:
6048 case Instruction::SRem:
6049 case Instruction::URem:
6050 return true;
6051 case Instruction::FDiv:
6052 case Instruction::FRem:
6053 return !Use->hasNoNaNs();
6054 }
6055 llvm_unreachable(nullptr);
6056 }
6057
6058public:
Mehdi Amini44ede332015-07-09 02:09:04 +00006059 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
6060 const TargetTransformInfo &TTI, Instruction *Transition,
6061 unsigned CombineCost)
6062 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Eugene Zelenko900b6332017-08-29 22:32:07 +00006063 StoreExtractCombineCost(CombineCost) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00006064 assert(Transition && "Do not know how to promote null");
6065 }
6066
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006067 /// Check if we can promote \p ToBePromoted to \p Type.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006068 bool canPromote(const Instruction *ToBePromoted) const {
6069 // We could support CastInst too.
6070 return isa<BinaryOperator>(ToBePromoted);
6071 }
6072
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006073 /// Check if it is profitable to promote \p ToBePromoted
Quentin Colombetc32615d2014-10-31 17:52:53 +00006074 /// by moving downward the transition through.
6075 bool shouldPromote(const Instruction *ToBePromoted) const {
6076 // Promote only if all the operands can be statically expanded.
6077 // Indeed, we do not want to introduce any new kind of transitions.
6078 for (const Use &U : ToBePromoted->operands()) {
6079 const Value *Val = U.get();
6080 if (Val == getEndOfTransition()) {
6081 // If the use is a division and the transition is on the rhs,
6082 // we cannot promote the operation, otherwise we may create a
6083 // division by zero.
6084 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
6085 return false;
6086 continue;
6087 }
6088 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
6089 !isa<ConstantFP>(Val))
6090 return false;
6091 }
6092 // Check that the resulting operation is legal.
6093 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
6094 if (!ISDOpcode)
6095 return false;
6096 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00006097 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00006098 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00006099 }
6100
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006101 /// Check whether or not \p Use can be combined
Quentin Colombetc32615d2014-10-31 17:52:53 +00006102 /// with the transition.
6103 /// I.e., is it possible to do Use(Transition) => AnotherUse?
6104 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
6105
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006106 /// Record \p ToBePromoted as part of the chain to be promoted.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006107 void enqueueForPromotion(Instruction *ToBePromoted) {
6108 InstsToBePromoted.push_back(ToBePromoted);
6109 }
6110
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006111 /// Set the instruction that will be combined with the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006112 void recordCombineInstruction(Instruction *ToBeCombined) {
6113 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
6114 CombineInst = ToBeCombined;
6115 }
6116
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006117 /// Promote all the instructions enqueued for promotion if it is
Quentin Colombetc32615d2014-10-31 17:52:53 +00006118 /// is profitable.
6119 /// \return True if the promotion happened, false otherwise.
6120 bool promote() {
6121 // Check if there is something to promote.
6122 // Right now, if we do not have anything to combine with,
6123 // we assume the promotion is not profitable.
6124 if (InstsToBePromoted.empty() || !CombineInst)
6125 return false;
6126
6127 // Check cost.
6128 if (!StressStoreExtract && !isProfitableToPromote())
6129 return false;
6130
6131 // Promote.
6132 for (auto &ToBePromoted : InstsToBePromoted)
6133 promoteImpl(ToBePromoted);
6134 InstsToBePromoted.clear();
6135 return true;
6136 }
6137};
Eugene Zelenko900b6332017-08-29 22:32:07 +00006138
6139} // end anonymous namespace
Quentin Colombetc32615d2014-10-31 17:52:53 +00006140
6141void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
6142 // At this point, we know that all the operands of ToBePromoted but Def
6143 // can be statically promoted.
6144 // For Def, we need to use its parameter in ToBePromoted:
6145 // b = ToBePromoted ty1 a
6146 // Def = Transition ty1 b to ty2
6147 // Move the transition down.
6148 // 1. Replace all uses of the promoted operation by the transition.
6149 // = ... b => = ... Def.
6150 assert(ToBePromoted->getType() == Transition->getType() &&
6151 "The type of the result of the transition does not match "
6152 "the final type");
6153 ToBePromoted->replaceAllUsesWith(Transition);
6154 // 2. Update the type of the uses.
6155 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
6156 Type *TransitionTy = getTransitionType();
6157 ToBePromoted->mutateType(TransitionTy);
6158 // 3. Update all the operands of the promoted operation with promoted
6159 // operands.
6160 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
6161 for (Use &U : ToBePromoted->operands()) {
6162 Value *Val = U.get();
6163 Value *NewVal = nullptr;
6164 if (Val == Transition)
6165 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
6166 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
6167 isa<ConstantFP>(Val)) {
6168 // Use a splat constant if it is not safe to use undef.
6169 NewVal = getConstantVector(
6170 cast<Constant>(Val),
6171 isa<UndefValue>(Val) ||
6172 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
6173 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00006174 llvm_unreachable("Did you modified shouldPromote and forgot to update "
6175 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006176 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
6177 }
Sanjay Patel674d2c22017-08-29 14:07:48 +00006178 Transition->moveAfter(ToBePromoted);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006179 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6180}
6181
6182/// Some targets can do store(extractelement) with one instruction.
6183/// Try to push the extractelement towards the stores when the target
6184/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006185bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006186 unsigned CombineCost = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006187 if (DisableStoreExtract || !TLI ||
6188 (!StressStoreExtract &&
6189 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
6190 Inst->getOperand(1), CombineCost)))
6191 return false;
6192
6193 // At this point we know that Inst is a vector to scalar transition.
6194 // Try to move it down the def-use chain, until:
6195 // - We can combine the transition with its single use
6196 // => we got rid of the transition.
6197 // - We escape the current basic block
6198 // => we would need to check that we are moving it at a cheaper place and
6199 // we do not do that for now.
6200 BasicBlock *Parent = Inst->getParent();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006201 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00006202 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006203 // If the transition has more than one use, assume this is not going to be
6204 // beneficial.
6205 while (Inst->hasOneUse()) {
6206 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006207 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006208
6209 if (ToBePromoted->getParent() != Parent) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006210 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
6211 << ToBePromoted->getParent()->getName()
6212 << ") than the transition (" << Parent->getName()
6213 << ").\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006214 return false;
6215 }
6216
6217 if (VPH.canCombine(ToBePromoted)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006218 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
6219 << "will be combined with: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006220 VPH.recordCombineInstruction(ToBePromoted);
6221 bool Changed = VPH.promote();
6222 NumStoreExtractExposed += Changed;
6223 return Changed;
6224 }
6225
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006226 LLVM_DEBUG(dbgs() << "Try promoting.\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006227 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6228 return false;
6229
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006230 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006231
6232 VPH.enqueueForPromotion(ToBePromoted);
6233 Inst = ToBePromoted;
6234 }
6235 return false;
6236}
6237
Wei Mia2f0b592016-12-22 19:44:45 +00006238/// For the instruction sequence of store below, F and I values
6239/// are bundled together as an i64 value before being stored into memory.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006240/// Sometimes it is more efficient to generate separate stores for F and I,
Wei Mia2f0b592016-12-22 19:44:45 +00006241/// which can remove the bitwise instructions or sink them to colder places.
6242///
6243/// (store (or (zext (bitcast F to i32) to i64),
6244/// (shl (zext I to i64), 32)), addr) -->
6245/// (store F, addr) and (store I, addr+4)
6246///
6247/// Similarly, splitting for other merged store can also be beneficial, like:
6248/// For pair of {i32, i32}, i64 store --> two i32 stores.
6249/// For pair of {i32, i16}, i64 store --> two i32 stores.
6250/// For pair of {i16, i16}, i32 store --> two i16 stores.
6251/// For pair of {i16, i8}, i32 store --> two i16 stores.
6252/// For pair of {i8, i8}, i16 store --> two i8 stores.
6253///
6254/// We allow each target to determine specifically which kind of splitting is
6255/// supported.
6256///
6257/// The store patterns are commonly seen from the simple code snippet below
6258/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
6259/// void goo(const std::pair<int, float> &);
6260/// hoo() {
6261/// ...
6262/// goo(std::make_pair(tmp, ftmp));
6263/// ...
6264/// }
6265///
6266/// Although we already have similar splitting in DAG Combine, we duplicate
6267/// it in CodeGenPrepare to catch the case in which pattern is across
6268/// multiple BBs. The logic in DAG Combine is kept to catch case generated
6269/// during code expansion.
6270static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
6271 const TargetLowering &TLI) {
6272 // Handle simple but common cases only.
6273 Type *StoreType = SI.getValueOperand()->getType();
6274 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6275 DL.getTypeSizeInBits(StoreType) == 0)
6276 return false;
6277
6278 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6279 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6280 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6281 DL.getTypeSizeInBits(SplitStoreType))
6282 return false;
6283
6284 // Match the following patterns:
6285 // (store (or (zext LValue to i64),
6286 // (shl (zext HValue to i64), 32)), HalfValBitSize)
6287 // or
6288 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6289 // (zext LValue to i64),
6290 // Expect both operands of OR and the first operand of SHL have only
6291 // one use.
6292 Value *LValue, *HValue;
6293 if (!match(SI.getValueOperand(),
6294 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6295 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6296 m_SpecificInt(HalfValBitSize))))))
6297 return false;
6298
6299 // Check LValue and HValue are int with size less or equal than 32.
6300 if (!LValue->getType()->isIntegerTy() ||
6301 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6302 !HValue->getType()->isIntegerTy() ||
6303 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6304 return false;
6305
6306 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6307 // as the input of target query.
6308 auto *LBC = dyn_cast<BitCastInst>(LValue);
6309 auto *HBC = dyn_cast<BitCastInst>(HValue);
6310 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6311 : EVT::getEVT(LValue->getType());
6312 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6313 : EVT::getEVT(HValue->getType());
6314 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6315 return false;
6316
6317 // Start to split store.
6318 IRBuilder<> Builder(SI.getContext());
6319 Builder.SetInsertPoint(&SI);
6320
6321 // If LValue/HValue is a bitcast in another BB, create a new one in current
6322 // BB so it may be merged with the splitted stores by dag combiner.
6323 if (LBC && LBC->getParent() != SI.getParent())
6324 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6325 if (HBC && HBC->getParent() != SI.getParent())
6326 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6327
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006328 bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
Wei Mia2f0b592016-12-22 19:44:45 +00006329 auto CreateSplitStore = [&](Value *V, bool Upper) {
6330 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6331 Value *Addr = Builder.CreateBitCast(
6332 SI.getOperand(1),
6333 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006334 if ((IsLE && Upper) || (!IsLE && !Upper))
Wei Mia2f0b592016-12-22 19:44:45 +00006335 Addr = Builder.CreateGEP(
6336 SplitStoreType, Addr,
6337 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6338 Builder.CreateAlignedStore(
6339 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6340 };
6341
6342 CreateSplitStore(LValue, false);
6343 CreateSplitStore(HValue, true);
6344
6345 // Delete the old store.
6346 SI.eraseFromParent();
6347 return true;
6348}
6349
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006350// Return true if the GEP has two operands, the first operand is of a sequential
6351// type, and the second operand is a constant.
6352static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6353 gep_type_iterator I = gep_type_begin(*GEP);
6354 return GEP->getNumOperands() == 2 &&
6355 I.isSequential() &&
6356 isa<ConstantInt>(GEP->getOperand(1));
6357}
6358
6359// Try unmerging GEPs to reduce liveness interference (register pressure) across
6360// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6361// reducing liveness interference across those edges benefits global register
6362// allocation. Currently handles only certain cases.
6363//
6364// For example, unmerge %GEPI and %UGEPI as below.
6365//
6366// ---------- BEFORE ----------
6367// SrcBlock:
6368// ...
6369// %GEPIOp = ...
6370// ...
6371// %GEPI = gep %GEPIOp, Idx
6372// ...
6373// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6374// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6375// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6376// %UGEPI)
6377//
6378// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6379// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6380// ...
6381//
6382// DstBi:
6383// ...
6384// %UGEPI = gep %GEPIOp, UIdx
6385// ...
6386// ---------------------------
6387//
6388// ---------- AFTER ----------
6389// SrcBlock:
6390// ... (same as above)
6391// (* %GEPI is still alive on the indirectbr edges)
6392// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6393// unmerging)
6394// ...
6395//
6396// DstBi:
6397// ...
6398// %UGEPI = gep %GEPI, (UIdx-Idx)
6399// ...
6400// ---------------------------
6401//
6402// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6403// no longer alive on them.
6404//
6405// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6406// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6407// not to disable further simplications and optimizations as a result of GEP
6408// merging.
6409//
6410// Note this unmerging may increase the length of the data flow critical path
6411// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6412// between the register pressure and the length of data-flow critical
6413// path. Restricting this to the uncommon IndirectBr case would minimize the
6414// impact of potentially longer critical path, if any, and the impact on compile
6415// time.
6416static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6417 const TargetTransformInfo *TTI) {
6418 BasicBlock *SrcBlock = GEPI->getParent();
6419 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6420 // (non-IndirectBr) cases exit early here.
6421 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6422 return false;
6423 // Check that GEPI is a simple gep with a single constant index.
6424 if (!GEPSequentialConstIndexed(GEPI))
6425 return false;
6426 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6427 // Check that GEPI is a cheap one.
6428 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6429 > TargetTransformInfo::TCC_Basic)
6430 return false;
6431 Value *GEPIOp = GEPI->getOperand(0);
6432 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6433 if (!isa<Instruction>(GEPIOp))
6434 return false;
6435 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6436 if (GEPIOpI->getParent() != SrcBlock)
6437 return false;
6438 // Check that GEP is used outside the block, meaning it's alive on the
6439 // IndirectBr edge(s).
6440 if (find_if(GEPI->users(), [&](User *Usr) {
6441 if (auto *I = dyn_cast<Instruction>(Usr)) {
6442 if (I->getParent() != SrcBlock) {
6443 return true;
6444 }
6445 }
6446 return false;
6447 }) == GEPI->users().end())
6448 return false;
6449 // The second elements of the GEP chains to be unmerged.
6450 std::vector<GetElementPtrInst *> UGEPIs;
6451 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6452 // on IndirectBr edges.
6453 for (User *Usr : GEPIOp->users()) {
6454 if (Usr == GEPI) continue;
6455 // Check if Usr is an Instruction. If not, give up.
6456 if (!isa<Instruction>(Usr))
6457 return false;
6458 auto *UI = cast<Instruction>(Usr);
6459 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6460 if (UI->getParent() == SrcBlock)
6461 continue;
6462 // Check if Usr is a GEP. If not, give up.
6463 if (!isa<GetElementPtrInst>(Usr))
6464 return false;
6465 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6466 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6467 // the pointer operand to it. If so, record it in the vector. If not, give
6468 // up.
6469 if (!GEPSequentialConstIndexed(UGEPI))
6470 return false;
6471 if (UGEPI->getOperand(0) != GEPIOp)
6472 return false;
6473 if (GEPIIdx->getType() !=
6474 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6475 return false;
6476 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6477 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6478 > TargetTransformInfo::TCC_Basic)
6479 return false;
6480 UGEPIs.push_back(UGEPI);
6481 }
6482 if (UGEPIs.size() == 0)
6483 return false;
6484 // Check the materializing cost of (Uidx-Idx).
6485 for (GetElementPtrInst *UGEPI : UGEPIs) {
6486 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6487 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6488 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6489 if (ImmCost > TargetTransformInfo::TCC_Basic)
6490 return false;
6491 }
6492 // Now unmerge between GEPI and UGEPIs.
6493 for (GetElementPtrInst *UGEPI : UGEPIs) {
6494 UGEPI->setOperand(0, GEPI);
6495 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6496 Constant *NewUGEPIIdx =
6497 ConstantInt::get(GEPIIdx->getType(),
6498 UGEPIIdx->getValue() - GEPIIdx->getValue());
6499 UGEPI->setOperand(1, NewUGEPIIdx);
6500 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6501 // inbounds to avoid UB.
6502 if (!GEPI->isInBounds()) {
6503 UGEPI->setIsInBounds(false);
6504 }
6505 }
6506 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6507 // alive on IndirectBr edges).
6508 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6509 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6510 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6511 return true;
6512}
6513
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006514bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00006515 // Bail out if we inserted the instruction to prevent optimizations from
6516 // stepping on each other's toes.
6517 if (InsertedInsts.count(I))
6518 return false;
6519
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006520 if (PHINode *P = dyn_cast<PHINode>(I)) {
6521 // It is possible for very late stage optimizations (such as SimplifyCFG)
6522 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6523 // trivial PHI, go ahead and zap it here.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00006524 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006525 P->replaceAllUsesWith(V);
6526 P->eraseFromParent();
6527 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00006528 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006529 }
Chris Lattneree588de2011-01-15 07:29:01 +00006530 return false;
6531 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006532
Chris Lattneree588de2011-01-15 07:29:01 +00006533 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006534 // If the source of the cast is a constant, then this should have
6535 // already been constant folded. The only reason NOT to constant fold
6536 // it is if something (e.g. LSR) was careful to place the constant
6537 // evaluation in a block other than then one that uses it (e.g. to hoist
6538 // the address of globals out of a loop). If this is the case, we don't
6539 // want to forward-subst the cast.
6540 if (isa<Constant>(CI->getOperand(0)))
6541 return false;
6542
Mehdi Amini44ede332015-07-09 02:09:04 +00006543 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00006544 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006545
Chris Lattneree588de2011-01-15 07:29:01 +00006546 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006547 /// Sink a zext or sext into its user blocks if the target type doesn't
6548 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00006549 if (TLI &&
6550 TLI->getTypeAction(CI->getContext(),
6551 TLI->getValueType(*DL, CI->getType())) ==
6552 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006553 return SinkCast(CI);
6554 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00006555 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00006556 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006557 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006558 }
Chris Lattneree588de2011-01-15 07:29:01 +00006559 return false;
6560 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006561
Chris Lattneree588de2011-01-15 07:29:01 +00006562 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00006563 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00006564 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00006565
Chris Lattneree588de2011-01-15 07:29:01 +00006566 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006567 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006568 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006569 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006570 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006571 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6572 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006573 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006574 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006575 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006576
Chris Lattneree588de2011-01-15 07:29:01 +00006577 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006578 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6579 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006580 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006581 if (TLI) {
6582 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006583 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006584 SI->getOperand(0)->getType(), AS);
6585 }
Chris Lattneree588de2011-01-15 07:29:01 +00006586 return false;
6587 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006588
Matt Arsenault02d915b2017-03-15 22:35:20 +00006589 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6590 unsigned AS = RMW->getPointerAddressSpace();
6591 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6592 RMW->getType(), AS);
6593 }
6594
6595 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6596 unsigned AS = CmpX->getPointerAddressSpace();
6597 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6598 CmpX->getCompareOperand()->getType(), AS);
6599 }
6600
Yi Jiangd069f632014-04-21 19:34:27 +00006601 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6602
Geoff Berry5d534b62017-02-21 18:53:14 +00006603 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6604 EnableAndCmpSinking && TLI)
6605 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6606
Yi Jiangd069f632014-04-21 19:34:27 +00006607 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6608 BinOp->getOpcode() == Instruction::LShr)) {
6609 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6610 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006611 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006612
6613 return false;
6614 }
6615
Chris Lattneree588de2011-01-15 07:29:01 +00006616 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006617 if (GEPI->hasAllZeroIndices()) {
6618 /// The GEP operand must be a pointer, so must its result -> BitCast
6619 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6620 GEPI->getName(), GEPI);
Vedant Kumar40399a22018-05-24 23:00:21 +00006621 NC->setDebugLoc(GEPI->getDebugLoc());
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006622 GEPI->replaceAllUsesWith(NC);
6623 GEPI->eraseFromParent();
6624 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00006625 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00006626 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006627 }
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006628 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
6629 return true;
6630 }
Chris Lattneree588de2011-01-15 07:29:01 +00006631 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006632 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006633
Chris Lattneree588de2011-01-15 07:29:01 +00006634 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006635 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006636
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006637 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006638 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006639
Tim Northoveraeb8e062014-02-19 10:02:43 +00006640 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006641 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006642
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006643 if (auto *Switch = dyn_cast<SwitchInst>(I))
6644 return optimizeSwitchInst(Switch);
6645
Quentin Colombetc32615d2014-10-31 17:52:53 +00006646 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006647 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006648
Chris Lattneree588de2011-01-15 07:29:01 +00006649 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006650}
6651
James Molloyf01488e2016-01-15 09:20:19 +00006652/// Given an OR instruction, check to see if this is a bitreverse
6653/// idiom. If so, insert the new intrinsic and return true.
6654static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6655 const TargetLowering &TLI) {
6656 if (!I.getType()->isIntegerTy() ||
6657 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6658 TLI.getValueType(DL, I.getType(), true)))
6659 return false;
6660
6661 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00006662 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00006663 return false;
6664 Instruction *LastInst = Insts.back();
6665 I.replaceAllUsesWith(LastInst);
6666 RecursivelyDeleteTriviallyDeadInstructions(&I);
6667 return true;
6668}
6669
Chris Lattnerf2836d12007-03-31 04:06:36 +00006670// In this pass we look for GEP and cast instructions that are used
6671// across basic blocks and rewrite them to improve basic-block-at-a-time
6672// selection.
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006673bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00006674 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00006675 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00006676
Chris Lattner7a277142011-01-15 07:14:54 +00006677 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006678 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006679 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006680 if (ModifiedDT)
6681 return true;
6682 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00006683
James Molloyf01488e2016-01-15 09:20:19 +00006684 bool MadeBitReverse = true;
6685 while (TLI && MadeBitReverse) {
6686 MadeBitReverse = false;
6687 for (auto &I : reverse(BB)) {
6688 if (makeBitReverse(I, *DL, *TLI)) {
6689 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00006690 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00006691 break;
6692 }
6693 }
6694 }
James Molloy3ef84c42016-01-15 10:36:01 +00006695 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00006696
Chris Lattnerf2836d12007-03-31 04:06:36 +00006697 return MadeChange;
6698}
Devang Patel53771ba2011-08-18 00:50:51 +00006699
6700// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00006701// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00006702// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006703bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00006704 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006705 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00006706 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006707 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006708 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00006709 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00006710 // Leave dbg.values that refer to an alloca alone. These
Craig Topper87e715f2017-11-07 20:56:17 +00006711 // intrinsics describe the address of a variable (= the alloca)
Adrian Prantl32da8892014-04-25 20:49:25 +00006712 // being taken. They should not be moved next to the alloca
6713 // (and to the beginning of the scope), but rather stay close to
6714 // where said address is used.
6715 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00006716 PrevNonDbgInst = Insn;
6717 continue;
6718 }
6719
6720 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6721 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00006722 // If VI is a phi in a block with an EHPad terminator, we can't insert
6723 // after it.
6724 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6725 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006726 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
6727 << *DVI << ' ' << *VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006728 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00006729 if (isa<PHINode>(VI))
6730 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6731 else
6732 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006733 MadeChange = true;
6734 ++NumDbgValueMoved;
6735 }
6736 }
6737 }
6738 return MadeChange;
6739}
Tim Northovercea0abb2014-03-29 08:22:29 +00006740
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006741/// Scale down both weights to fit into uint32_t.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006742static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6743 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006744 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006745 NewTrue = NewTrue / Scale;
6746 NewFalse = NewFalse / Scale;
6747}
6748
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006749/// Some targets prefer to split a conditional branch like:
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006750/// \code
6751/// %0 = icmp ne i32 %a, 0
6752/// %1 = icmp ne i32 %b, 0
6753/// %or.cond = or i1 %0, %1
6754/// br i1 %or.cond, label %TrueBB, label %FalseBB
6755/// \endcode
6756/// into multiple branch instructions like:
6757/// \code
6758/// bb1:
6759/// %0 = icmp ne i32 %a, 0
6760/// br i1 %0, label %TrueBB, label %bb2
6761/// bb2:
6762/// %1 = icmp ne i32 %b, 0
6763/// br i1 %1, label %TrueBB, label %FalseBB
6764/// \endcode
6765/// This usually allows instruction selection to do even further optimizations
6766/// and combine the compare with the branch instruction. Currently this is
6767/// applied for targets which have "cheap" jump instructions.
6768///
6769/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6770///
6771bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006772 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006773 return false;
6774
6775 bool MadeChange = false;
6776 for (auto &BB : F) {
6777 // Does this BB end with the following?
6778 // %cond1 = icmp|fcmp|binary instruction ...
6779 // %cond2 = icmp|fcmp|binary instruction ...
6780 // %cond.or = or|and i1 %cond1, cond2
6781 // br i1 %cond.or label %dest1, label %dest2"
6782 BinaryOperator *LogicOp;
6783 BasicBlock *TBB, *FBB;
6784 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6785 continue;
6786
Sanjay Patel42574202015-09-02 19:23:23 +00006787 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6788 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6789 continue;
6790
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006791 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006792 Value *Cond1, *Cond2;
6793 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6794 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006795 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006796 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6797 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006798 Opc = Instruction::Or;
6799 else
6800 continue;
6801
6802 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6803 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6804 continue;
6805
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006806 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006807
6808 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00006809 auto TmpBB =
6810 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6811 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006812
6813 // Update original basic block by using the first condition directly by the
6814 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006815 Br1->setCondition(Cond1);
6816 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006817
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006818 // Depending on the condition we have to either replace the true or the
6819 // false successor of the original branch instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006820 if (Opc == Instruction::And)
6821 Br1->setSuccessor(0, TmpBB);
6822 else
6823 Br1->setSuccessor(1, TmpBB);
6824
6825 // Fill in the new basic block.
6826 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006827 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6828 I->removeFromParent();
6829 I->insertBefore(Br2);
6830 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006831
6832 // Update PHI nodes in both successors. The original BB needs to be
Hiroshi Inoue6a391bb2017-06-27 10:35:37 +00006833 // replaced in one successor's PHI nodes, because the branch comes now from
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006834 // the newly generated BB (NewBB). In the other successor we need to add one
6835 // incoming edge to the PHI nodes, because both branch instructions target
6836 // now the same successor. Depending on the original branch condition
6837 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006838 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006839 // This doesn't change the successor order of the just created branch
6840 // instruction (or any other instruction).
6841 if (Opc == Instruction::Or)
6842 std::swap(TBB, FBB);
6843
6844 // Replace the old BB with the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006845 for (PHINode &PN : TBB->phis()) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006846 int i;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006847 while ((i = PN.getBasicBlockIndex(&BB)) >= 0)
6848 PN.setIncomingBlock(i, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006849 }
6850
6851 // Add another incoming edge form the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006852 for (PHINode &PN : FBB->phis()) {
6853 auto *Val = PN.getIncomingValueForBlock(&BB);
6854 PN.addIncoming(Val, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006855 }
6856
6857 // Update the branch weights (from SelectionDAGBuilder::
6858 // FindMergedConditions).
6859 if (Opc == Instruction::Or) {
6860 // Codegen X | Y as:
6861 // BB1:
6862 // jmp_if_X TBB
6863 // jmp TmpBB
6864 // TmpBB:
6865 // jmp_if_Y TBB
6866 // jmp FBB
6867 //
6868
6869 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6870 // The requirement is that
6871 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006872 // = TrueProb for original BB.
6873 // Assuming the original weights are A and B, one choice is to set BB1's
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006874 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6875 // assumes that
6876 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6877 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6878 // TmpBB, but the math is more complicated.
6879 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006880 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006881 uint64_t NewTrueWeight = TrueWeight;
6882 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6883 scaleWeights(NewTrueWeight, NewFalseWeight);
6884 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6885 .createBranchWeights(TrueWeight, FalseWeight));
6886
6887 NewTrueWeight = TrueWeight;
6888 NewFalseWeight = 2 * FalseWeight;
6889 scaleWeights(NewTrueWeight, NewFalseWeight);
6890 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6891 .createBranchWeights(TrueWeight, FalseWeight));
6892 }
6893 } else {
6894 // Codegen X & Y as:
6895 // BB1:
6896 // jmp_if_X TmpBB
6897 // jmp FBB
6898 // TmpBB:
6899 // jmp_if_Y TBB
6900 // jmp FBB
6901 //
6902 // This requires creation of TmpBB after CurBB.
6903
6904 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6905 // The requirement is that
6906 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006907 // = FalseProb for original BB.
6908 // Assuming the original weights are A and B, one choice is to set BB1's
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006909 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6910 // assumes that
6911 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6912 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006913 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006914 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6915 uint64_t NewFalseWeight = FalseWeight;
6916 scaleWeights(NewTrueWeight, NewFalseWeight);
6917 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6918 .createBranchWeights(TrueWeight, FalseWeight));
6919
6920 NewTrueWeight = 2 * TrueWeight;
6921 NewFalseWeight = FalseWeight;
6922 scaleWeights(NewTrueWeight, NewFalseWeight);
6923 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6924 .createBranchWeights(TrueWeight, FalseWeight));
6925 }
6926 }
6927
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006928 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00006929 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006930 ModifiedDT = true;
6931
6932 MadeChange = true;
6933
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006934 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6935 TmpBB->dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006936 }
6937 return MadeChange;
6938}