blob: 1e04f7918ee05d76f7306932cc8ffb65b5b21720 [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerf2836d12007-03-31 04:06:36 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000010// SelectionDAG-based code generation. This works around limitations in it's
11// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000012//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenko900b6332017-08-29 22:32:07 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000018#include "llvm/ADT/PointerIntPair.h"
19#include "llvm/ADT/STLExtras.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000020#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/ADT/Statistic.h"
Jun Bum Lim90b6b502016-12-16 20:38:39 +000023#include "llvm/Analysis/BlockFrequencyInfo.h"
24#include "llvm/Analysis/BranchProbabilityInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000025#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000027#include "llvm/Analysis/LoopInfo.h"
Zaara Syeda3a7578c2017-05-31 17:12:38 +000028#include "llvm/Analysis/MemoryBuiltins.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000029#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000030#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000031#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000032#include "llvm/Transforms/Utils/Local.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000033#include "llvm/Analysis/ValueTracking.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000034#include "llvm/CodeGen/Analysis.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000035#include "llvm/CodeGen/ISDOpcodes.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000036#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000037#include "llvm/CodeGen/TargetLowering.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000038#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000039#include "llvm/CodeGen/TargetSubtargetInfo.h"
Craig Topper2fa14362018-03-29 17:21:10 +000040#include "llvm/CodeGen/ValueTypes.h"
Nico Weber432a3882018-04-30 14:59:11 +000041#include "llvm/Config/llvm-config.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000042#include "llvm/IR/Argument.h"
43#include "llvm/IR/Attributes.h"
44#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000045#include "llvm/IR/CallSite.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000046#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Constants.h"
48#include "llvm/IR/DataLayout.h"
49#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000050#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000052#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000053#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/IRBuilder.h"
56#include "llvm/IR/InlineAsm.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000057#include "llvm/IR/InstrTypes.h"
58#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000059#include "llvm/IR/Instructions.h"
60#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000061#include "llvm/IR/Intrinsics.h"
62#include "llvm/IR/LLVMContext.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000063#include "llvm/IR/MDBuilder.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000064#include "llvm/IR/Module.h"
65#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000066#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000067#include "llvm/IR/Statepoint.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000068#include "llvm/IR/Type.h"
69#include "llvm/IR/Use.h"
70#include "llvm/IR/User.h"
71#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000072#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000073#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000074#include "llvm/Pass.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000075#include "llvm/Support/BlockFrequency.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000076#include "llvm/Support/BranchProbability.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000077#include "llvm/Support/Casting.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000078#include "llvm/Support/CommandLine.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000079#include "llvm/Support/Compiler.h"
Evan Chengd3d80172007-12-05 23:58:20 +000080#include "llvm/Support/Debug.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000081#include "llvm/Support/ErrorHandling.h"
David Blaikie13e77db2018-03-23 23:58:25 +000082#include "llvm/Support/MachineValueType.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000083#include "llvm/Support/MathExtras.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000084#include "llvm/Support/raw_ostream.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000085#include "llvm/Target/TargetMachine.h"
86#include "llvm/Target/TargetOptions.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000087#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000088#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000089#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000090#include <algorithm>
91#include <cassert>
92#include <cstdint>
93#include <iterator>
94#include <limits>
95#include <memory>
96#include <utility>
97#include <vector>
Zaara Syeda3a7578c2017-05-31 17:12:38 +000098
Chris Lattnerf2836d12007-03-31 04:06:36 +000099using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +0000100using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000101
Chandler Carruth1b9dde02014-04-22 02:02:50 +0000102#define DEBUG_TYPE "codegenprepare"
103
Cameron Zwarichced753f2011-01-05 17:27:27 +0000104STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +0000105STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
106STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +0000107STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
108 "sunken Cmps");
109STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
110 "of sunken Casts");
111STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
112 "computations were sunk");
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000113STATISTIC(NumMemoryInstsPhiCreated,
114 "Number of phis created when address "
115 "computations were sunk to memory instructions");
116STATISTIC(NumMemoryInstsSelectCreated,
117 "Number of select created when address "
118 "computations were sunk to memory instructions");
Evan Cheng0663f232011-03-21 01:19:09 +0000119STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
120STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +0000121STATISTIC(NumAndsAdded,
122 "Number of and mask instructions added to form ext loads");
123STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +0000124STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +0000125STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000126STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +0000127STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +0000128
Cameron Zwarich338d3622011-03-11 21:52:04 +0000129static cl::opt<bool> DisableBranchOpts(
130 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
131 cl::desc("Disable branch optimizations in CodeGenPrepare"));
132
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000133static cl::opt<bool>
134 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
135 cl::desc("Disable GC optimizations in CodeGenPrepare"));
136
Benjamin Kramer3d38c172012-05-06 14:25:16 +0000137static cl::opt<bool> DisableSelectToBranch(
138 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
139 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000140
Hal Finkelc3998302014-04-12 00:59:48 +0000141static cl::opt<bool> AddrSinkUsingGEPs(
Eli Friedman5fba1e52017-04-06 22:42:18 +0000142 "addr-sink-using-gep", cl::Hidden, cl::init(true),
Hal Finkelc3998302014-04-12 00:59:48 +0000143 cl::desc("Address sinking in CGP using GEPs."));
144
Tim Northovercea0abb2014-03-29 08:22:29 +0000145static cl::opt<bool> EnableAndCmpSinking(
146 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
147 cl::desc("Enable sinkinig and/cmp into branches."));
148
Quentin Colombetc32615d2014-10-31 17:52:53 +0000149static cl::opt<bool> DisableStoreExtract(
150 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
151 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
152
153static cl::opt<bool> StressStoreExtract(
154 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
155 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
156
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000157static cl::opt<bool> DisableExtLdPromotion(
158 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
159 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
160 "CodeGenPrepare"));
161
162static cl::opt<bool> StressExtLdPromotion(
163 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
164 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
165 "optimization in CodeGenPrepare"));
166
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000167static cl::opt<bool> DisablePreheaderProtect(
168 "disable-preheader-prot", cl::Hidden, cl::init(false),
169 cl::desc("Disable protection against removing loop preheaders"));
170
Dehao Chen302b69c2016-10-18 20:42:47 +0000171static cl::opt<bool> ProfileGuidedSectionPrefix(
David Callahan5960d9b12017-06-14 20:35:33 +0000172 "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
Dehao Chen302b69c2016-10-18 20:42:47 +0000173 cl::desc("Use profile info to add section prefix for hot/cold functions"));
174
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000175static cl::opt<unsigned> FreqRatioToSkipMerge(
176 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
177 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
178 "(frequency of destination block) is greater than this ratio"));
179
Wei Mia2f0b592016-12-22 19:44:45 +0000180static cl::opt<bool> ForceSplitStore(
181 "force-split-store", cl::Hidden, cl::init(false),
182 cl::desc("Force store splitting no matter what the target query says."));
183
Jun Bum Limdee55652017-04-03 19:20:07 +0000184static cl::opt<bool>
185EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
186 cl::desc("Enable merging of redundant sexts when one is dominating"
187 " the other."), cl::init(true));
188
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000189static cl::opt<bool> DisableComplexAddrModes(
Serguei Katkovd4df7442017-11-29 09:48:50 +0000190 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000191 cl::desc("Disables combining addressing modes with different parts "
192 "in optimizeMemoryInst."));
193
194static cl::opt<bool>
195AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
196 cl::desc("Allow creation of Phis in Address sinking."));
197
198static cl::opt<bool>
Serguei Katkov9fe05242018-01-26 06:26:56 +0000199AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000200 cl::desc("Allow creation of selects in Address sinking."));
201
John Brawn70cdb5b2017-11-24 14:10:45 +0000202static cl::opt<bool> AddrSinkCombineBaseReg(
203 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
204 cl::desc("Allow combining of BaseReg field in Address sinking."));
205
206static cl::opt<bool> AddrSinkCombineBaseGV(
207 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
208 cl::desc("Allow combining of BaseGV field in Address sinking."));
209
210static cl::opt<bool> AddrSinkCombineBaseOffs(
211 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
212 cl::desc("Allow combining of BaseOffs field in Address sinking."));
213
214static cl::opt<bool> AddrSinkCombineScaledReg(
215 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
216 cl::desc("Allow combining of ScaledReg field in Address sinking."));
217
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000218static cl::opt<bool>
219 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
220 cl::init(true),
221 cl::desc("Enable splitting large offset of GEP."));
222
Eric Christopherc1ea1492008-09-24 05:32:41 +0000223namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000224
Guozhi Wei8c17f9a2018-08-15 22:08:26 +0000225enum ExtType {
226 ZeroExtension, // Zero extension has been seen.
227 SignExtension, // Sign extension has been seen.
228 BothExtension // This extension type is used if we saw sext after
229 // ZeroExtension had been set, or if we saw zext after
230 // SignExtension had been set. It makes the type
231 // information of a promoted instruction invalid.
232};
233
Eugene Zelenko900b6332017-08-29 22:32:07 +0000234using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
Guozhi Wei8c17f9a2018-08-15 22:08:26 +0000235using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000236using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
237using SExts = SmallVector<Instruction *, 16>;
238using ValueToSExts = DenseMap<Value *, SExts>;
239
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000240class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000241
Chris Lattner2dd09db2009-09-02 06:11:42 +0000242 class CodeGenPrepare : public FunctionPass {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000243 const TargetMachine *TM = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000244 const TargetSubtargetInfo *SubtargetInfo;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000245 const TargetLowering *TLI = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000246 const TargetRegisterInfo *TRI;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000247 const TargetTransformInfo *TTI = nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000248 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000249 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000250 std::unique_ptr<BlockFrequencyInfo> BFI;
251 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000252
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000253 /// As we scan instructions optimizing them, this is the next instruction
254 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000255 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000256
Evan Cheng0663f232011-03-21 01:19:09 +0000257 /// Keeps track of non-local addresses that have been sunk into a block.
258 /// This allows us to avoid inserting duplicate code for blocks with
Simon Dardis230f4532017-11-24 16:45:28 +0000259 /// multiple load/stores of the same address. The usage of WeakTrackingVH
260 /// enables SunkAddrs to be treated as a cache whose entries can be
261 /// invalidated if a sunken address computation has been erased.
262 ValueMap<Value*, WeakTrackingVH> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000263
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000264 /// Keeps track of all instructions inserted for the current function.
265 SetOfInstrs InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000266
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000267 /// Keeps track of the type of the related instruction before their
268 /// promotion for the current function.
269 InstrToOrigTy PromotedInsts;
270
Jun Bum Limdee55652017-04-03 19:20:07 +0000271 /// Keep track of instructions removed during promotion.
272 SetOfInstrs RemovedInsts;
273
274 /// Keep track of sext chains based on their initial value.
275 DenseMap<Value *, Instruction *> SeenChainsForSExt;
276
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000277 /// Keep track of GEPs accessing the same data structures such as structs or
278 /// arrays that are candidates to be split later because of their large
279 /// size.
David Greene27e87c2018-09-12 10:19:10 +0000280 MapVector<
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000281 AssertingVH<Value>,
282 SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
283 LargeOffsetGEPMap;
284
285 /// Keep track of new GEP base after splitting the GEPs having large offset.
286 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
287
288 /// Map serial numbers to Large offset GEPs.
289 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
290
Jun Bum Limdee55652017-04-03 19:20:07 +0000291 /// Keep track of SExt promoted.
292 ValueToSExts ValToSExtendedUses;
293
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000294 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000295 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000296
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000297 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000298 bool OptSize;
299
Mehdi Amini4fe37982015-07-07 18:45:17 +0000300 /// DataLayout for the Function being processed.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000301 const DataLayout *DL = nullptr;
Mehdi Amini4fe37982015-07-07 18:45:17 +0000302
Chris Lattnerf2836d12007-03-31 04:06:36 +0000303 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000304 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000305
306 CodeGenPrepare() : FunctionPass(ID) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000307 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
308 }
Eugene Zelenko900b6332017-08-29 22:32:07 +0000309
Craig Topper4584cd52014-03-07 09:26:03 +0000310 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000311
Mehdi Amini117296c2016-10-01 02:56:57 +0000312 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000313
Craig Topper4584cd52014-03-07 09:26:03 +0000314 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000315 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000316 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000317 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000318 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000319 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000320 }
321
Chris Lattnerf2836d12007-03-31 04:06:36 +0000322 private:
James Y Knight72f76bf2018-11-07 15:24:12 +0000323 template <typename F>
324 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
325 // Substituting can cause recursive simplifications, which can invalidate
326 // our iterator. Use a WeakTrackingVH to hold onto it in case this
327 // happens.
328 Value *CurValue = &*CurInstIterator;
329 WeakTrackingVH IterHandle(CurValue);
330
331 f();
332
333 // If the iterator instruction was recursively deleted, start over at the
334 // start of the block.
335 if (IterHandle != CurValue) {
336 CurInstIterator = BB->begin();
337 SunkAddrs.clear();
338 }
339 }
340
Sanjay Patelfc580a62015-09-21 23:03:16 +0000341 bool eliminateFallThrough(Function &F);
342 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000343 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000344 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
345 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000346 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
347 bool isPreheader);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000348 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
349 bool optimizeInst(Instruction *I, bool &ModifiedDT);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000350 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
351 Type *AccessTy, unsigned AddrSpace);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000352 bool optimizeInlineAsmInst(CallInst *CS);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000353 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000354 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000355 bool optimizeExtUses(Instruction *I);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000356 bool optimizeLoadExt(LoadInst *Load);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000357 bool optimizeSelectInst(SelectInst *SI);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000358 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
359 bool optimizeSwitchInst(SwitchInst *SI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000360 bool optimizeExtractElementInst(Instruction *Inst);
361 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
362 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000363 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
364 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
365 bool tryToPromoteExts(TypePromotionTransaction &TPT,
366 const SmallVectorImpl<Instruction *> &Exts,
367 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
368 unsigned CreatedInstsCost = 0);
Jun Bum Limdee55652017-04-03 19:20:07 +0000369 bool mergeSExts(Function &F);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000370 bool splitLargeGEPOffsets();
Jun Bum Limdee55652017-04-03 19:20:07 +0000371 bool performAddressTypePromotion(
372 Instruction *&Inst,
373 bool AllowPromotionWithoutCommonHeader,
374 bool HasPromoted, TypePromotionTransaction &TPT,
375 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000376 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000377 bool simplifyOffsetableRelocate(Instruction &I);
Florian Hahn3b251962019-02-05 10:27:40 +0000378
379 bool tryToSinkFreeOperands(Instruction *I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000380 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000381
382} // end anonymous namespace
Devang Patel09f162c2007-05-01 21:15:47 +0000383
Devang Patel8c78a0b2007-05-03 01:11:54 +0000384char CodeGenPrepare::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000385
Matthias Braun1527baa2017-05-25 21:26:32 +0000386INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000387 "Optimize for code generation", false, false)
Dehao Chen302b69c2016-10-18 20:42:47 +0000388INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000389INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000390 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000391
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000392FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000393
Chris Lattnerf2836d12007-03-31 04:06:36 +0000394bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000395 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000396 return false;
397
Mehdi Amini4fe37982015-07-07 18:45:17 +0000398 DL = &F.getParent()->getDataLayout();
399
Chris Lattnerf2836d12007-03-31 04:06:36 +0000400 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000401 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000402 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000403 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000404
Devang Patel8f606d72011-03-24 15:35:25 +0000405 ModifiedDT = false;
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000406 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
407 TM = &TPC->getTM<TargetMachine>();
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000408 SubtargetInfo = TM->getSubtargetImpl(F);
409 TLI = SubtargetInfo->getTargetLowering();
410 TRI = SubtargetInfo->getRegisterInfo();
411 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000412 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000413 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000414 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000415 BPI.reset(new BranchProbabilityInfo(F, *LI));
416 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000417 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000418
Easwaran Raman0d55b552017-11-14 19:31:51 +0000419 ProfileSummaryInfo *PSI =
Vedant Kumare7b789b2018-11-19 05:23:16 +0000420 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen302b69c2016-10-18 20:42:47 +0000421 if (ProfileGuidedSectionPrefix) {
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000422 if (PSI->isFunctionHotInCallGraph(&F, *BFI))
Dehao Chen302b69c2016-10-18 20:42:47 +0000423 F.setSectionPrefix(".hot");
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000424 else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
Teresa Johnson720d9b42017-05-09 01:43:24 +0000425 F.setSectionPrefix(".unlikely");
Dehao Chen302b69c2016-10-18 20:42:47 +0000426 }
427
Preston Gurdcdf540d2012-09-04 18:22:17 +0000428 /// This optimization identifies DIV instructions that can be
429 /// profitably bypassed and carried out with a shorter, faster divide.
Easwaran Raman0d55b552017-11-14 19:31:51 +0000430 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
431 TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000432 const DenseMap<unsigned int, unsigned int> &BypassWidths =
433 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000434 BasicBlock* BB = &*F.begin();
435 while (BB != nullptr) {
436 // bypassSlowDivision may create new BBs, but we don't want to reapply the
437 // optimization to those blocks.
438 BasicBlock* Next = BB->getNextNode();
439 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
440 BB = Next;
441 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000442 }
443
444 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000445 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000446 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000447
Geoff Berry5d534b62017-02-21 18:53:14 +0000448 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000449 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000450
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000451 // Split some critical edges where one of the sources is an indirect branch,
452 // to help generate sane code for PHIs involving such edges.
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000453 EverMadeChange |= SplitIndirectBrCriticalEdges(F);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000454
Chris Lattnerc3748562007-04-02 01:35:34 +0000455 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000456 while (MadeChange) {
457 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000458 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000459 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000460 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000461 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000462
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000463 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000464 if (ModifiedDTOnIteration)
465 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000466 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000467 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
468 MadeChange |= mergeSExts(F);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000469 if (!LargeOffsetGEPMap.empty())
470 MadeChange |= splitLargeGEPOffsets();
Jun Bum Limdee55652017-04-03 19:20:07 +0000471
472 // Really free removed instructions during promotion.
473 for (Instruction *I : RemovedInsts)
Reid Kleckner96ab8722017-05-18 17:24:10 +0000474 I->deleteValue();
Jun Bum Limdee55652017-04-03 19:20:07 +0000475
Chris Lattnerf2836d12007-03-31 04:06:36 +0000476 EverMadeChange |= MadeChange;
Peter Collingbourneabd820a2018-10-23 21:23:18 +0000477 SeenChainsForSExt.clear();
478 ValToSExtendedUses.clear();
479 RemovedInsts.clear();
480 LargeOffsetGEPMap.clear();
481 LargeOffsetGEPID.clear();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000482 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000483
484 SunkAddrs.clear();
485
Cameron Zwarich338d3622011-03-11 21:52:04 +0000486 if (!DisableBranchOpts) {
487 MadeChange = false;
David Stenberg23bba562018-07-02 14:23:48 +0000488 // Use a set vector to get deterministic iteration order. The order the
489 // blocks are removed may affect whether or not PHI nodes in successors
490 // are removed.
491 SmallSetVector<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000492 for (BasicBlock &BB : F) {
493 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
494 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000495 if (!MadeChange) continue;
496
497 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 }
502
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000503 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000504 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000505 while (!WorkList.empty()) {
David Stenberg23bba562018-07-02 14:23:48 +0000506 BasicBlock *BB = WorkList.pop_back_val();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000507 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
508
509 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000510
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000511 for (SmallVectorImpl<BasicBlock*>::iterator
512 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
513 if (pred_begin(*II) == pred_end(*II))
514 WorkList.insert(*II);
515 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000516
Nadav Rotem70409992012-08-14 05:19:07 +0000517 // Merge pairs of basic blocks with unconditional branches, connected by
518 // a single edge.
519 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000520 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000521
Cameron Zwarich338d3622011-03-11 21:52:04 +0000522 EverMadeChange |= MadeChange;
523 }
524
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000525 if (!DisableGCOpts) {
526 SmallVector<Instruction *, 2> Statepoints;
527 for (BasicBlock &BB : F)
528 for (Instruction &I : BB)
529 if (isStatepoint(I))
530 Statepoints.push_back(&I);
531 for (auto &I : Statepoints)
532 EverMadeChange |= simplifyOffsetableRelocate(*I);
533 }
534
Vedant Kumar30406fd2018-08-21 23:43:08 +0000535 // Do this last to clean up use-before-def scenarios introduced by other
536 // preparatory transforms.
537 EverMadeChange |= placeDbgValues(F);
538
Chris Lattnerf2836d12007-03-31 04:06:36 +0000539 return EverMadeChange;
540}
541
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000542/// Merge basic blocks which are connected by a single edge, where one of the
543/// basic blocks has a single successor pointing to the other basic block,
544/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000545bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000546 bool Changed = false;
547 // Scan all of the blocks in the function, except for the entry block.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000548 // Use a temporary array to avoid iterator being invalidated when
549 // deleting blocks.
550 SmallVector<WeakTrackingVH, 16> Blocks;
551 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
552 Blocks.push_back(&Block);
553
554 for (auto &Block : Blocks) {
555 auto *BB = cast_or_null<BasicBlock>(Block);
556 if (!BB)
557 continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000558 // If the destination block has a single pred, then this is a trivial
559 // edge, just collapse it.
560 BasicBlock *SinglePred = BB->getSinglePredecessor();
561
Evan Cheng64a223a2012-09-28 23:58:57 +0000562 // Don't merge if BB's address is taken.
563 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000564
565 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
566 if (Term && !Term->isConditional()) {
567 Changed = true;
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000568 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000569
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000570 // Merge BB into SinglePred and delete it.
571 MergeBlockIntoPredecessor(BB);
Nadav Rotem70409992012-08-14 05:19:07 +0000572 }
573 }
574 return Changed;
575}
576
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000577/// Find a destination block from BB if BB is mergeable empty block.
578BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
579 // If this block doesn't end with an uncond branch, ignore it.
580 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
581 if (!BI || !BI->isUnconditional())
582 return nullptr;
583
584 // If the instruction before the branch (skipping debug info) isn't a phi
585 // node, then other stuff is happening here.
586 BasicBlock::iterator BBI = BI->getIterator();
587 if (BBI != BB->begin()) {
588 --BBI;
589 while (isa<DbgInfoIntrinsic>(BBI)) {
590 if (BBI == BB->begin())
591 break;
592 --BBI;
593 }
594 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
595 return nullptr;
596 }
597
598 // Do not break infinite loops.
599 BasicBlock *DestBB = BI->getSuccessor(0);
600 if (DestBB == BB)
601 return nullptr;
602
603 if (!canMergeBlocks(BB, DestBB))
604 DestBB = nullptr;
605
606 return DestBB;
607}
608
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000609/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
610/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
611/// edges in ways that are non-optimal for isel. Start by eliminating these
612/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000613bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000614 SmallPtrSet<BasicBlock *, 16> Preheaders;
615 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
616 while (!LoopList.empty()) {
617 Loop *L = LoopList.pop_back_val();
618 LoopList.insert(LoopList.end(), L->begin(), L->end());
619 if (BasicBlock *Preheader = L->getLoopPreheader())
620 Preheaders.insert(Preheader);
621 }
622
Chris Lattnerc3748562007-04-02 01:35:34 +0000623 bool MadeChange = false;
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000624 // Copy blocks into a temporary array to avoid iterator invalidation issues
625 // as we remove them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000626 // Note that this intentionally skips the entry block.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000627 SmallVector<WeakTrackingVH, 16> Blocks;
628 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
629 Blocks.push_back(&Block);
630
631 for (auto &Block : Blocks) {
632 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
633 if (!BB)
634 continue;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000635 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
636 if (!DestBB ||
637 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000638 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000639
Sanjay Patelfc580a62015-09-21 23:03:16 +0000640 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000641 MadeChange = true;
642 }
643 return MadeChange;
644}
645
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000646bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
647 BasicBlock *DestBB,
648 bool isPreheader) {
649 // Do not delete loop preheaders if doing so would create a critical edge.
650 // Loop preheaders can be good locations to spill registers. If the
651 // preheader is deleted and we create a critical edge, registers may be
652 // spilled in the loop body instead.
653 if (!DisablePreheaderProtect && isPreheader &&
654 !(BB->getSinglePredecessor() &&
655 BB->getSinglePredecessor()->getSingleSuccessor()))
656 return false;
657
658 // Try to skip merging if the unique predecessor of BB is terminated by a
659 // switch or indirect branch instruction, and BB is used as an incoming block
660 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
661 // add COPY instructions in the predecessor of BB instead of BB (if it is not
662 // merged). Note that the critical edge created by merging such blocks wont be
663 // split in MachineSink because the jump table is not analyzable. By keeping
664 // such empty block (BB), ISel will place COPY instructions in BB, not in the
665 // predecessor of BB.
666 BasicBlock *Pred = BB->getUniquePredecessor();
667 if (!Pred ||
668 !(isa<SwitchInst>(Pred->getTerminator()) ||
669 isa<IndirectBrInst>(Pred->getTerminator())))
670 return true;
671
Jonas Devlieghere42243df2018-08-07 12:14:01 +0000672 if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000673 return true;
674
675 // We use a simple cost heuristic which determine skipping merging is
676 // profitable if the cost of skipping merging is less than the cost of
677 // merging : Cost(skipping merging) < Cost(merging BB), where the
678 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
679 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
680 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
681 // Freq(Pred) / Freq(BB) > 2.
682 // Note that if there are multiple empty blocks sharing the same incoming
683 // value for the PHIs in the DestBB, we consider them together. In such
684 // case, Cost(merging BB) will be the sum of their frequencies.
685
686 if (!isa<PHINode>(DestBB->begin()))
687 return true;
688
689 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
690
691 // Find all other incoming blocks from which incoming values of all PHIs in
692 // DestBB are the same as the ones from BB.
693 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
694 ++PI) {
695 BasicBlock *DestBBPred = *PI;
696 if (DestBBPred == BB)
697 continue;
698
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000699 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
700 return DestPN.getIncomingValueForBlock(BB) ==
701 DestPN.getIncomingValueForBlock(DestBBPred);
702 }))
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000703 SameIncomingValueBBs.insert(DestBBPred);
704 }
705
706 // See if all BB's incoming values are same as the value from Pred. In this
707 // case, no reason to skip merging because COPYs are expected to be place in
708 // Pred already.
709 if (SameIncomingValueBBs.count(Pred))
710 return true;
711
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000712 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
713 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
714
715 for (auto SameValueBB : SameIncomingValueBBs)
716 if (SameValueBB->getUniquePredecessor() == Pred &&
717 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
718 BBFreq += BFI->getBlockFreq(SameValueBB);
719
720 return PredFreq.getFrequency() <=
721 BBFreq.getFrequency() * FreqRatioToSkipMerge;
722}
723
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000724/// Return true if we can merge BB into DestBB if there is a single
725/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000726/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000727bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000728 const BasicBlock *DestBB) const {
729 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
730 // the successor. If there are more complex condition (e.g. preheaders),
731 // don't mess around with them.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000732 for (const PHINode &PN : BB->phis()) {
733 for (const User *U : PN.users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000734 const Instruction *UI = cast<Instruction>(U);
735 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000736 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000737 // If User is inside DestBB block and it is a PHINode then check
738 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000739 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000740 if (UI->getParent() == DestBB) {
741 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000742 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
743 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
744 if (Insn && Insn->getParent() == BB &&
745 Insn->getParent() != UPN->getIncomingBlock(I))
746 return false;
747 }
748 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000749 }
750 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000751
Chris Lattnerc3748562007-04-02 01:35:34 +0000752 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
753 // and DestBB may have conflicting incoming values for the block. If so, we
754 // can't merge the block.
755 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
756 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000757
Chris Lattnerc3748562007-04-02 01:35:34 +0000758 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000759 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000760 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
761 // It is faster to get preds from a PHI than with pred_iterator.
762 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
763 BBPreds.insert(BBPN->getIncomingBlock(i));
764 } else {
765 BBPreds.insert(pred_begin(BB), pred_end(BB));
766 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000767
Chris Lattnerc3748562007-04-02 01:35:34 +0000768 // Walk the preds of DestBB.
769 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
770 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
771 if (BBPreds.count(Pred)) { // Common predecessor?
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000772 for (const PHINode &PN : DestBB->phis()) {
773 const Value *V1 = PN.getIncomingValueForBlock(Pred);
774 const Value *V2 = PN.getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000775
Chris Lattnerc3748562007-04-02 01:35:34 +0000776 // If V2 is a phi node in BB, look up what the mapped value will be.
777 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
778 if (V2PN->getParent() == BB)
779 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000780
Chris Lattnerc3748562007-04-02 01:35:34 +0000781 // If there is a conflict, bail out.
782 if (V1 != V2) return false;
783 }
784 }
785 }
786
787 return true;
788}
789
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000790/// Eliminate a basic block that has only phi's and an unconditional branch in
791/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000792void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000793 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
794 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000795
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000796 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
797 << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000798
Chris Lattnerc3748562007-04-02 01:35:34 +0000799 // If the destination block has a single pred, then this is a trivial edge,
800 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000801 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000802 if (SinglePred != DestBB) {
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000803 assert(SinglePred == BB &&
804 "Single predecessor not the same as predecessor");
805 // Merge DestBB into SinglePred/BB and delete it.
806 MergeBlockIntoPredecessor(DestBB);
807 // Note: BB(=SinglePred) will not be deleted on this path.
808 // DestBB(=its single successor) is the one that was deleted.
809 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000810 return;
811 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000812 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000813
Chris Lattnerc3748562007-04-02 01:35:34 +0000814 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
815 // to handle the new incoming edges it is about to have.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000816 for (PHINode &PN : DestBB->phis()) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000817 // Remove the incoming value for BB, and remember it.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000818 Value *InVal = PN.removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000819
Chris Lattnerc3748562007-04-02 01:35:34 +0000820 // Two options: either the InVal is a phi node defined in BB or it is some
821 // value that dominates BB.
822 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
823 if (InValPhi && InValPhi->getParent() == BB) {
824 // Add all of the input values of the input PHI as inputs of this phi.
825 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000826 PN.addIncoming(InValPhi->getIncomingValue(i),
827 InValPhi->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000828 } else {
829 // Otherwise, add one instance of the dominating value for each edge that
830 // we will be adding.
831 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
832 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000833 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000834 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000835 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000836 PN.addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000837 }
838 }
839 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000840
Chris Lattnerc3748562007-04-02 01:35:34 +0000841 // The PHIs are now updated, change everything that refers to BB to use
842 // DestBB and remove BB.
843 BB->replaceAllUsesWith(DestBB);
844 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000845 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000846
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000847 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000848}
849
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000850// Computes a map of base pointer relocation instructions to corresponding
851// derived pointer relocation instructions given a vector of all relocate calls
852static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000853 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
854 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
855 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000856 // Collect information in two maps: one primarily for locating the base object
857 // while filling the second map; the second map is the final structure holding
858 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000859 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
860 for (auto *ThisRelocate : AllRelocateCalls) {
861 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
862 ThisRelocate->getDerivedPtrIndex());
863 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000864 }
865 for (auto &Item : RelocateIdxMap) {
866 std::pair<unsigned, unsigned> Key = Item.first;
867 if (Key.first == Key.second)
868 // Base relocation: nothing to insert
869 continue;
870
Manuel Jacob83eefa62016-01-05 04:03:00 +0000871 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000872 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000873
874 // We're iterating over RelocateIdxMap so we cannot modify it.
875 auto MaybeBase = RelocateIdxMap.find(BaseKey);
876 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000877 // TODO: We might want to insert a new base object relocate and gep off
878 // that, if there are enough derived object relocates.
879 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000880
881 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000882 }
883}
884
885// Accepts a GEP and extracts the operands into a vector provided they're all
886// small integer constants
887static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
888 SmallVectorImpl<Value *> &OffsetV) {
889 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
890 // Only accept small constant integer operands
891 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
892 if (!Op || Op->getZExtValue() > 20)
893 return false;
894 }
895
896 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
897 OffsetV.push_back(GEP->getOperand(i));
898 return true;
899}
900
901// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
902// replace, computes a replacement, and affects it.
903static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000904simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
905 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000906 bool MadeChange = false;
Serguei Katkov9e5604d2017-08-17 05:48:30 +0000907 // We must ensure the relocation of derived pointer is defined after
908 // relocation of base pointer. If we find a relocation corresponding to base
909 // defined earlier than relocation of base then we move relocation of base
910 // right before found relocation. We consider only relocation in the same
911 // basic block as relocation of base. Relocations from other basic block will
912 // be skipped by optimization and we do not care about them.
913 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
914 &*R != RelocatedBase; ++R)
915 if (auto RI = dyn_cast<GCRelocateInst>(R))
916 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
917 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
918 RelocatedBase->moveBefore(RI);
919 break;
920 }
921
Manuel Jacob83eefa62016-01-05 04:03:00 +0000922 for (GCRelocateInst *ToReplace : Targets) {
923 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000924 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000925 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000926 // A duplicate relocate call. TODO: coalesce duplicates.
927 continue;
928 }
929
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000930 if (RelocatedBase->getParent() != ToReplace->getParent()) {
931 // Base and derived relocates are in different basic blocks.
932 // In this case transform is only valid when base dominates derived
933 // relocate. However it would be too expensive to check dominance
934 // for each such relocate, so we skip the whole transformation.
935 continue;
936 }
937
Manuel Jacob83eefa62016-01-05 04:03:00 +0000938 Value *Base = ToReplace->getBasePtr();
939 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000940 if (!Derived || Derived->getPointerOperand() != Base)
941 continue;
942
943 SmallVector<Value *, 2> OffsetV;
944 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
945 continue;
946
947 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000948 assert(RelocatedBase->getNextNode() &&
949 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000950
951 // Insert after RelocatedBase
952 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000953 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000954
955 // If gc_relocate does not match the actual type, cast it to the right type.
956 // In theory, there must be a bitcast after gc_relocate if the type does not
957 // match, and we should reuse it to get the derived pointer. But it could be
958 // cases like this:
959 // bb1:
960 // ...
961 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
962 // br label %merge
963 //
964 // bb2:
965 // ...
966 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
967 // br label %merge
968 //
969 // merge:
970 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
971 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
972 //
973 // In this case, we can not find the bitcast any more. So we insert a new bitcast
974 // no matter there is already one or not. In this way, we can handle all cases, and
975 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000976 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000977 if (RelocatedBase->getType() != Base->getType()) {
978 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000979 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000980 }
David Blaikie68d535c2015-03-24 22:38:16 +0000981 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000982 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000983 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000984 // If the newly generated derived pointer's type does not match the original derived
985 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000986 Value *ActualReplacement = Replacement;
987 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000988 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000989 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000990 }
991 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000992 ToReplace->eraseFromParent();
993
994 MadeChange = true;
995 }
996 return MadeChange;
997}
998
999// Turns this:
1000//
1001// %base = ...
1002// %ptr = gep %base + 15
1003// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1004// %base' = relocate(%tok, i32 4, i32 4)
1005// %ptr' = relocate(%tok, i32 4, i32 5)
1006// %val = load %ptr'
1007//
1008// into this:
1009//
1010// %base = ...
1011// %ptr = gep %base + 15
1012// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1013// %base' = gc.relocate(%tok, i32 4, i32 4)
1014// %ptr' = gep %base' + 15
1015// %val = load %ptr'
1016bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1017 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +00001018 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001019
1020 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +00001021 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001022 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +00001023 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001024
1025 // We need atleast one base pointer relocation + one derived pointer
1026 // relocation to mangle
1027 if (AllRelocateCalls.size() < 2)
1028 return false;
1029
1030 // RelocateInstMap is a mapping from the base relocate instruction to the
1031 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +00001032 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001033 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1034 if (RelocateInstMap.empty())
1035 return false;
1036
1037 for (auto &Item : RelocateInstMap)
1038 // Item.first is the RelocatedBase to offset against
1039 // Item.second is the vector of Targets to replace
1040 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1041 return MadeChange;
1042}
1043
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001044/// SinkCast - Sink the specified cast instruction into its user blocks
1045static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001046 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001047
Chris Lattnerf2836d12007-03-31 04:06:36 +00001048 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001049 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001050
Chris Lattnerf2836d12007-03-31 04:06:36 +00001051 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001052 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001053 UI != E; ) {
1054 Use &TheUse = UI.getUse();
1055 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001056
Chris Lattnerf2836d12007-03-31 04:06:36 +00001057 // Figure out which BB this cast is used in. For PHI's this is the
1058 // appropriate predecessor block.
1059 BasicBlock *UserBB = User->getParent();
1060 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001061 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001062 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001063
Chris Lattnerf2836d12007-03-31 04:06:36 +00001064 // Preincrement use iterator so we don't invalidate it.
1065 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001066
David Majnemer0c80e2e2016-04-27 19:36:38 +00001067 // The first insertion point of a block containing an EH pad is after the
1068 // pad. If the pad is the user, we cannot sink the cast past the pad.
1069 if (User->isEHPad())
1070 continue;
1071
Andrew Kaylord0430e82015-11-23 19:16:15 +00001072 // If the block selected to receive the cast is an EH pad that does not
1073 // allow non-PHI instructions before the terminator, we can't sink the
1074 // cast.
1075 if (UserBB->getTerminator()->isEHPad())
1076 continue;
1077
Chris Lattnerf2836d12007-03-31 04:06:36 +00001078 // If this user is in the same block as the cast, don't change the cast.
1079 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001080
Chris Lattnerf2836d12007-03-31 04:06:36 +00001081 // If we have already inserted a cast into this block, use it.
1082 CastInst *&InsertedCast = InsertedCasts[UserBB];
1083
1084 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001085 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001086 assert(InsertPt != UserBB->end());
1087 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1088 CI->getType(), "", &*InsertPt);
Vedant Kumar9374c042018-05-23 22:03:48 +00001089 InsertedCast->setDebugLoc(CI->getDebugLoc());
Chris Lattnerf2836d12007-03-31 04:06:36 +00001090 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001091
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001092 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001093 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001094 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001095 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001096 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001097
Chris Lattnerf2836d12007-03-31 04:06:36 +00001098 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001099 if (CI->use_empty()) {
Adrian Prantl261ac8b2017-11-03 21:55:03 +00001100 salvageDebugInfo(*CI);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001101 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001102 MadeChange = true;
1103 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001104
Chris Lattnerf2836d12007-03-31 04:06:36 +00001105 return MadeChange;
1106}
1107
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001108/// If the specified cast instruction is a noop copy (e.g. it's casting from
1109/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1110/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001111///
1112/// Return true if any changes are made.
Mehdi Amini44ede332015-07-09 02:09:04 +00001113static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1114 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001115 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1116 // than sinking only nop casts, but is helpful on some platforms.
1117 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1118 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1119 ASC->getDestAddressSpace()))
1120 return false;
1121 }
1122
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001123 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001124 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1125 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001126
1127 // This is an fp<->int conversion?
1128 if (SrcVT.isInteger() != DstVT.isInteger())
1129 return false;
1130
1131 // If this is an extension, it will be a zero or sign extension, which
1132 // isn't a noop.
1133 if (SrcVT.bitsLT(DstVT)) return false;
1134
1135 // If these values will be promoted, find out what they will be promoted
1136 // to. This helps us consider truncates on PPC as noop copies when they
1137 // are.
1138 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1139 TargetLowering::TypePromoteInteger)
1140 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1141 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1142 TargetLowering::TypePromoteInteger)
1143 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1144
1145 // If, after promotion, these are the same types, this is a noop copy.
1146 if (SrcVT != DstVT)
1147 return false;
1148
1149 return SinkCast(CI);
1150}
1151
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001152static void replaceMathCmpWithIntrinsic(BinaryOperator *BO, CmpInst *Cmp,
1153 Instruction *InsertPt,
1154 Intrinsic::ID IID) {
1155 IRBuilder<> Builder(InsertPt);
1156 Value *MathOV = Builder.CreateBinaryIntrinsic(IID, BO->getOperand(0),
1157 BO->getOperand(1));
1158 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
1159 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
1160 BO->replaceAllUsesWith(Math);
1161 Cmp->replaceAllUsesWith(OV);
1162 BO->eraseFromParent();
1163 Cmp->eraseFromParent();
1164}
1165
Sanjay Patel00fcc742019-02-03 13:48:03 +00001166/// Try to combine the compare into a call to the llvm.uadd.with.overflow
1167/// intrinsic. Return true if any changes were made.
Sanjay Patel84ceae62019-02-03 17:53:09 +00001168static bool combineToUAddWithOverflow(CmpInst *Cmp, const TargetLowering &TLI,
1169 const DataLayout &DL) {
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001170 Value *A, *B;
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001171 BinaryOperator *Add;
1172 if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add))))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001173 return false;
1174
Sanjay Patel84ceae62019-02-03 17:53:09 +00001175 // Allow the transform as long as we have an integer type that is not
1176 // obviously illegal and unsupported.
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001177 Type *Ty = Add->getType();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001178 if (!isa<IntegerType>(Ty))
1179 return false;
Sanjay Patel84ceae62019-02-03 17:53:09 +00001180 EVT CodegenVT = TLI.getValueType(DL, Ty);
1181 if (!CodegenVT.isSimple() && TLI.isOperationExpand(ISD::UADDO, CodegenVT))
1182 return false;
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001183
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001184 // We don't want to move around uses of condition values this late, so we
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001185 // check if it is legal to create the call to the intrinsic in the basic
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001186 // block containing the icmp.
1187 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001188 return false;
1189
1190#ifndef NDEBUG
1191 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1192 // for now:
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001193 if (Add->hasOneUse())
1194 assert(*Add->user_begin() == Cmp && "expected!");
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001195#endif
1196
Sanjay Patelc00bdab42019-02-04 16:30:46 +00001197 Instruction *InPt = Add->hasOneUse() ? cast<Instruction>(Cmp)
1198 : cast<Instruction>(Add);
1199 replaceMathCmpWithIntrinsic(Add, Cmp, InPt, Intrinsic::uadd_with_overflow);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001200 return true;
1201}
1202
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001203/// Sink the given CmpInst into user blocks to reduce the number of virtual
1204/// registers that must be created and coalesced. This is a clear win except on
1205/// targets with multiple condition code registers (PowerPC), where it might
1206/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001207///
1208/// Return true if any changes are made.
Sanjay Patel00fcc742019-02-03 13:48:03 +00001209static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI) {
1210 if (TLI.hasMultipleConditionRegisters())
1211 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001212
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001213 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Sanjay Patel00fcc742019-02-03 13:48:03 +00001214 if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001215 return false;
1216
1217 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001218 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001219
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001220 bool MadeChange = false;
Sanjay Patel00fcc742019-02-03 13:48:03 +00001221 for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001222 UI != E; ) {
1223 Use &TheUse = UI.getUse();
1224 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001225
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001226 // Preincrement use iterator so we don't invalidate it.
1227 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001228
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001229 // Don't bother for PHI nodes.
1230 if (isa<PHINode>(User))
1231 continue;
1232
1233 // Figure out which BB this cmp is used in.
1234 BasicBlock *UserBB = User->getParent();
Sanjay Patel00fcc742019-02-03 13:48:03 +00001235 BasicBlock *DefBB = Cmp->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001236
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001237 // If this user is in the same block as the cmp, don't change the cmp.
1238 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001239
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001240 // If we have already inserted a cmp into this block, use it.
1241 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1242
1243 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001244 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001245 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001246 InsertedCmp =
Sanjay Patel00fcc742019-02-03 13:48:03 +00001247 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(),
1248 Cmp->getOperand(0), Cmp->getOperand(1), "",
1249 &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001250 // Propagate the debug info.
Sanjay Patel00fcc742019-02-03 13:48:03 +00001251 InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001252 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001253
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001254 // Replace a use of the cmp with a use of the new cmp.
1255 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001256 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001257 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001258 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001259
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001260 // If we removed all uses, nuke the cmp.
Sanjay Patel00fcc742019-02-03 13:48:03 +00001261 if (Cmp->use_empty()) {
1262 Cmp->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001263 MadeChange = true;
1264 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001265
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001266 return MadeChange;
1267}
1268
Sanjay Patel84ceae62019-02-03 17:53:09 +00001269static bool optimizeCmpExpression(CmpInst *Cmp, const TargetLowering &TLI,
1270 const DataLayout &DL) {
Sanjay Patel00fcc742019-02-03 13:48:03 +00001271 if (sinkCmpExpression(Cmp, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001272 return true;
1273
Sanjay Patel84ceae62019-02-03 17:53:09 +00001274 if (combineToUAddWithOverflow(Cmp, TLI, DL))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001275 return true;
1276
1277 return false;
1278}
1279
Geoff Berry5d534b62017-02-21 18:53:14 +00001280/// Duplicate and sink the given 'and' instruction into user blocks where it is
1281/// used in a compare to allow isel to generate better code for targets where
1282/// this operation can be combined.
1283///
1284/// Return true if any changes are made.
1285static bool sinkAndCmp0Expression(Instruction *AndI,
1286 const TargetLowering &TLI,
1287 SetOfInstrs &InsertedInsts) {
1288 // Double-check that we're not trying to optimize an instruction that was
1289 // already optimized by some other part of this pass.
1290 assert(!InsertedInsts.count(AndI) &&
1291 "Attempting to optimize already optimized and instruction");
1292 (void) InsertedInsts;
1293
1294 // Nothing to do for single use in same basic block.
1295 if (AndI->hasOneUse() &&
1296 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1297 return false;
1298
1299 // Try to avoid cases where sinking/duplicating is likely to increase register
1300 // pressure.
1301 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1302 !isa<ConstantInt>(AndI->getOperand(1)) &&
1303 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1304 return false;
1305
1306 for (auto *U : AndI->users()) {
1307 Instruction *User = cast<Instruction>(U);
1308
1309 // Only sink for and mask feeding icmp with 0.
1310 if (!isa<ICmpInst>(User))
1311 return false;
1312
1313 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1314 if (!CmpC || !CmpC->isZero())
1315 return false;
1316 }
1317
1318 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1319 return false;
1320
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001321 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1322 LLVM_DEBUG(AndI->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001323
1324 // Push the 'and' into the same block as the icmp 0. There should only be
1325 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1326 // others, so we don't need to keep track of which BBs we insert into.
1327 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1328 UI != E; ) {
1329 Use &TheUse = UI.getUse();
1330 Instruction *User = cast<Instruction>(*UI);
1331
1332 // Preincrement use iterator so we don't invalidate it.
1333 ++UI;
1334
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001335 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
Geoff Berry5d534b62017-02-21 18:53:14 +00001336
1337 // Keep the 'and' in the same place if the use is already in the same block.
1338 Instruction *InsertPt =
1339 User->getParent() == AndI->getParent() ? AndI : User;
1340 Instruction *InsertedAnd =
1341 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1342 AndI->getOperand(1), "", InsertPt);
1343 // Propagate the debug info.
1344 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1345
1346 // Replace a use of the 'and' with a use of the new 'and'.
1347 TheUse = InsertedAnd;
1348 ++NumAndUses;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001349 LLVM_DEBUG(User->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001350 }
1351
1352 // We removed all uses, nuke the and.
1353 AndI->eraseFromParent();
1354 return true;
1355}
1356
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001357/// Check if the candidates could be combined with a shift instruction, which
1358/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001359/// 1. Truncate instruction
1360/// 2. And instruction and the imm is a mask of the low bits:
1361/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001362static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001363 if (!isa<TruncInst>(User)) {
1364 if (User->getOpcode() != Instruction::And ||
1365 !isa<ConstantInt>(User->getOperand(1)))
1366 return false;
1367
Quentin Colombetd4f44692014-04-22 01:20:34 +00001368 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001369
Quentin Colombetd4f44692014-04-22 01:20:34 +00001370 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001371 return false;
1372 }
1373 return true;
1374}
1375
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001376/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001377static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001378SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1379 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001380 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001381 BasicBlock *UserBB = User->getParent();
1382 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1383 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1384 bool MadeChange = false;
1385
1386 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1387 TruncE = TruncI->user_end();
1388 TruncUI != TruncE;) {
1389
1390 Use &TruncTheUse = TruncUI.getUse();
1391 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1392 // Preincrement use iterator so we don't invalidate it.
1393
1394 ++TruncUI;
1395
1396 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1397 if (!ISDOpcode)
1398 continue;
1399
Tim Northovere2239ff2014-07-29 10:20:22 +00001400 // If the use is actually a legal node, there will not be an
1401 // implicit truncate.
1402 // FIXME: always querying the result type is just an
1403 // approximation; some nodes' legality is determined by the
1404 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001405 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001406 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001407 continue;
1408
1409 // Don't bother for PHI nodes.
1410 if (isa<PHINode>(TruncUser))
1411 continue;
1412
1413 BasicBlock *TruncUserBB = TruncUser->getParent();
1414
1415 if (UserBB == TruncUserBB)
1416 continue;
1417
1418 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1419 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1420
1421 if (!InsertedShift && !InsertedTrunc) {
1422 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001423 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001424 // Sink the shift
1425 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001426 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1427 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001428 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001429 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1430 "", &*InsertPt);
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001431 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
Yi Jiangd069f632014-04-21 19:34:27 +00001432
1433 // Sink the trunc
1434 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1435 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001436 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001437
1438 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001439 TruncI->getType(), "", &*TruncInsertPt);
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001440 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
Yi Jiangd069f632014-04-21 19:34:27 +00001441
1442 MadeChange = true;
1443
1444 TruncTheUse = InsertedTrunc;
1445 }
1446 }
1447 return MadeChange;
1448}
1449
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001450/// Sink the shift *right* instruction into user blocks if the uses could
1451/// potentially be combined with this shift instruction and generate BitExtract
1452/// instruction. It will only be applied if the architecture supports BitExtract
1453/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001454/// BB1:
1455/// %x.extract.shift = lshr i64 %arg1, 32
1456/// BB2:
1457/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1458/// ==>
1459///
1460/// BB2:
1461/// %x.extract.shift.1 = lshr i64 %arg1, 32
1462/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1463///
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001464/// CodeGen will recognize the pattern in BB2 and generate BitExtract
Yi Jiangd069f632014-04-21 19:34:27 +00001465/// instruction.
1466/// Return true if any changes are made.
1467static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001468 const TargetLowering &TLI,
1469 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001470 BasicBlock *DefBB = ShiftI->getParent();
1471
1472 /// Only insert instructions in each block once.
1473 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1474
Mehdi Amini44ede332015-07-09 02:09:04 +00001475 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001476
1477 bool MadeChange = false;
1478 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1479 UI != E;) {
1480 Use &TheUse = UI.getUse();
1481 Instruction *User = cast<Instruction>(*UI);
1482 // Preincrement use iterator so we don't invalidate it.
1483 ++UI;
1484
1485 // Don't bother for PHI nodes.
1486 if (isa<PHINode>(User))
1487 continue;
1488
1489 if (!isExtractBitsCandidateUse(User))
1490 continue;
1491
1492 BasicBlock *UserBB = User->getParent();
1493
1494 if (UserBB == DefBB) {
1495 // If the shift and truncate instruction are in the same BB. The use of
1496 // the truncate(TruncUse) may still introduce another truncate if not
1497 // legal. In this case, we would like to sink both shift and truncate
1498 // instruction to the BB of TruncUse.
1499 // for example:
1500 // BB1:
1501 // i64 shift.result = lshr i64 opnd, imm
1502 // trunc.result = trunc shift.result to i16
1503 //
1504 // BB2:
1505 // ----> We will have an implicit truncate here if the architecture does
1506 // not have i16 compare.
1507 // cmp i16 trunc.result, opnd2
1508 //
1509 if (isa<TruncInst>(User) && shiftIsLegal
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001510 // If the type of the truncate is legal, no truncate will be
Yi Jiangd069f632014-04-21 19:34:27 +00001511 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001512 &&
1513 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001514 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001515 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001516
1517 continue;
1518 }
1519 // If we have already inserted a shift into this block, use it.
1520 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1521
1522 if (!InsertedShift) {
1523 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001524 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001525
1526 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001527 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1528 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001529 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001530 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1531 "", &*InsertPt);
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001532 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
Yi Jiangd069f632014-04-21 19:34:27 +00001533
1534 MadeChange = true;
1535 }
1536
1537 // Replace a use of the shift with a use of the new shift.
1538 TheUse = InsertedShift;
1539 }
1540
1541 // If we removed all uses, nuke the shift.
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001542 if (ShiftI->use_empty()) {
1543 salvageDebugInfo(*ShiftI);
Yi Jiangd069f632014-04-21 19:34:27 +00001544 ShiftI->eraseFromParent();
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001545 }
Yi Jiangd069f632014-04-21 19:34:27 +00001546
1547 return MadeChange;
1548}
1549
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001550/// If counting leading or trailing zeros is an expensive operation and a zero
1551/// input is defined, add a check for zero to avoid calling the intrinsic.
1552///
1553/// We want to transform:
1554/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1555///
1556/// into:
1557/// entry:
1558/// %cmpz = icmp eq i64 %A, 0
1559/// br i1 %cmpz, label %cond.end, label %cond.false
1560/// cond.false:
1561/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1562/// br label %cond.end
1563/// cond.end:
1564/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1565///
1566/// If the transform is performed, return true and set ModifiedDT to true.
1567static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1568 const TargetLowering *TLI,
1569 const DataLayout *DL,
1570 bool &ModifiedDT) {
1571 if (!TLI || !DL)
1572 return false;
1573
1574 // If a zero input is undefined, it doesn't make sense to despeculate that.
1575 if (match(CountZeros->getOperand(1), m_One()))
1576 return false;
1577
1578 // If it's cheap to speculate, there's nothing to do.
1579 auto IntrinsicID = CountZeros->getIntrinsicID();
1580 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1581 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1582 return false;
1583
1584 // Only handle legal scalar cases. Anything else requires too much work.
1585 Type *Ty = CountZeros->getType();
1586 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001587 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001588 return false;
1589
1590 // The intrinsic will be sunk behind a compare against zero and branch.
1591 BasicBlock *StartBlock = CountZeros->getParent();
1592 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1593
1594 // Create another block after the count zero intrinsic. A PHI will be added
1595 // in this block to select the result of the intrinsic or the bit-width
1596 // constant if the input to the intrinsic is zero.
1597 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1598 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1599
1600 // Set up a builder to create a compare, conditional branch, and PHI.
1601 IRBuilder<> Builder(CountZeros->getContext());
1602 Builder.SetInsertPoint(StartBlock->getTerminator());
1603 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1604
1605 // Replace the unconditional branch that was created by the first split with
1606 // a compare against zero and a conditional branch.
1607 Value *Zero = Constant::getNullValue(Ty);
1608 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1609 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1610 StartBlock->getTerminator()->eraseFromParent();
1611
1612 // Create a PHI in the end block to select either the output of the intrinsic
1613 // or the bit width of the operand.
1614 Builder.SetInsertPoint(&EndBlock->front());
1615 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1616 CountZeros->replaceAllUsesWith(PN);
1617 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1618 PN->addIncoming(BitWidth, StartBlock);
1619 PN->addIncoming(CountZeros, CallBlock);
1620
1621 // We are explicitly handling the zero case, so we can set the intrinsic's
1622 // undefined zero argument to 'true'. This will also prevent reprocessing the
1623 // intrinsic; we only despeculate when a zero input is defined.
1624 CountZeros->setArgOperand(1, Builder.getTrue());
1625 ModifiedDT = true;
1626 return true;
1627}
1628
Sanjay Patel3b8974b2017-06-08 20:00:09 +00001629bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001630 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001631
Chris Lattner7a277142011-01-15 07:14:54 +00001632 // Lower inline assembly if we can.
1633 // If we found an inline asm expession, and if the target knows how to
1634 // lower it to normal LLVM code, do so now.
1635 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1636 if (TLI->ExpandInlineAsm(CI)) {
1637 // Avoid invalidating the iterator.
1638 CurInstIterator = BB->begin();
1639 // Avoid processing instructions out of order, which could cause
1640 // reuse before a value is defined.
1641 SunkAddrs.clear();
1642 return true;
1643 }
1644 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001645 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001646 return true;
1647 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001648
John Brawn0dbcd652015-03-18 12:01:59 +00001649 // Align the pointer arguments to this call if the target thinks it's a good
1650 // idea
1651 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001652 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001653 for (auto &Arg : CI->arg_operands()) {
1654 // We want to align both objects whose address is used directly and
1655 // objects whose address is used in casts and GEPs, though it only makes
1656 // sense for GEPs if the offset is a multiple of the desired alignment and
1657 // if size - offset meets the size threshold.
1658 if (!Arg->getType()->isPointerTy())
1659 continue;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001660 APInt Offset(DL->getIndexSizeInBits(
Mehdi Amini4fe37982015-07-07 18:45:17 +00001661 cast<PointerType>(Arg->getType())->getAddressSpace()),
1662 0);
1663 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001664 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001665 if ((Offset2 & (PrefAlign-1)) != 0)
1666 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001667 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001668 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1669 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001670 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001671 // Global variables can only be aligned if they are defined in this
1672 // object (i.e. they are uniquely initialized in this object), and
1673 // over-aligning global variables that have an explicit section is
1674 // forbidden.
1675 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001676 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001677 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001678 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001679 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001680 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001681 }
1682 // If this is a memcpy (or similar) then we may be able to improve the
1683 // alignment
1684 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Daniel Neilsonbe58a222018-01-31 17:24:53 +00001685 unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
1686 if (DestAlign > MI->getDestAlignment())
1687 MI->setDestAlignment(DestAlign);
1688 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1689 unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
1690 if (SrcAlign > MTI->getSourceAlignment())
1691 MTI->setSourceAlignment(SrcAlign);
1692 }
John Brawn0dbcd652015-03-18 12:01:59 +00001693 }
1694 }
1695
Philip Reamesac115ed2016-03-09 23:13:12 +00001696 // If we have a cold call site, try to sink addressing computation into the
1697 // cold block. This interacts with our handling for loads and stores to
1698 // ensure that we can fold all uses of a potential addressing computation
1699 // into their uses. TODO: generalize this to work over profiling data
1700 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1701 for (auto &Arg : CI->arg_operands()) {
1702 if (!Arg->getType()->isPointerTy())
1703 continue;
1704 unsigned AS = Arg->getType()->getPointerAddressSpace();
1705 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1706 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001707
Eric Christopher4b7948e2010-03-11 02:41:03 +00001708 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001709 if (II) {
1710 switch (II->getIntrinsicID()) {
1711 default: break;
Philip Reamesede49dd2019-01-31 18:45:46 +00001712 case Intrinsic::experimental_widenable_condition: {
1713 // Give up on future widening oppurtunties so that we can fold away dead
1714 // paths and merge blocks before going into block-local instruction
1715 // selection.
1716 if (II->use_empty()) {
1717 II->eraseFromParent();
1718 return true;
1719 }
1720 Constant *RetVal = ConstantInt::getTrue(II->getContext());
1721 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1722 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1723 });
1724 return true;
1725 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001726 case Intrinsic::objectsize: {
1727 // Lower all uses of llvm.objectsize.*
Erik Pilkington600e9de2019-01-30 20:34:35 +00001728 Value *RetVal =
George Burgess IV3f089142016-12-20 23:46:36 +00001729 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Nadav Rotem465834c2012-07-24 10:51:42 +00001730
James Y Knight72f76bf2018-11-07 15:24:12 +00001731 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1732 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1733 });
1734 return true;
1735 }
1736 case Intrinsic::is_constant: {
1737 // If is_constant hasn't folded away yet, lower it to false now.
1738 Constant *RetVal = ConstantInt::get(II->getType(), 0);
1739 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1740 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1741 });
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001742 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001743 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001744 case Intrinsic::aarch64_stlxr:
1745 case Intrinsic::aarch64_stxr: {
1746 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1747 if (!ExtVal || !ExtVal->hasOneUse() ||
1748 ExtVal->getParent() == CI->getParent())
1749 return false;
1750 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1751 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001752 // Mark this instruction as "inserted by CGP", so that other
1753 // optimizations don't touch it.
1754 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001755 return true;
1756 }
Florian Hahn3b251962019-02-05 10:27:40 +00001757
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001758 case Intrinsic::launder_invariant_group:
Krzysztof Pszeniczny2bfe7592018-10-19 19:02:16 +00001759 case Intrinsic::strip_invariant_group: {
1760 Value *ArgVal = II->getArgOperand(0);
1761 auto it = LargeOffsetGEPMap.find(II);
1762 if (it != LargeOffsetGEPMap.end()) {
1763 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
1764 // Make sure not to have to deal with iterator invalidation
1765 // after possibly adding ArgVal to LargeOffsetGEPMap.
1766 auto GEPs = std::move(it->second);
1767 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
1768 LargeOffsetGEPMap.erase(II);
1769 }
1770
1771 II->replaceAllUsesWith(ArgVal);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001772 II->eraseFromParent();
1773 return true;
Krzysztof Pszeniczny2bfe7592018-10-19 19:02:16 +00001774 }
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001775 case Intrinsic::cttz:
1776 case Intrinsic::ctlz:
1777 // If counting zeros is expensive, try to avoid it.
1778 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001779 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001780
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001781 if (TLI) {
1782 SmallVector<Value*, 2> PtrOps;
1783 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001784 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1785 while (!PtrOps.empty()) {
1786 Value *PtrVal = PtrOps.pop_back_val();
1787 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1788 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001789 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001790 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001791 }
Pete Cooper615fd892012-03-13 20:59:56 +00001792 }
1793
Eric Christopher4b7948e2010-03-11 02:41:03 +00001794 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001795 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001796
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001797 // Lower all default uses of _chk calls. This is very similar
1798 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001799 // to fortified library functions (e.g. __memcpy_chk) that have the default
1800 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001801 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001802 if (Value *V = Simplifier.optimizeCall(CI)) {
1803 CI->replaceAllUsesWith(V);
1804 CI->eraseFromParent();
1805 return true;
1806 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001807
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001808 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001809}
Chris Lattner1b93be52011-01-15 07:25:29 +00001810
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001811/// Look for opportunities to duplicate return instructions to the predecessor
1812/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001813/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001814/// bb0:
1815/// %tmp0 = tail call i32 @f0()
1816/// br label %return
1817/// bb1:
1818/// %tmp1 = tail call i32 @f1()
1819/// br label %return
1820/// bb2:
1821/// %tmp2 = tail call i32 @f2()
1822/// br label %return
1823/// return:
1824/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1825/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001826/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001827///
1828/// =>
1829///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001830/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001831/// bb0:
1832/// %tmp0 = tail call i32 @f0()
1833/// ret i32 %tmp0
1834/// bb1:
1835/// %tmp1 = tail call i32 @f1()
1836/// ret i32 %tmp1
1837/// bb2:
1838/// %tmp2 = tail call i32 @f2()
1839/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001840/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001841bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001842 if (!TLI)
1843 return false;
1844
Michael Kuperstein71321562016-09-07 20:29:49 +00001845 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1846 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001847 return false;
1848
Craig Topperc0196b12014-04-14 00:51:57 +00001849 PHINode *PN = nullptr;
1850 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001851 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001852 if (V) {
1853 BCI = dyn_cast<BitCastInst>(V);
1854 if (BCI)
1855 V = BCI->getOperand(0);
1856
1857 PN = dyn_cast<PHINode>(V);
1858 if (!PN)
1859 return false;
1860 }
Evan Cheng0663f232011-03-21 01:19:09 +00001861
Cameron Zwarich4649f172011-03-24 04:52:10 +00001862 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001863 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001864
Cameron Zwarich4649f172011-03-24 04:52:10 +00001865 // Make sure there are no instructions between the PHI and return, or that the
1866 // return is the first instruction in the block.
1867 if (PN) {
1868 BasicBlock::iterator BI = BB->begin();
Jonas Paulsson5ed4d462019-01-29 09:03:35 +00001869 // Skip over debug and the bitcast.
1870 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI) || &*BI == BCI);
Michael Kuperstein71321562016-09-07 20:29:49 +00001871 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001872 return false;
1873 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001874 BasicBlock::iterator BI = BB->begin();
1875 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001876 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001877 return false;
1878 }
Evan Cheng0663f232011-03-21 01:19:09 +00001879
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001880 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1881 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001882 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001883 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001884 if (PN) {
1885 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1886 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1887 // Make sure the phi value is indeed produced by the tail call.
1888 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001889 TLI->mayBeEmittedAsTailCall(CI) &&
1890 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001891 TailCalls.push_back(CI);
1892 }
1893 } else {
1894 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001895 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001896 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001897 continue;
1898
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001899 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001900 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1901 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001902 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1903 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001904 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001905
Cameron Zwarich4649f172011-03-24 04:52:10 +00001906 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001907 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1908 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001909 TailCalls.push_back(CI);
1910 }
Evan Cheng0663f232011-03-21 01:19:09 +00001911 }
1912
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001913 bool Changed = false;
1914 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1915 CallInst *CI = TailCalls[i];
1916 CallSite CS(CI);
1917
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001918 // Make sure the call instruction is followed by an unconditional branch to
1919 // the return block.
1920 BasicBlock *CallBB = CI->getParent();
1921 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1922 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1923 continue;
1924
1925 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00001926 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001927 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001928 ++NumRetsDup;
1929 }
1930
1931 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001932 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001933 BB->eraseFromParent();
1934
1935 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001936}
1937
Chris Lattner728f9022008-11-25 07:09:13 +00001938//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001939// Memory Optimization
1940//===----------------------------------------------------------------------===//
1941
Chandler Carruthc8925912013-01-05 02:09:22 +00001942namespace {
1943
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001944/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00001945/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001946struct ExtAddrMode : public TargetLowering::AddrMode {
Eugene Zelenko900b6332017-08-29 22:32:07 +00001947 Value *BaseReg = nullptr;
1948 Value *ScaledReg = nullptr;
John Brawn736bf002017-10-03 13:08:22 +00001949 Value *OriginalValue = nullptr;
1950
1951 enum FieldName {
1952 NoField = 0x00,
1953 BaseRegField = 0x01,
1954 BaseGVField = 0x02,
1955 BaseOffsField = 0x04,
1956 ScaledRegField = 0x08,
1957 ScaleField = 0x10,
1958 MultipleFields = 0xff
1959 };
Eugene Zelenko900b6332017-08-29 22:32:07 +00001960
1961 ExtAddrMode() = default;
1962
Chandler Carruthc8925912013-01-05 02:09:22 +00001963 void print(raw_ostream &OS) const;
1964 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001965
John Brawn736bf002017-10-03 13:08:22 +00001966 FieldName compare(const ExtAddrMode &other) {
1967 // First check that the types are the same on each field, as differing types
1968 // is something we can't cope with later on.
1969 if (BaseReg && other.BaseReg &&
1970 BaseReg->getType() != other.BaseReg->getType())
1971 return MultipleFields;
1972 if (BaseGV && other.BaseGV &&
1973 BaseGV->getType() != other.BaseGV->getType())
1974 return MultipleFields;
1975 if (ScaledReg && other.ScaledReg &&
1976 ScaledReg->getType() != other.ScaledReg->getType())
1977 return MultipleFields;
1978
1979 // Check each field to see if it differs.
1980 unsigned Result = NoField;
1981 if (BaseReg != other.BaseReg)
1982 Result |= BaseRegField;
1983 if (BaseGV != other.BaseGV)
1984 Result |= BaseGVField;
1985 if (BaseOffs != other.BaseOffs)
1986 Result |= BaseOffsField;
1987 if (ScaledReg != other.ScaledReg)
1988 Result |= ScaledRegField;
1989 // Don't count 0 as being a different scale, because that actually means
1990 // unscaled (which will already be counted by having no ScaledReg).
1991 if (Scale && other.Scale && Scale != other.Scale)
1992 Result |= ScaleField;
1993
1994 if (countPopulation(Result) > 1)
1995 return MultipleFields;
1996 else
1997 return static_cast<FieldName>(Result);
1998 }
1999
John Brawn4b476482017-11-27 11:29:15 +00002000 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
2001 // with no offset.
John Brawn736bf002017-10-03 13:08:22 +00002002 bool isTrivial() {
John Brawn4b476482017-11-27 11:29:15 +00002003 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
2004 // trivial if at most one of these terms is nonzero, except that BaseGV and
2005 // BaseReg both being zero actually means a null pointer value, which we
2006 // consider to be 'non-zero' here.
2007 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
Chandler Carruthc8925912013-01-05 02:09:22 +00002008 }
John Brawn70cdb5b2017-11-24 14:10:45 +00002009
2010 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
2011 switch (Field) {
2012 default:
2013 return nullptr;
2014 case BaseRegField:
2015 return BaseReg;
2016 case BaseGVField:
2017 return BaseGV;
2018 case ScaledRegField:
2019 return ScaledReg;
2020 case BaseOffsField:
2021 return ConstantInt::get(IntPtrTy, BaseOffs);
2022 }
2023 }
2024
2025 void SetCombinedField(FieldName Field, Value *V,
2026 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
2027 switch (Field) {
2028 default:
2029 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
2030 break;
2031 case ExtAddrMode::BaseRegField:
2032 BaseReg = V;
2033 break;
2034 case ExtAddrMode::BaseGVField:
2035 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
2036 // in the BaseReg field.
2037 assert(BaseReg == nullptr);
2038 BaseReg = V;
2039 BaseGV = nullptr;
2040 break;
2041 case ExtAddrMode::ScaledRegField:
2042 ScaledReg = V;
2043 // If we have a mix of scaled and unscaled addrmodes then we want scale
2044 // to be the scale and not zero.
2045 if (!Scale)
2046 for (const ExtAddrMode &AM : AddrModes)
2047 if (AM.Scale) {
2048 Scale = AM.Scale;
2049 break;
2050 }
2051 break;
2052 case ExtAddrMode::BaseOffsField:
2053 // The offset is no longer a constant, so it goes in ScaledReg with a
2054 // scale of 1.
2055 assert(ScaledReg == nullptr);
2056 ScaledReg = V;
2057 Scale = 1;
2058 BaseOffs = 0;
2059 break;
2060 }
2061 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002062};
2063
Eugene Zelenko900b6332017-08-29 22:32:07 +00002064} // end anonymous namespace
2065
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002066#ifndef NDEBUG
2067static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2068 AM.print(OS);
2069 return OS;
2070}
2071#endif
2072
Aaron Ballman615eb472017-10-15 14:32:27 +00002073#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthc8925912013-01-05 02:09:22 +00002074void ExtAddrMode::print(raw_ostream &OS) const {
2075 bool NeedPlus = false;
2076 OS << "[";
2077 if (BaseGV) {
2078 OS << (NeedPlus ? " + " : "")
2079 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002080 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002081 NeedPlus = true;
2082 }
2083
Richard Trieuc0f91212014-05-30 03:15:17 +00002084 if (BaseOffs) {
2085 OS << (NeedPlus ? " + " : "")
2086 << BaseOffs;
2087 NeedPlus = true;
2088 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002089
2090 if (BaseReg) {
2091 OS << (NeedPlus ? " + " : "")
2092 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002093 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002094 NeedPlus = true;
2095 }
2096 if (Scale) {
2097 OS << (NeedPlus ? " + " : "")
2098 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002099 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002100 }
2101
2102 OS << ']';
2103}
2104
Yaron Kereneb2a2542016-01-29 20:50:44 +00002105LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002106 print(dbgs());
2107 dbgs() << '\n';
2108}
2109#endif
2110
Eugene Zelenko900b6332017-08-29 22:32:07 +00002111namespace {
2112
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002113/// This class provides transaction based operation on the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002114/// Every change made through this class is recorded in the internal state and
2115/// can be undone (rollback) until commit is called.
2116class TypePromotionTransaction {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002117 /// This represents the common interface of the individual transaction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002118 /// Each class implements the logic for doing one specific modification on
2119 /// the IR via the TypePromotionTransaction.
2120 class TypePromotionAction {
2121 protected:
2122 /// The Instruction modified.
2123 Instruction *Inst;
2124
2125 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002126 /// Constructor of the action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002127 /// The constructor performs the related action on the IR.
2128 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2129
Eugene Zelenko900b6332017-08-29 22:32:07 +00002130 virtual ~TypePromotionAction() = default;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002131
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002132 /// Undo the modification done by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002133 /// When this method is called, the IR must be in the same state as it was
2134 /// before this action was applied.
2135 /// \pre Undoing the action works if and only if the IR is in the exact same
2136 /// state as it was directly after this action was applied.
2137 virtual void undo() = 0;
2138
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002139 /// Advocate every change made by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002140 /// When the results on the IR of the action are to be kept, it is important
2141 /// to call this function, otherwise hidden information may be kept forever.
2142 virtual void commit() {
2143 // Nothing to be done, this action is not doing anything.
2144 }
2145 };
2146
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002147 /// Utility to remember the position of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002148 class InsertionHandler {
2149 /// Position of an instruction.
2150 /// Either an instruction:
2151 /// - Is the first in a basic block: BB is used.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002152 /// - Has a previous instruction: PrevInst is used.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002153 union {
2154 Instruction *PrevInst;
2155 BasicBlock *BB;
2156 } Point;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002157
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002158 /// Remember whether or not the instruction had a previous instruction.
2159 bool HasPrevInstruction;
2160
2161 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002162 /// Record the position of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002163 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002164 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002165 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2166 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002167 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002168 else
2169 Point.BB = Inst->getParent();
2170 }
2171
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002172 /// Insert \p Inst at the recorded position.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002173 void insert(Instruction *Inst) {
2174 if (HasPrevInstruction) {
2175 if (Inst->getParent())
2176 Inst->removeFromParent();
2177 Inst->insertAfter(Point.PrevInst);
2178 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002179 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002180 if (Inst->getParent())
2181 Inst->moveBefore(Position);
2182 else
2183 Inst->insertBefore(Position);
2184 }
2185 }
2186 };
2187
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002188 /// Move an instruction before another.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002189 class InstructionMoveBefore : public TypePromotionAction {
2190 /// Original position of the instruction.
2191 InsertionHandler Position;
2192
2193 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002194 /// Move \p Inst before \p Before.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002195 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2196 : TypePromotionAction(Inst), Position(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002197 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
2198 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002199 Inst->moveBefore(Before);
2200 }
2201
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002202 /// Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002203 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002204 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002205 Position.insert(Inst);
2206 }
2207 };
2208
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002209 /// Set the operand of an instruction with a new value.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002210 class OperandSetter : public TypePromotionAction {
2211 /// Original operand of the instruction.
2212 Value *Origin;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002213
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002214 /// Index of the modified instruction.
2215 unsigned Idx;
2216
2217 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002218 /// Set \p Idx operand of \p Inst with \p NewVal.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002219 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2220 : TypePromotionAction(Inst), Idx(Idx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002221 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2222 << "for:" << *Inst << "\n"
2223 << "with:" << *NewVal << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002224 Origin = Inst->getOperand(Idx);
2225 Inst->setOperand(Idx, NewVal);
2226 }
2227
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002228 /// Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002229 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002230 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2231 << "for: " << *Inst << "\n"
2232 << "with: " << *Origin << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002233 Inst->setOperand(Idx, Origin);
2234 }
2235 };
2236
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002237 /// Hide the operands of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002238 /// Do as if this instruction was not using any of its operands.
2239 class OperandsHider : public TypePromotionAction {
2240 /// The list of original operands.
2241 SmallVector<Value *, 4> OriginalValues;
2242
2243 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002244 /// Remove \p Inst from the uses of the operands of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002245 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002246 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002247 unsigned NumOpnds = Inst->getNumOperands();
2248 OriginalValues.reserve(NumOpnds);
2249 for (unsigned It = 0; It < NumOpnds; ++It) {
2250 // Save the current operand.
2251 Value *Val = Inst->getOperand(It);
2252 OriginalValues.push_back(Val);
2253 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002254 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002255 // that we are not willing to pay.
2256 Inst->setOperand(It, UndefValue::get(Val->getType()));
2257 }
2258 }
2259
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002260 /// Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002261 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002262 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002263 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2264 Inst->setOperand(It, OriginalValues[It]);
2265 }
2266 };
2267
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002268 /// Build a truncate instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002269 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002270 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002271
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002272 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002273 /// Build a truncate instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002274 /// result.
2275 /// trunc Opnd to Ty.
2276 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2277 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002278 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002279 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002280 }
2281
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002282 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002283 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002284
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002285 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002286 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002287 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002288 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2289 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002290 }
2291 };
2292
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002293 /// Build a sign extension instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002294 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002295 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002296
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002297 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002298 /// Build a sign extension instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002299 /// result.
2300 /// sext Opnd to Ty.
2301 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002302 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002303 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002304 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002305 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002306 }
2307
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002308 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002309 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002310
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002311 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002312 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002313 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002314 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2315 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002316 }
2317 };
2318
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002319 /// Build a zero extension instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002320 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002321 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002322
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002323 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002324 /// Build a zero extension instruction of \p Opnd producing a \p Ty
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002325 /// result.
2326 /// zext Opnd to Ty.
2327 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002328 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002329 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002330 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002331 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002332 }
2333
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002334 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002335 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002336
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002337 /// Remove the built instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002338 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002339 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002340 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2341 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002342 }
2343 };
2344
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002345 /// Mutate an instruction to another type.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002346 class TypeMutator : public TypePromotionAction {
2347 /// Record the original type.
2348 Type *OrigTy;
2349
2350 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002351 /// Mutate the type of \p Inst into \p NewTy.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002352 TypeMutator(Instruction *Inst, Type *NewTy)
2353 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002354 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2355 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002356 Inst->mutateType(NewTy);
2357 }
2358
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002359 /// Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002360 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002361 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2362 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002363 Inst->mutateType(OrigTy);
2364 }
2365 };
2366
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002367 /// Replace the uses of an instruction by another instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002368 class UsesReplacer : public TypePromotionAction {
2369 /// Helper structure to keep track of the replaced uses.
2370 struct InstructionAndIdx {
2371 /// The instruction using the instruction.
2372 Instruction *Inst;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002373
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002374 /// The index where this instruction is used for Inst.
2375 unsigned Idx;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002376
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002377 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2378 : Inst(Inst), Idx(Idx) {}
2379 };
2380
2381 /// Keep track of the original uses (pair Instruction, Index).
2382 SmallVector<InstructionAndIdx, 4> OriginalUses;
Wolfgang Piebac874c42018-12-11 21:13:53 +00002383 /// Keep track of the debug users.
2384 SmallVector<DbgValueInst *, 1> DbgValues;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002385
2386 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002387
2388 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002389 /// Replace all the use of \p Inst by \p New.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002390 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002391 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2392 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002393 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002394 for (Use &U : Inst->uses()) {
2395 Instruction *UserI = cast<Instruction>(U.getUser());
2396 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002397 }
Wolfgang Piebac874c42018-12-11 21:13:53 +00002398 // Record the debug uses separately. They are not in the instruction's
2399 // use list, but they are replaced by RAUW.
2400 findDbgValues(DbgValues, Inst);
2401
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002402 // Now, we can replace the uses.
2403 Inst->replaceAllUsesWith(New);
2404 }
2405
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002406 /// Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002407 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002408 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002409 for (use_iterator UseIt = OriginalUses.begin(),
2410 EndIt = OriginalUses.end();
2411 UseIt != EndIt; ++UseIt) {
2412 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2413 }
Wolfgang Piebac874c42018-12-11 21:13:53 +00002414 // RAUW has replaced all original uses with references to the new value,
2415 // including the debug uses. Since we are undoing the replacements,
2416 // the original debug uses must also be reinstated to maintain the
2417 // correctness and utility of debug value instructions.
2418 for (auto *DVI: DbgValues) {
2419 LLVMContext &Ctx = Inst->getType()->getContext();
2420 auto *MV = MetadataAsValue::get(Ctx, ValueAsMetadata::get(Inst));
2421 DVI->setOperand(0, MV);
2422 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002423 }
2424 };
2425
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002426 /// Remove an instruction from the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002427 class InstructionRemover : public TypePromotionAction {
2428 /// Original position of the instruction.
2429 InsertionHandler Inserter;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002430
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002431 /// Helper structure to hide all the link to the instruction. In other
2432 /// words, this helps to do as if the instruction was removed.
2433 OperandsHider Hider;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002434
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002435 /// Keep track of the uses replaced, if any.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002436 UsesReplacer *Replacer = nullptr;
2437
Jun Bum Limdee55652017-04-03 19:20:07 +00002438 /// Keep track of instructions removed.
2439 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002440
2441 public:
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002442 /// Remove all reference of \p Inst and optionally replace all its
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002443 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002444 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002445 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002446 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2447 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002448 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Eugene Zelenko900b6332017-08-29 22:32:07 +00002449 RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002450 if (New)
2451 Replacer = new UsesReplacer(Inst, New);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002452 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002453 RemovedInsts.insert(Inst);
2454 /// The instructions removed here will be freed after completing
2455 /// optimizeBlock() for all blocks as we need to keep track of the
2456 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002457 Inst->removeFromParent();
2458 }
2459
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002460 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002461
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002462 /// Resurrect the instruction and reassign it to the proper uses if
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002463 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002464 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002465 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002466 Inserter.insert(Inst);
2467 if (Replacer)
2468 Replacer->undo();
2469 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002470 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002471 }
2472 };
2473
2474public:
2475 /// Restoration point.
2476 /// The restoration point is a pointer to an action instead of an iterator
2477 /// because the iterator may be invalidated but not the pointer.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002478 using ConstRestorationPt = const TypePromotionAction *;
Jun Bum Limdee55652017-04-03 19:20:07 +00002479
2480 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2481 : RemovedInsts(RemovedInsts) {}
2482
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002483 /// Advocate every changes made in that transaction.
2484 void commit();
Eugene Zelenko900b6332017-08-29 22:32:07 +00002485
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002486 /// Undo all the changes made after the given point.
2487 void rollback(ConstRestorationPt Point);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002488
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002489 /// Get the current restoration point.
2490 ConstRestorationPt getRestorationPoint() const;
2491
2492 /// \name API for IR modification with state keeping to support rollback.
2493 /// @{
2494 /// Same as Instruction::setOperand.
2495 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002496
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002497 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002498 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002499
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002500 /// Same as Value::replaceAllUsesWith.
2501 void replaceAllUsesWith(Instruction *Inst, Value *New);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002502
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002503 /// Same as Value::mutateType.
2504 void mutateType(Instruction *Inst, Type *NewTy);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002505
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002506 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002507 Value *createTrunc(Instruction *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002508
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002509 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002510 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002511
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002512 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002513 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002514
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002515 /// Same as Instruction::moveBefore.
2516 void moveBefore(Instruction *Inst, Instruction *Before);
2517 /// @}
2518
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002519private:
2520 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002521 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002522
2523 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2524
Jun Bum Limdee55652017-04-03 19:20:07 +00002525 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002526};
2527
Eugene Zelenko900b6332017-08-29 22:32:07 +00002528} // end anonymous namespace
2529
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002530void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2531 Value *NewVal) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002532 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2533 Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002534}
2535
2536void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2537 Value *NewVal) {
2538 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002539 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2540 Inst, RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002541}
2542
2543void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2544 Value *New) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002545 Actions.push_back(
2546 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002547}
2548
2549void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002550 Actions.push_back(
2551 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002552}
2553
Quentin Colombetac55b152014-09-16 22:36:07 +00002554Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2555 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002556 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002557 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002558 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002559 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002560}
2561
Quentin Colombetac55b152014-09-16 22:36:07 +00002562Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2563 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002564 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002565 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002566 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002567 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002568}
2569
Quentin Colombetac55b152014-09-16 22:36:07 +00002570Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2571 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002572 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002573 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002574 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002575 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002576}
2577
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002578void TypePromotionTransaction::moveBefore(Instruction *Inst,
2579 Instruction *Before) {
2580 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002581 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2582 Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002583}
2584
2585TypePromotionTransaction::ConstRestorationPt
2586TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002587 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002588}
2589
2590void TypePromotionTransaction::commit() {
2591 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002592 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002593 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002594 Actions.clear();
2595}
2596
2597void TypePromotionTransaction::rollback(
2598 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002599 while (!Actions.empty() && Point != Actions.back().get()) {
2600 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002601 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002602 }
2603}
2604
Eugene Zelenko900b6332017-08-29 22:32:07 +00002605namespace {
2606
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002607/// A helper class for matching addressing modes.
Chandler Carruthc8925912013-01-05 02:09:22 +00002608///
2609/// This encapsulates the logic for matching the target-legal addressing modes.
2610class AddressingModeMatcher {
2611 SmallVectorImpl<Instruction*> &AddrModeInsts;
2612 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002613 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002614 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002615
2616 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2617 /// the memory instruction that we're computing this address for.
2618 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002619 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002620 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002621
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002622 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002623 /// part of the return value of this addressing mode matching stuff.
2624 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002625
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002626 /// The instructions inserted by other CodeGenPrepare optimizations.
2627 const SetOfInstrs &InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002628
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002629 /// A map from the instructions to their type before promotion.
2630 InstrToOrigTy &PromotedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002631
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002632 /// The ongoing transaction where every action should be registered.
2633 TypePromotionTransaction &TPT;
2634
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002635 // A GEP which has too large offset to be folded into the addressing mode.
2636 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
2637
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002638 /// This is set to true when we should not do profitability checks.
2639 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002640 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002641
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002642 AddressingModeMatcher(
2643 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
2644 const TargetRegisterInfo &TRI, Type *AT, unsigned AS, Instruction *MI,
2645 ExtAddrMode &AM, const SetOfInstrs &InsertedInsts,
2646 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
2647 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002648 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002649 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2650 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002651 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002652 IgnoreProfitability = false;
2653 }
Stephen Lin837bba12013-07-15 17:55:02 +00002654
Eugene Zelenko900b6332017-08-29 22:32:07 +00002655public:
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002656 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002657 /// give an access type of AccessTy. This returns a list of involved
2658 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002659 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002660 /// optimizations.
2661 /// \p PromotedInsts maps the instructions to their type before promotion.
2662 /// \p The ongoing transaction where every action should be registered.
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002663 static ExtAddrMode
2664 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
2665 SmallVectorImpl<Instruction *> &AddrModeInsts,
2666 const TargetLowering &TLI, const TargetRegisterInfo &TRI,
2667 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
2668 TypePromotionTransaction &TPT,
2669 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002670 ExtAddrMode Result;
2671
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002672 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002673 MemoryInst, Result, InsertedInsts,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002674 PromotedInsts, TPT, LargeOffsetGEP)
2675 .matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002676 (void)Success; assert(Success && "Couldn't select *anything*?");
2677 return Result;
2678 }
Eugene Zelenko900b6332017-08-29 22:32:07 +00002679
Chandler Carruthc8925912013-01-05 02:09:22 +00002680private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002681 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
Fangrui Songcb0bab82018-07-16 18:51:40 +00002682 bool matchAddr(Value *Addr, unsigned Depth);
2683 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002684 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002685 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002686 ExtAddrMode &AMBefore,
2687 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002688 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2689 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002690 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002691};
2692
Ali Tamurd482b012018-11-12 21:43:43 +00002693class PhiNodeSet;
2694
2695/// An iterator for PhiNodeSet.
2696class PhiNodeSetIterator {
2697 PhiNodeSet * const Set;
2698 size_t CurrentIndex = 0;
2699
2700public:
2701 /// The constructor. Start should point to either a valid element, or be equal
2702 /// to the size of the underlying SmallVector of the PhiNodeSet.
2703 PhiNodeSetIterator(PhiNodeSet * const Set, size_t Start);
2704 PHINode * operator*() const;
2705 PhiNodeSetIterator& operator++();
2706 bool operator==(const PhiNodeSetIterator &RHS) const;
2707 bool operator!=(const PhiNodeSetIterator &RHS) const;
2708};
2709
2710/// Keeps a set of PHINodes.
2711///
2712/// This is a minimal set implementation for a specific use case:
2713/// It is very fast when there are very few elements, but also provides good
2714/// performance when there are many. It is similar to SmallPtrSet, but also
2715/// provides iteration by insertion order, which is deterministic and stable
2716/// across runs. It is also similar to SmallSetVector, but provides removing
2717/// elements in O(1) time. This is achieved by not actually removing the element
2718/// from the underlying vector, so comes at the cost of using more memory, but
2719/// that is fine, since PhiNodeSets are used as short lived objects.
2720class PhiNodeSet {
2721 friend class PhiNodeSetIterator;
2722
2723 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
2724 using iterator = PhiNodeSetIterator;
2725
2726 /// Keeps the elements in the order of their insertion in the underlying
2727 /// vector. To achieve constant time removal, it never deletes any element.
2728 SmallVector<PHINode *, 32> NodeList;
2729
2730 /// Keeps the elements in the underlying set implementation. This (and not the
2731 /// NodeList defined above) is the source of truth on whether an element
2732 /// is actually in the collection.
2733 MapType NodeMap;
2734
2735 /// Points to the first valid (not deleted) element when the set is not empty
2736 /// and the value is not zero. Equals to the size of the underlying vector
2737 /// when the set is empty. When the value is 0, as in the beginning, the
2738 /// first element may or may not be valid.
2739 size_t FirstValidElement = 0;
2740
2741public:
2742 /// Inserts a new element to the collection.
2743 /// \returns true if the element is actually added, i.e. was not in the
2744 /// collection before the operation.
2745 bool insert(PHINode *Ptr) {
2746 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
2747 NodeList.push_back(Ptr);
2748 return true;
2749 }
2750 return false;
2751 }
2752
2753 /// Removes the element from the collection.
2754 /// \returns whether the element is actually removed, i.e. was in the
2755 /// collection before the operation.
2756 bool erase(PHINode *Ptr) {
2757 auto it = NodeMap.find(Ptr);
2758 if (it != NodeMap.end()) {
2759 NodeMap.erase(Ptr);
2760 SkipRemovedElements(FirstValidElement);
2761 return true;
2762 }
2763 return false;
2764 }
2765
2766 /// Removes all elements and clears the collection.
2767 void clear() {
2768 NodeMap.clear();
2769 NodeList.clear();
2770 FirstValidElement = 0;
2771 }
2772
2773 /// \returns an iterator that will iterate the elements in the order of
2774 /// insertion.
2775 iterator begin() {
2776 if (FirstValidElement == 0)
2777 SkipRemovedElements(FirstValidElement);
2778 return PhiNodeSetIterator(this, FirstValidElement);
2779 }
2780
2781 /// \returns an iterator that points to the end of the collection.
2782 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
2783
2784 /// Returns the number of elements in the collection.
2785 size_t size() const {
2786 return NodeMap.size();
2787 }
2788
2789 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
2790 size_t count(PHINode *Ptr) const {
2791 return NodeMap.count(Ptr);
2792 }
2793
2794private:
2795 /// Updates the CurrentIndex so that it will point to a valid element.
2796 ///
2797 /// If the element of NodeList at CurrentIndex is valid, it does not
2798 /// change it. If there are no more valid elements, it updates CurrentIndex
2799 /// to point to the end of the NodeList.
2800 void SkipRemovedElements(size_t &CurrentIndex) {
2801 while (CurrentIndex < NodeList.size()) {
2802 auto it = NodeMap.find(NodeList[CurrentIndex]);
2803 // If the element has been deleted and added again later, NodeMap will
2804 // point to a different index, so CurrentIndex will still be invalid.
2805 if (it != NodeMap.end() && it->second == CurrentIndex)
2806 break;
2807 ++CurrentIndex;
2808 }
2809 }
2810};
2811
2812PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
2813 : Set(Set), CurrentIndex(Start) {}
2814
2815PHINode * PhiNodeSetIterator::operator*() const {
2816 assert(CurrentIndex < Set->NodeList.size() &&
2817 "PhiNodeSet access out of range");
2818 return Set->NodeList[CurrentIndex];
2819}
2820
2821PhiNodeSetIterator& PhiNodeSetIterator::operator++() {
2822 assert(CurrentIndex < Set->NodeList.size() &&
2823 "PhiNodeSet access out of range");
2824 ++CurrentIndex;
2825 Set->SkipRemovedElements(CurrentIndex);
2826 return *this;
2827}
2828
2829bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
2830 return CurrentIndex == RHS.CurrentIndex;
2831}
2832
2833bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
Serge Guelton12c7a962018-11-19 10:05:28 +00002834 return !((*this) == RHS);
Ali Tamurd482b012018-11-12 21:43:43 +00002835}
2836
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002837/// Keep track of simplification of Phi nodes.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002838/// Accept the set of all phi nodes and erase phi node from this set
2839/// if it is simplified.
2840class SimplificationTracker {
2841 DenseMap<Value *, Value *> Storage;
2842 const SimplifyQuery &SQ;
Ali Tamurd482b012018-11-12 21:43:43 +00002843 // Tracks newly created Phi nodes. The elements are iterated by insertion
2844 // order.
2845 PhiNodeSet AllPhiNodes;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002846 // Tracks newly created Select nodes.
2847 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002848
2849public:
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002850 SimplificationTracker(const SimplifyQuery &sq)
2851 : SQ(sq) {}
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002852
2853 Value *Get(Value *V) {
2854 do {
2855 auto SV = Storage.find(V);
2856 if (SV == Storage.end())
2857 return V;
2858 V = SV->second;
2859 } while (true);
2860 }
2861
2862 Value *Simplify(Value *Val) {
2863 SmallVector<Value *, 32> WorkList;
2864 SmallPtrSet<Value *, 32> Visited;
2865 WorkList.push_back(Val);
2866 while (!WorkList.empty()) {
2867 auto P = WorkList.pop_back_val();
2868 if (!Visited.insert(P).second)
2869 continue;
2870 if (auto *PI = dyn_cast<Instruction>(P))
2871 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
2872 for (auto *U : PI->users())
2873 WorkList.push_back(cast<Value>(U));
2874 Put(PI, V);
2875 PI->replaceAllUsesWith(V);
2876 if (auto *PHI = dyn_cast<PHINode>(PI))
Ali Tamurd482b012018-11-12 21:43:43 +00002877 AllPhiNodes.erase(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002878 if (auto *Select = dyn_cast<SelectInst>(PI))
2879 AllSelectNodes.erase(Select);
2880 PI->eraseFromParent();
2881 }
2882 }
2883 return Get(Val);
2884 }
2885
2886 void Put(Value *From, Value *To) {
2887 Storage.insert({ From, To });
2888 }
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002889
2890 void ReplacePhi(PHINode *From, PHINode *To) {
2891 Value* OldReplacement = Get(From);
2892 while (OldReplacement != From) {
2893 From = To;
2894 To = dyn_cast<PHINode>(OldReplacement);
2895 OldReplacement = Get(From);
2896 }
2897 assert(Get(To) == To && "Replacement PHI node is already replaced.");
2898 Put(From, To);
2899 From->replaceAllUsesWith(To);
Ali Tamurd482b012018-11-12 21:43:43 +00002900 AllPhiNodes.erase(From);
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002901 From->eraseFromParent();
2902 }
2903
Ali Tamurd482b012018-11-12 21:43:43 +00002904 PhiNodeSet& newPhiNodes() { return AllPhiNodes; }
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002905
2906 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
2907
2908 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
2909
2910 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
2911
2912 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
2913
2914 void destroyNewNodes(Type *CommonType) {
2915 // For safe erasing, replace the uses with dummy value first.
2916 auto Dummy = UndefValue::get(CommonType);
2917 for (auto I : AllPhiNodes) {
2918 I->replaceAllUsesWith(Dummy);
2919 I->eraseFromParent();
2920 }
2921 AllPhiNodes.clear();
2922 for (auto I : AllSelectNodes) {
2923 I->replaceAllUsesWith(Dummy);
2924 I->eraseFromParent();
2925 }
2926 AllSelectNodes.clear();
2927 }
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002928};
2929
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002930/// A helper class for combining addressing modes.
John Brawn736bf002017-10-03 13:08:22 +00002931class AddressingModeCombiner {
Serguei Katkov2673f172018-11-29 06:45:18 +00002932 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002933 typedef std::pair<PHINode *, PHINode *> PHIPair;
2934
John Brawn736bf002017-10-03 13:08:22 +00002935private:
2936 /// The addressing modes we've collected.
2937 SmallVector<ExtAddrMode, 16> AddrModes;
2938
2939 /// The field in which the AddrModes differ, when we have more than one.
2940 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
2941
2942 /// Are the AddrModes that we have all just equal to their original values?
2943 bool AllAddrModesTrivial = true;
2944
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002945 /// Common Type for all different fields in addressing modes.
2946 Type *CommonType;
2947
2948 /// SimplifyQuery for simplifyInstruction utility.
2949 const SimplifyQuery &SQ;
2950
2951 /// Original Address.
Serguei Katkov2673f172018-11-29 06:45:18 +00002952 Value *Original;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002953
John Brawn736bf002017-10-03 13:08:22 +00002954public:
Serguei Katkov2673f172018-11-29 06:45:18 +00002955 AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue)
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002956 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
2957
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002958 /// Get the combined AddrMode
John Brawn736bf002017-10-03 13:08:22 +00002959 const ExtAddrMode &getAddrMode() const {
2960 return AddrModes[0];
2961 }
2962
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002963 /// Add a new AddrMode if it's compatible with the AddrModes we already
John Brawn736bf002017-10-03 13:08:22 +00002964 /// have.
2965 /// \return True iff we succeeded in doing so.
2966 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
2967 // Take note of if we have any non-trivial AddrModes, as we need to detect
2968 // when all AddrModes are trivial as then we would introduce a phi or select
2969 // which just duplicates what's already there.
2970 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
2971
2972 // If this is the first addrmode then everything is fine.
2973 if (AddrModes.empty()) {
2974 AddrModes.emplace_back(NewAddrMode);
2975 return true;
2976 }
2977
2978 // Figure out how different this is from the other address modes, which we
2979 // can do just by comparing against the first one given that we only care
2980 // about the cumulative difference.
2981 ExtAddrMode::FieldName ThisDifferentField =
2982 AddrModes[0].compare(NewAddrMode);
2983 if (DifferentField == ExtAddrMode::NoField)
2984 DifferentField = ThisDifferentField;
2985 else if (DifferentField != ThisDifferentField)
2986 DifferentField = ExtAddrMode::MultipleFields;
2987
Serguei Katkov17e57942018-01-23 12:07:49 +00002988 // If NewAddrMode differs in more than one dimension we cannot handle it.
2989 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
2990
2991 // If Scale Field is different then we reject.
2992 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
2993
Serguei Katkov4d1dd6b2018-01-09 04:37:06 +00002994 // We also must reject the case when base offset is different and
2995 // scale reg is not null, we cannot handle this case due to merge of
2996 // different offsets will be used as ScaleReg.
Serguei Katkov17e57942018-01-23 12:07:49 +00002997 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
2998 !NewAddrMode.ScaledReg);
John Brawn736bf002017-10-03 13:08:22 +00002999
Serguei Katkov17e57942018-01-23 12:07:49 +00003000 // We also must reject the case when GV is different and BaseReg installed
3001 // due to we want to use base reg as a merge of GV values.
3002 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
3003 !NewAddrMode.HasBaseReg);
3004
3005 // Even if NewAddMode is the same we still need to collect it due to
3006 // original value is different. And later we will need all original values
3007 // as anchors during finding the common Phi node.
3008 if (CanHandle)
3009 AddrModes.emplace_back(NewAddrMode);
3010 else
3011 AddrModes.clear();
3012
3013 return CanHandle;
John Brawn736bf002017-10-03 13:08:22 +00003014 }
3015
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003016 /// Combine the addressing modes we've collected into a single
John Brawn736bf002017-10-03 13:08:22 +00003017 /// addressing mode.
3018 /// \return True iff we successfully combined them or we only had one so
3019 /// didn't need to combine them anyway.
3020 bool combineAddrModes() {
3021 // If we have no AddrModes then they can't be combined.
3022 if (AddrModes.size() == 0)
3023 return false;
3024
3025 // A single AddrMode can trivially be combined.
Serguei Katkov505359f2017-11-20 05:42:36 +00003026 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
John Brawn736bf002017-10-03 13:08:22 +00003027 return true;
3028
3029 // If the AddrModes we collected are all just equal to the value they are
3030 // derived from then combining them wouldn't do anything useful.
3031 if (AllAddrModesTrivial)
3032 return false;
3033
John Brawn70cdb5b2017-11-24 14:10:45 +00003034 if (!addrModeCombiningAllowed())
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003035 return false;
3036
3037 // Build a map between <original value, basic block where we saw it> to
3038 // value of base register.
Serguei Katkov50364592017-11-29 05:51:26 +00003039 // Bail out if there is no common type.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003040 FoldAddrToValueMapping Map;
Serguei Katkov50364592017-11-29 05:51:26 +00003041 if (!initializeMap(Map))
3042 return false;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003043
3044 Value *CommonValue = findCommon(Map);
3045 if (CommonValue)
John Brawn70cdb5b2017-11-24 14:10:45 +00003046 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003047 return CommonValue != nullptr;
3048 }
3049
3050private:
Serguei Katkov2673f172018-11-29 06:45:18 +00003051 /// Initialize Map with anchor values. For address seen
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003052 /// we set the value of different field saw in this address.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003053 /// At the same time we find a common type for different field we will
3054 /// use to create new Phi/Select nodes. Keep it in CommonType field.
Serguei Katkov50364592017-11-29 05:51:26 +00003055 /// Return false if there is no common type found.
3056 bool initializeMap(FoldAddrToValueMapping &Map) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003057 // Keep track of keys where the value is null. We will need to replace it
3058 // with constant null when we know the common type.
Serguei Katkov2673f172018-11-29 06:45:18 +00003059 SmallVector<Value *, 2> NullValue;
John Brawn70cdb5b2017-11-24 14:10:45 +00003060 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003061 for (auto &AM : AddrModes) {
John Brawn70cdb5b2017-11-24 14:10:45 +00003062 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003063 if (DV) {
Serguei Katkov50364592017-11-29 05:51:26 +00003064 auto *Type = DV->getType();
3065 if (CommonType && CommonType != Type)
3066 return false;
3067 CommonType = Type;
Serguei Katkov2673f172018-11-29 06:45:18 +00003068 Map[AM.OriginalValue] = DV;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003069 } else {
Serguei Katkov2673f172018-11-29 06:45:18 +00003070 NullValue.push_back(AM.OriginalValue);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003071 }
3072 }
3073 assert(CommonType && "At least one non-null value must be!");
Serguei Katkov2673f172018-11-29 06:45:18 +00003074 for (auto *V : NullValue)
3075 Map[V] = Constant::getNullValue(CommonType);
Serguei Katkov50364592017-11-29 05:51:26 +00003076 return true;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003077 }
3078
Serguei Katkov2673f172018-11-29 06:45:18 +00003079 /// We have mapping between value A and other value B where B was a field in
3080 /// addressing mode represented by A. Also we have an original value C
3081 /// representing an address we start with. Traversing from C through phi and
3082 /// selects we ended up with A's in a map. This utility function tries to find
3083 /// a value V which is a field in addressing mode C and traversing through phi
3084 /// nodes and selects we will end up in corresponded values B in a map.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003085 /// The utility will create a new Phi/Selects if needed.
3086 // The simple example looks as follows:
3087 // BB1:
3088 // p1 = b1 + 40
3089 // br cond BB2, BB3
3090 // BB2:
3091 // p2 = b2 + 40
3092 // br BB3
3093 // BB3:
3094 // p = phi [p1, BB1], [p2, BB2]
3095 // v = load p
3096 // Map is
Serguei Katkov2673f172018-11-29 06:45:18 +00003097 // p1 -> b1
3098 // p2 -> b2
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003099 // Request is
Serguei Katkov2673f172018-11-29 06:45:18 +00003100 // p -> ?
3101 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003102 Value *findCommon(FoldAddrToValueMapping &Map) {
Eric Christopherd72f78e2018-01-09 23:25:38 +00003103 // Tracks the simplification of newly created phi nodes. The reason we use
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003104 // this mapping is because we will add new created Phi nodes in AddrToBase.
3105 // Simplification of Phi nodes is recursive, so some Phi node may
Serguei Katkov2673f172018-11-29 06:45:18 +00003106 // be simplified after we added it to AddrToBase. In reality this
3107 // simplification is possible only if original phi/selects were not
3108 // simplified yet.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003109 // Using this mapping we can find the current value in AddrToBase.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003110 SimplificationTracker ST(SQ);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003111
3112 // First step, DFS to create PHI nodes for all intermediate blocks.
3113 // Also fill traverse order for the second step.
Serguei Katkov2673f172018-11-29 06:45:18 +00003114 SmallVector<Value *, 32> TraverseOrder;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003115 InsertPlaceholders(Map, TraverseOrder, ST);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003116
3117 // Second Step, fill new nodes by merged values and simplify if possible.
3118 FillPlaceholders(Map, TraverseOrder, ST);
3119
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003120 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
3121 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003122 return nullptr;
3123 }
3124
3125 // Now we'd like to match New Phi nodes to existed ones.
3126 unsigned PhiNotMatchedCount = 0;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003127 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
3128 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003129 return nullptr;
3130 }
3131
3132 auto *Result = ST.Get(Map.find(Original)->second);
3133 if (Result) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003134 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
3135 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003136 }
3137 return Result;
3138 }
3139
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003140 /// Try to match PHI node to Candidate.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003141 /// Matcher tracks the matched Phi nodes.
3142 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003143 SmallSetVector<PHIPair, 8> &Matcher,
Ali Tamurd482b012018-11-12 21:43:43 +00003144 PhiNodeSet &PhiNodesToMatch) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003145 SmallVector<PHIPair, 8> WorkList;
3146 Matcher.insert({ PHI, Candidate });
3147 WorkList.push_back({ PHI, Candidate });
3148 SmallSet<PHIPair, 8> Visited;
3149 while (!WorkList.empty()) {
3150 auto Item = WorkList.pop_back_val();
3151 if (!Visited.insert(Item).second)
3152 continue;
3153 // We iterate over all incoming values to Phi to compare them.
3154 // If values are different and both of them Phi and the first one is a
3155 // Phi we added (subject to match) and both of them is in the same basic
3156 // block then we can match our pair if values match. So we state that
3157 // these values match and add it to work list to verify that.
3158 for (auto B : Item.first->blocks()) {
3159 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
3160 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
3161 if (FirstValue == SecondValue)
3162 continue;
3163
3164 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
3165 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
3166
3167 // One of them is not Phi or
3168 // The first one is not Phi node from the set we'd like to match or
3169 // Phi nodes from different basic blocks then
3170 // we will not be able to match.
3171 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
3172 FirstPhi->getParent() != SecondPhi->getParent())
3173 return false;
3174
3175 // If we already matched them then continue.
3176 if (Matcher.count({ FirstPhi, SecondPhi }))
3177 continue;
3178 // So the values are different and does not match. So we need them to
3179 // match.
3180 Matcher.insert({ FirstPhi, SecondPhi });
3181 // But me must check it.
3182 WorkList.push_back({ FirstPhi, SecondPhi });
3183 }
3184 }
3185 return true;
3186 }
3187
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003188 /// For the given set of PHI nodes (in the SimplificationTracker) try
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003189 /// to find their equivalents.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003190 /// Returns false if this matching fails and creation of new Phi is disabled.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003191 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003192 unsigned &PhiNotMatchedCount) {
Ali Tamurd482b012018-11-12 21:43:43 +00003193 // Matched and PhiNodesToMatch iterate their elements in a deterministic
3194 // order, so the replacements (ReplacePhi) are also done in a deterministic
3195 // order.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003196 SmallSetVector<PHIPair, 8> Matched;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003197 SmallPtrSet<PHINode *, 8> WillNotMatch;
Ali Tamurd482b012018-11-12 21:43:43 +00003198 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003199 while (PhiNodesToMatch.size()) {
3200 PHINode *PHI = *PhiNodesToMatch.begin();
3201
3202 // Add us, if no Phi nodes in the basic block we do not match.
3203 WillNotMatch.clear();
3204 WillNotMatch.insert(PHI);
3205
3206 // Traverse all Phis until we found equivalent or fail to do that.
3207 bool IsMatched = false;
3208 for (auto &P : PHI->getParent()->phis()) {
3209 if (&P == PHI)
3210 continue;
3211 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3212 break;
3213 // If it does not match, collect all Phi nodes from matcher.
3214 // if we end up with no match, them all these Phi nodes will not match
3215 // later.
3216 for (auto M : Matched)
3217 WillNotMatch.insert(M.first);
3218 Matched.clear();
3219 }
3220 if (IsMatched) {
Serguei Katkova20e05b2018-03-12 03:50:07 +00003221 // Replace all matched values and erase them.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003222 for (auto MV : Matched)
3223 ST.ReplacePhi(MV.first, MV.second);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003224 Matched.clear();
3225 continue;
3226 }
3227 // If we are not allowed to create new nodes then bail out.
3228 if (!AllowNewPhiNodes)
3229 return false;
3230 // Just remove all seen values in matcher. They will not match anything.
3231 PhiNotMatchedCount += WillNotMatch.size();
3232 for (auto *P : WillNotMatch)
Ali Tamurd482b012018-11-12 21:43:43 +00003233 PhiNodesToMatch.erase(P);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003234 }
3235 return true;
3236 }
Serguei Katkov2673f172018-11-29 06:45:18 +00003237 /// Fill the placeholders with values from predecessors and simplify them.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003238 void FillPlaceholders(FoldAddrToValueMapping &Map,
Serguei Katkov2673f172018-11-29 06:45:18 +00003239 SmallVectorImpl<Value *> &TraverseOrder,
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003240 SimplificationTracker &ST) {
3241 while (!TraverseOrder.empty()) {
Serguei Katkov2673f172018-11-29 06:45:18 +00003242 Value *Current = TraverseOrder.pop_back_val();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003243 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003244 Value *V = Map[Current];
3245
3246 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3247 // CurrentValue also must be Select.
Serguei Katkov2673f172018-11-29 06:45:18 +00003248 auto *CurrentSelect = cast<SelectInst>(Current);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003249 auto *TrueValue = CurrentSelect->getTrueValue();
Serguei Katkov2673f172018-11-29 06:45:18 +00003250 assert(Map.find(TrueValue) != Map.end() && "No True Value!");
3251 Select->setTrueValue(ST.Get(Map[TrueValue]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003252 auto *FalseValue = CurrentSelect->getFalseValue();
Serguei Katkov2673f172018-11-29 06:45:18 +00003253 assert(Map.find(FalseValue) != Map.end() && "No False Value!");
3254 Select->setFalseValue(ST.Get(Map[FalseValue]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003255 } else {
3256 // Must be a Phi node then.
3257 PHINode *PHI = cast<PHINode>(V);
Serguei Katkov2673f172018-11-29 06:45:18 +00003258 auto *CurrentPhi = dyn_cast<PHINode>(Current);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003259 // Fill the Phi node with values from predecessors.
Serguei Katkov2673f172018-11-29 06:45:18 +00003260 for (auto B : predecessors(PHI->getParent())) {
3261 Value *PV = CurrentPhi->getIncomingValueForBlock(B);
3262 assert(Map.find(PV) != Map.end() && "No predecessor Value!");
3263 PHI->addIncoming(ST.Get(Map[PV]), B);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003264 }
3265 }
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003266 Map[Current] = ST.Simplify(V);
3267 }
3268 }
3269
Serguei Katkov2673f172018-11-29 06:45:18 +00003270 /// Starting from original value recursively iterates over def-use chain up to
3271 /// known ending values represented in a map. For each traversed phi/select
3272 /// inserts a placeholder Phi or Select.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003273 /// Reports all new created Phi/Select nodes by adding them to set.
Serguei Katkov2673f172018-11-29 06:45:18 +00003274 /// Also reports and order in what values have been traversed.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003275 void InsertPlaceholders(FoldAddrToValueMapping &Map,
Serguei Katkov2673f172018-11-29 06:45:18 +00003276 SmallVectorImpl<Value *> &TraverseOrder,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003277 SimplificationTracker &ST) {
Serguei Katkov2673f172018-11-29 06:45:18 +00003278 SmallVector<Value *, 32> Worklist;
3279 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003280 "Address must be a Phi or Select node");
3281 auto *Dummy = UndefValue::get(CommonType);
3282 Worklist.push_back(Original);
3283 while (!Worklist.empty()) {
Serguei Katkov2673f172018-11-29 06:45:18 +00003284 Value *Current = Worklist.pop_back_val();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003285 // if it is already visited or it is an ending value then skip it.
3286 if (Map.find(Current) != Map.end())
3287 continue;
3288 TraverseOrder.push_back(Current);
3289
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003290 // CurrentValue must be a Phi node or select. All others must be covered
3291 // by anchors.
Serguei Katkov2673f172018-11-29 06:45:18 +00003292 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003293 // Is it OK to get metadata from OrigSelect?!
3294 // Create a Select placeholder with dummy value.
Serguei Katkov2673f172018-11-29 06:45:18 +00003295 SelectInst *Select = SelectInst::Create(
3296 CurrentSelect->getCondition(), Dummy, Dummy,
3297 CurrentSelect->getName(), CurrentSelect, CurrentSelect);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003298 Map[Current] = Select;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003299 ST.insertNewSelect(Select);
Serguei Katkov2673f172018-11-29 06:45:18 +00003300 // We are interested in True and False values.
3301 Worklist.push_back(CurrentSelect->getTrueValue());
3302 Worklist.push_back(CurrentSelect->getFalseValue());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003303 } else {
3304 // It must be a Phi node then.
Serguei Katkov2673f172018-11-29 06:45:18 +00003305 PHINode *CurrentPhi = cast<PHINode>(Current);
3306 unsigned PredCount = CurrentPhi->getNumIncomingValues();
3307 PHINode *PHI =
3308 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003309 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003310 ST.insertNewPhi(PHI);
Serguei Katkov2673f172018-11-29 06:45:18 +00003311 for (Value *P : CurrentPhi->incoming_values())
3312 Worklist.push_back(P);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003313 }
3314 }
John Brawn736bf002017-10-03 13:08:22 +00003315 }
John Brawn70cdb5b2017-11-24 14:10:45 +00003316
3317 bool addrModeCombiningAllowed() {
3318 if (DisableComplexAddrModes)
3319 return false;
3320 switch (DifferentField) {
3321 default:
3322 return false;
3323 case ExtAddrMode::BaseRegField:
3324 return AddrSinkCombineBaseReg;
3325 case ExtAddrMode::BaseGVField:
3326 return AddrSinkCombineBaseGV;
3327 case ExtAddrMode::BaseOffsField:
3328 return AddrSinkCombineBaseOffs;
3329 case ExtAddrMode::ScaledRegField:
3330 return AddrSinkCombineScaledReg;
3331 }
3332 }
John Brawn736bf002017-10-03 13:08:22 +00003333};
Eugene Zelenko900b6332017-08-29 22:32:07 +00003334} // end anonymous namespace
3335
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003336/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003337/// Return true and update AddrMode if this addr mode is legal for the target,
3338/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003339bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003340 unsigned Depth) {
3341 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3342 // mode. Just process that directly.
3343 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003344 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003345
Chandler Carruthc8925912013-01-05 02:09:22 +00003346 // If the scale is 0, it takes nothing to add this.
3347 if (Scale == 0)
3348 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003349
Chandler Carruthc8925912013-01-05 02:09:22 +00003350 // If we already have a scale of this value, we can add to it, otherwise, we
3351 // need an available scale field.
3352 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3353 return false;
3354
3355 ExtAddrMode TestAddrMode = AddrMode;
3356
3357 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3358 // [A+B + A*7] -> [B+A*8].
3359 TestAddrMode.Scale += Scale;
3360 TestAddrMode.ScaledReg = ScaleReg;
3361
3362 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003363 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003364 return false;
3365
3366 // It was legal, so commit it.
3367 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003368
Chandler Carruthc8925912013-01-05 02:09:22 +00003369 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3370 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3371 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003372 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003373 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3374 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3375 TestAddrMode.ScaledReg = AddLHS;
3376 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003377
Chandler Carruthc8925912013-01-05 02:09:22 +00003378 // If this addressing mode is legal, commit it and remember that we folded
3379 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003380 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003381 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3382 AddrMode = TestAddrMode;
3383 return true;
3384 }
3385 }
3386
3387 // Otherwise, not (x+c)*scale, just return what we have.
3388 return true;
3389}
3390
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003391/// This is a little filter, which returns true if an addressing computation
3392/// involving I might be folded into a load/store accessing it.
3393/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003394/// the set of instructions that MatchOperationAddr can.
3395static bool MightBeFoldableInst(Instruction *I) {
3396 switch (I->getOpcode()) {
3397 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003398 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003399 // Don't touch identity bitcasts.
3400 if (I->getType() == I->getOperand(0)->getType())
3401 return false;
Vedant Kumarb3091da2018-07-06 20:17:42 +00003402 return I->getType()->isIntOrPtrTy();
Chandler Carruthc8925912013-01-05 02:09:22 +00003403 case Instruction::PtrToInt:
3404 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3405 return true;
3406 case Instruction::IntToPtr:
3407 // We know the input is intptr_t, so this is foldable.
3408 return true;
3409 case Instruction::Add:
3410 return true;
3411 case Instruction::Mul:
3412 case Instruction::Shl:
3413 // Can only handle X*C and X << C.
3414 return isa<ConstantInt>(I->getOperand(1));
3415 case Instruction::GetElementPtr:
3416 return true;
3417 default:
3418 return false;
3419 }
3420}
3421
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003422/// Check whether or not \p Val is a legal instruction for \p TLI.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003423/// \note \p Val is assumed to be the product of some type promotion.
3424/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3425/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003426static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3427 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003428 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3429 if (!PromotedInst)
3430 return false;
3431 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3432 // If the ISDOpcode is undefined, it was undefined before the promotion.
3433 if (!ISDOpcode)
3434 return true;
3435 // Otherwise, check if the promoted instruction is legal or not.
3436 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003437 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003438}
3439
Eugene Zelenko900b6332017-08-29 22:32:07 +00003440namespace {
3441
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003442/// Hepler class to perform type promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003443class TypePromotionHelper {
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003444 /// Utility function to add a promoted instruction \p ExtOpnd to
3445 /// \p PromotedInsts and record the type of extension we have seen.
3446 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
3447 Instruction *ExtOpnd,
3448 bool IsSExt) {
3449 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3450 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
3451 if (It != PromotedInsts.end()) {
3452 // If the new extension is same as original, the information in
3453 // PromotedInsts[ExtOpnd] is still correct.
3454 if (It->second.getInt() == ExtTy)
3455 return;
3456
3457 // Now the new extension is different from old extension, we make
3458 // the type information invalid by setting extension type to
3459 // BothExtension.
3460 ExtTy = BothExtension;
3461 }
3462 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
3463 }
3464
3465 /// Utility function to query the original type of instruction \p Opnd
3466 /// with a matched extension type. If the extension doesn't match, we
3467 /// cannot use the information we had on the original type.
3468 /// BothExtension doesn't match any extension type.
3469 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
3470 Instruction *Opnd,
3471 bool IsSExt) {
3472 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3473 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3474 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
3475 return It->second.getPointer();
3476 return nullptr;
3477 }
3478
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003479 /// Utility function to check whether or not a sign or zero extension
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003480 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3481 /// either using the operands of \p Inst or promoting \p Inst.
3482 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003483 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003484 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003485 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003486 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003487 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003488 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003489 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003490 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3491 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003492
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003493 /// Utility function to determine if \p OpIdx should be promoted when
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003494 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003495 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003496 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003497 }
3498
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003499 /// Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003500 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003501 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003502 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003503 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003504 /// Newly added extensions are inserted in \p Exts.
3505 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003506 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003507 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003508 static Value *promoteOperandForTruncAndAnyExt(
3509 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003510 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003511 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003512 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003513
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003514 /// Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003515 /// operand is promotable and is not a supported trunc or sext.
3516 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003517 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003518 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003519 /// Newly added extensions are inserted in \p Exts.
3520 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003521 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003522 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003523 static Value *promoteOperandForOther(Instruction *Ext,
3524 TypePromotionTransaction &TPT,
3525 InstrToOrigTy &PromotedInsts,
3526 unsigned &CreatedInstsCost,
3527 SmallVectorImpl<Instruction *> *Exts,
3528 SmallVectorImpl<Instruction *> *Truncs,
3529 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003530
3531 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003532 static Value *signExtendOperandForOther(
3533 Instruction *Ext, TypePromotionTransaction &TPT,
3534 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3535 SmallVectorImpl<Instruction *> *Exts,
3536 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3537 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3538 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003539 }
3540
3541 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003542 static Value *zeroExtendOperandForOther(
3543 Instruction *Ext, TypePromotionTransaction &TPT,
3544 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3545 SmallVectorImpl<Instruction *> *Exts,
3546 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3547 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3548 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003549 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003550
3551public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003552 /// Type for the utility function that promotes the operand of Ext.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003553 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3554 InstrToOrigTy &PromotedInsts,
3555 unsigned &CreatedInstsCost,
3556 SmallVectorImpl<Instruction *> *Exts,
3557 SmallVectorImpl<Instruction *> *Truncs,
3558 const TargetLowering &TLI);
3559
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003560 /// Given a sign/zero extend instruction \p Ext, return the appropriate
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003561 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003562 /// \return NULL if no promotable action is possible with the current
3563 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003564 /// \p InsertedInsts keeps track of all the instructions inserted by the
3565 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003566 /// because we do not want to promote these instructions as CodeGenPrepare
3567 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3568 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003569 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003570 const TargetLowering &TLI,
3571 const InstrToOrigTy &PromotedInsts);
3572};
3573
Eugene Zelenko900b6332017-08-29 22:32:07 +00003574} // end anonymous namespace
3575
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003576bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003577 Type *ConsideredExtType,
3578 const InstrToOrigTy &PromotedInsts,
3579 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003580 // The promotion helper does not know how to deal with vector types yet.
3581 // To be able to fix that, we would need to fix the places where we
3582 // statically extend, e.g., constants and such.
3583 if (Inst->getType()->isVectorTy())
3584 return false;
3585
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003586 // We can always get through zext.
3587 if (isa<ZExtInst>(Inst))
3588 return true;
3589
3590 // sext(sext) is ok too.
3591 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003592 return true;
3593
3594 // We can get through binary operator, if it is legal. In other words, the
3595 // binary operator must have a nuw or nsw flag.
3596 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3597 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003598 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3599 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003600 return true;
3601
Guozhi Weic4c6b542018-06-05 21:03:52 +00003602 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
3603 if ((Inst->getOpcode() == Instruction::And ||
3604 Inst->getOpcode() == Instruction::Or))
3605 return true;
3606
3607 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
3608 if (Inst->getOpcode() == Instruction::Xor) {
3609 const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1));
3610 // Make sure it is not a NOT.
3611 if (Cst && !Cst->getValue().isAllOnesValue())
3612 return true;
3613 }
3614
3615 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
3616 // It may change a poisoned value into a regular value, like
3617 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
3618 // poisoned value regular value
3619 // It should be OK since undef covers valid value.
3620 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
3621 return true;
3622
3623 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
3624 // It may change a poisoned value into a regular value, like
3625 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
3626 // poisoned value regular value
3627 // It should be OK since undef covers valid value.
3628 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
3629 const Instruction *ExtInst =
3630 dyn_cast<const Instruction>(*Inst->user_begin());
3631 if (ExtInst->hasOneUse()) {
3632 const Instruction *AndInst =
3633 dyn_cast<const Instruction>(*ExtInst->user_begin());
3634 if (AndInst && AndInst->getOpcode() == Instruction::And) {
3635 const ConstantInt *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
3636 if (Cst &&
3637 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
3638 return true;
3639 }
3640 }
3641 }
3642
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003643 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003644 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003645 if (!isa<TruncInst>(Inst))
3646 return false;
3647
3648 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003649 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003650 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003651 if (!OpndVal->getType()->isIntegerTy() ||
3652 OpndVal->getType()->getIntegerBitWidth() >
3653 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003654 return false;
3655
3656 // If the operand of the truncate is not an instruction, we will not have
3657 // any information on the dropped bits.
3658 // (Actually we could for constant but it is not worth the extra logic).
3659 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3660 if (!Opnd)
3661 return false;
3662
3663 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003664 // I.e., check that trunc just drops extended bits of the same kind of
3665 // the extension.
3666 // #1 get the type of the operand and check the kind of the extended bits.
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003667 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
3668 if (OpndType)
3669 ;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003670 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3671 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003672 else
3673 return false;
3674
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003675 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003676 return Inst->getType()->getIntegerBitWidth() >=
3677 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003678}
3679
3680TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003681 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003682 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003683 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3684 "Unexpected instruction type");
3685 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3686 Type *ExtTy = Ext->getType();
3687 bool IsSExt = isa<SExtInst>(Ext);
3688 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003689 // get through.
3690 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003691 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003692 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003693
3694 // Do not promote if the operand has been added by codegenprepare.
3695 // Otherwise, it means we are undoing an optimization that is likely to be
3696 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003697 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003698 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003699
3700 // SExt or Trunc instructions.
3701 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003702 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3703 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003704 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003705
3706 // Regular instruction.
3707 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003708 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003709 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003710 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003711}
3712
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003713Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003714 Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003715 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003716 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003717 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003718 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3719 // get through it and this method should not be called.
3720 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003721 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003722 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003723 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003724 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003725 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003726 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003727 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003728 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3729 TPT.replaceAllUsesWith(SExt, ZExt);
3730 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003731 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003732 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003733 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3734 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003735 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3736 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003737 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003738
3739 // Remove dead code.
3740 if (SExtOpnd->use_empty())
3741 TPT.eraseInstruction(SExtOpnd);
3742
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003743 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003744 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003745 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003746 if (ExtInst) {
3747 if (Exts)
3748 Exts->push_back(ExtInst);
3749 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3750 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003751 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003752 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003753
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003754 // At this point we have: ext ty opnd to ty.
3755 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3756 Value *NextVal = ExtInst->getOperand(0);
3757 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003758 return NextVal;
3759}
3760
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003761Value *TypePromotionHelper::promoteOperandForOther(
3762 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003763 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003764 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003765 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3766 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003767 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003768 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003769 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003770 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003771 if (!ExtOpnd->hasOneUse()) {
3772 // ExtOpnd will be promoted.
3773 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003774 // promoted version.
3775 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003776 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003777 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
Quentin Colombetac55b152014-09-16 22:36:07 +00003778 // Insert it just after the definition.
Sanjay Patel674d2c22017-08-29 14:07:48 +00003779 ITrunc->moveAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003780 if (Truncs)
3781 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003782 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003783
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003784 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003785 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003786 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003787 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003788 }
3789
3790 // Get through the Instruction:
3791 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003792 // 2. Replace the uses of Ext by Inst.
3793 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003794
3795 // Remember the original type of the instruction before promotion.
3796 // This is useful to know that the high bits are sign extended bits.
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003797 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003798 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003799 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003800 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003801 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003802 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003803 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003804
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003805 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003806 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003807 ++OpIdx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003808 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003809 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3810 !shouldExtOperand(ExtOpnd, OpIdx)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003811 LLVM_DEBUG(dbgs() << "No need to propagate\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003812 continue;
3813 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003814 // Check if we can statically extend the operand.
3815 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003816 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003817 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003818 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3819 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3820 : Cst->getValue().zext(BitWidth);
3821 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003822 continue;
3823 }
3824 // UndefValue are typed, so we have to statically sign extend them.
3825 if (isa<UndefValue>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003826 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003827 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003828 continue;
3829 }
3830
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003831 // Otherwise we have to explicitly sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003832 // Check if Ext was reused to extend an operand.
3833 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003834 // If yes, create a new one.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003835 LLVM_DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003836 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3837 : TPT.createZExt(Ext, Opnd, Ext->getType());
3838 if (!isa<Instruction>(ValForExtOpnd)) {
3839 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3840 continue;
3841 }
3842 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003843 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003844 if (Exts)
3845 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003846 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003847
3848 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003849 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3850 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003851 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003852 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003853 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003854 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003855 if (ExtForOpnd == Ext) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003856 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003857 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003858 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003859 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003860}
3861
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003862/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003863/// \p NewCost gives the cost of extension instructions created by the
3864/// promotion.
3865/// \p OldCost gives the cost of extension instructions before the promotion
3866/// plus the number of instructions that have been
3867/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003868/// \p PromotedOperand is the value that has been promoted.
3869/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003870bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003871 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003872 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
3873 << '\n');
Quentin Colombet1b274f92015-03-10 21:48:15 +00003874 // The cost of the new extensions is greater than the cost of the
3875 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003876 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003877 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003878 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003879 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003880 return true;
3881 // The promotion is neutral but it may help folding the sign extension in
3882 // loads for instance.
3883 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003884 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003885}
3886
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003887/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003888/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003889/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003890/// If \p MovedAway is not NULL, it contains the information of whether or
3891/// not AddrInst has to be folded into the addressing mode on success.
3892/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3893/// because it has been moved away.
3894/// Thus AddrInst must not be added in the matched instructions.
3895/// This state can happen when AddrInst is a sext, since it may be moved away.
3896/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3897/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003898bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003899 unsigned Depth,
3900 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003901 // Avoid exponential behavior on extremely deep expression trees.
3902 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003903
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003904 // By default, all matched instructions stay in place.
3905 if (MovedAway)
3906 *MovedAway = false;
3907
Chandler Carruthc8925912013-01-05 02:09:22 +00003908 switch (Opcode) {
3909 case Instruction::PtrToInt:
3910 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003911 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003912 case Instruction::IntToPtr: {
3913 auto AS = AddrInst->getType()->getPointerAddressSpace();
3914 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003915 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003916 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003917 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003918 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003919 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003920 case Instruction::BitCast:
3921 // BitCast is always a noop, and we can handle it as long as it is
3922 // int->int or pointer->pointer (we don't want int<->fp or something).
Vedant Kumarb3091da2018-07-06 20:17:42 +00003923 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
Chandler Carruthc8925912013-01-05 02:09:22 +00003924 // Don't touch identity bitcasts. These were probably put here by LSR,
3925 // and we don't want to mess around with them. Assume it knows what it
3926 // is doing.
3927 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003928 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003929 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003930 case Instruction::AddrSpaceCast: {
3931 unsigned SrcAS
3932 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3933 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3934 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003935 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003936 return false;
3937 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003938 case Instruction::Add: {
3939 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3940 ExtAddrMode BackupAddrMode = AddrMode;
3941 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003942 // Start a transaction at this point.
3943 // The LHS may match but not the RHS.
3944 // Therefore, we need a higher level restoration point to undo partially
3945 // matched operation.
3946 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3947 TPT.getRestorationPoint();
3948
Sanjay Patelfc580a62015-09-21 23:03:16 +00003949 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3950 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003951 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003952
Chandler Carruthc8925912013-01-05 02:09:22 +00003953 // Restore the old addr mode info.
3954 AddrMode = BackupAddrMode;
3955 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003956 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003957
Chandler Carruthc8925912013-01-05 02:09:22 +00003958 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003959 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3960 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003961 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003962
Chandler Carruthc8925912013-01-05 02:09:22 +00003963 // Otherwise we definitely can't merge the ADD in.
3964 AddrMode = BackupAddrMode;
3965 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003966 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003967 break;
3968 }
3969 //case Instruction::Or:
3970 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3971 //break;
3972 case Instruction::Mul:
3973 case Instruction::Shl: {
3974 // Can only handle X*C and X << C.
3975 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Philip Reames9c3cbee2017-10-30 23:59:51 +00003976 if (!RHS || RHS->getBitWidth() > 64)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003977 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003978 int64_t Scale = RHS->getSExtValue();
3979 if (Opcode == Instruction::Shl)
3980 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003981
Sanjay Patelfc580a62015-09-21 23:03:16 +00003982 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003983 }
3984 case Instruction::GetElementPtr: {
3985 // Scan the GEP. We check it if it contains constant offsets and at most
3986 // one variable offset.
3987 int VariableOperand = -1;
3988 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003989
Chandler Carruthc8925912013-01-05 02:09:22 +00003990 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003991 gep_type_iterator GTI = gep_type_begin(AddrInst);
3992 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003993 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003994 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003995 unsigned Idx =
3996 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3997 ConstantOffset += SL->getElementOffset(Idx);
3998 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003999 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00004000 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
Simon Pilgrimee82a792018-08-13 12:10:09 +00004001 const APInt &CVal = CI->getValue();
4002 if (CVal.getMinSignedBits() <= 64) {
4003 ConstantOffset += CVal.getSExtValue() * TypeSize;
4004 continue;
4005 }
4006 }
4007 if (TypeSize) { // Scales of zero don't do anything.
Chandler Carruthc8925912013-01-05 02:09:22 +00004008 // We only allow one variable index at the moment.
4009 if (VariableOperand != -1)
4010 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004011
Chandler Carruthc8925912013-01-05 02:09:22 +00004012 // Remember the variable index.
4013 VariableOperand = i;
4014 VariableScale = TypeSize;
4015 }
4016 }
4017 }
Stephen Lin837bba12013-07-15 17:55:02 +00004018
Chandler Carruthc8925912013-01-05 02:09:22 +00004019 // A common case is for the GEP to only do a constant offset. In this case,
4020 // just add it to the disp field and check validity.
4021 if (VariableOperand == -1) {
4022 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004023 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004024 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004025 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004026 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00004027 return true;
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004028 } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
4029 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
4030 ConstantOffset > 0) {
4031 // Record GEPs with non-zero offsets as candidates for splitting in the
4032 // event that the offset cannot fit into the r+i addressing mode.
4033 // Simple and common case that only one GEP is used in calculating the
4034 // address for the memory access.
4035 Value *Base = AddrInst->getOperand(0);
4036 auto *BaseI = dyn_cast<Instruction>(Base);
4037 auto *GEP = cast<GetElementPtrInst>(AddrInst);
4038 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
4039 (BaseI && !isa<CastInst>(BaseI) &&
4040 !isa<GetElementPtrInst>(BaseI))) {
4041 // If the base is an instruction, make sure the GEP is not in the same
4042 // basic block as the base. If the base is an argument or global
4043 // value, make sure the GEP is not in the entry block. Otherwise,
4044 // instruction selection can undo the split. Also make sure the
4045 // parent block allows inserting non-PHI instructions before the
4046 // terminator.
4047 BasicBlock *Parent =
4048 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
4049 if (GEP->getParent() != Parent && !Parent->getTerminator()->isEHPad())
4050 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
4051 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004052 }
4053 AddrMode.BaseOffs -= ConstantOffset;
4054 return false;
4055 }
4056
4057 // Save the valid addressing mode in case we can't match.
4058 ExtAddrMode BackupAddrMode = AddrMode;
4059 unsigned OldSize = AddrModeInsts.size();
4060
4061 // See if the scale and offset amount is valid for this target.
4062 AddrMode.BaseOffs += ConstantOffset;
4063
4064 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004065 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004066 // If it couldn't be matched, just stuff the value in a register.
4067 if (AddrMode.HasBaseReg) {
4068 AddrMode = BackupAddrMode;
4069 AddrModeInsts.resize(OldSize);
4070 return false;
4071 }
4072 AddrMode.HasBaseReg = true;
4073 AddrMode.BaseReg = AddrInst->getOperand(0);
4074 }
4075
4076 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004077 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00004078 Depth)) {
4079 // If it couldn't be matched, try stuffing the base into a register
4080 // instead of matching it, and retrying the match of the scale.
4081 AddrMode = BackupAddrMode;
4082 AddrModeInsts.resize(OldSize);
4083 if (AddrMode.HasBaseReg)
4084 return false;
4085 AddrMode.HasBaseReg = true;
4086 AddrMode.BaseReg = AddrInst->getOperand(0);
4087 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004088 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00004089 VariableScale, Depth)) {
4090 // If even that didn't work, bail.
4091 AddrMode = BackupAddrMode;
4092 AddrModeInsts.resize(OldSize);
4093 return false;
4094 }
4095 }
4096
4097 return true;
4098 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004099 case Instruction::SExt:
4100 case Instruction::ZExt: {
4101 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
4102 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00004103 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00004104
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004105 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004106 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004107 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004108 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004109 if (!TPH)
4110 return false;
4111
4112 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4113 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00004114 unsigned CreatedInstsCost = 0;
4115 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004116 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00004117 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004118 // SExt has been moved away.
4119 // Thus either it will be rematched later in the recursive calls or it is
4120 // gone. Anyway, we must not fold it into the addressing mode at this point.
4121 // E.g.,
4122 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004123 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004124 // addr = gep base, idx
4125 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004126 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004127 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
4128 // addr = gep base, op <- match
4129 if (MovedAway)
4130 *MovedAway = true;
4131
4132 assert(PromotedOperand &&
4133 "TypePromotionHelper should have filtered out those cases");
4134
4135 ExtAddrMode BackupAddrMode = AddrMode;
4136 unsigned OldSize = AddrModeInsts.size();
4137
Sanjay Patelfc580a62015-09-21 23:03:16 +00004138 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004139 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00004140 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004141 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00004142 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004143 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004144 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00004145 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004146 AddrMode = BackupAddrMode;
4147 AddrModeInsts.resize(OldSize);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004148 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004149 TPT.rollback(LastKnownGood);
4150 return false;
4151 }
4152 return true;
4153 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004154 }
4155 return false;
4156}
4157
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004158/// If we can, try to add the value of 'Addr' into the current addressing mode.
4159/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4160/// unmodified. This assumes that Addr is either a pointer type or intptr_t
4161/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00004162///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004163bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004164 // Start a transaction at this point that we will rollback if the matching
4165 // fails.
4166 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4167 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00004168 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4169 // Fold in immediates if legal for the target.
4170 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004171 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004172 return true;
4173 AddrMode.BaseOffs -= CI->getSExtValue();
4174 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4175 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00004176 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004177 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004178 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004179 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00004180 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004181 }
4182 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4183 ExtAddrMode BackupAddrMode = AddrMode;
4184 unsigned OldSize = AddrModeInsts.size();
4185
4186 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004187 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004188 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004189 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004190 // to check here.
4191 if (MovedAway)
4192 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004193 // Okay, it's possible to fold this. Check to see if it is actually
4194 // *profitable* to do so. We use a simple cost model to avoid increasing
4195 // register pressure too much.
4196 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00004197 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004198 AddrModeInsts.push_back(I);
4199 return true;
4200 }
Stephen Lin837bba12013-07-15 17:55:02 +00004201
Chandler Carruthc8925912013-01-05 02:09:22 +00004202 // It isn't profitable to do this, roll back.
4203 //cerr << "NOT FOLDING: " << *I;
4204 AddrMode = BackupAddrMode;
4205 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004206 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004207 }
4208 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00004209 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00004210 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004211 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004212 } else if (isa<ConstantPointerNull>(Addr)) {
4213 // Null pointer gets folded without affecting the addressing mode.
4214 return true;
4215 }
4216
4217 // Worse case, the target should support [reg] addressing modes. :)
4218 if (!AddrMode.HasBaseReg) {
4219 AddrMode.HasBaseReg = true;
4220 AddrMode.BaseReg = Addr;
4221 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004222 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004223 return true;
4224 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00004225 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004226 }
4227
4228 // If the base register is already taken, see if we can do [r+r].
4229 if (AddrMode.Scale == 0) {
4230 AddrMode.Scale = 1;
4231 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004232 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004233 return true;
4234 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00004235 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004236 }
4237 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004238 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004239 return false;
4240}
4241
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004242/// Check to see if all uses of OpVal by the specified inline asm call are due
4243/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00004244static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004245 const TargetLowering &TLI,
4246 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00004247 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00004248 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004249 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004250 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004251
Chandler Carruthc8925912013-01-05 02:09:22 +00004252 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4253 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00004254
Chandler Carruthc8925912013-01-05 02:09:22 +00004255 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004256 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00004257
4258 // If this asm operand is our Value*, and if it isn't an indirect memory
4259 // operand, we can't fold it!
4260 if (OpInfo.CallOperandVal == OpVal &&
4261 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4262 !OpInfo.isIndirect))
4263 return false;
4264 }
4265
4266 return true;
4267}
4268
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004269// Max number of memory uses to look at before aborting the search to conserve
4270// compile time.
4271static constexpr int MaxMemoryUsesToScan = 20;
4272
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004273/// Recursively walk all the uses of I until we find a memory use.
4274/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00004275/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00004276static bool FindAllMemoryUses(
4277 Instruction *I,
4278 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004279 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4280 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004281 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00004282 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00004283 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004284
Chandler Carruthc8925912013-01-05 02:09:22 +00004285 // If this is an obviously unfoldable instruction, bail out.
4286 if (!MightBeFoldableInst(I))
4287 return true;
4288
Philip Reamesac115ed2016-03-09 23:13:12 +00004289 const bool OptSize = I->getFunction()->optForSize();
4290
Chandler Carruthc8925912013-01-05 02:09:22 +00004291 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004292 for (Use &U : I->uses()) {
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004293 // Conservatively return true if we're seeing a large number or a deep chain
4294 // of users. This avoids excessive compilation times in pathological cases.
4295 if (SeenInsts++ >= MaxMemoryUsesToScan)
4296 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004297
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004298 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthcdf47882014-03-09 03:16:01 +00004299 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4300 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00004301 continue;
4302 }
Stephen Lin837bba12013-07-15 17:55:02 +00004303
Chandler Carruthcdf47882014-03-09 03:16:01 +00004304 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4305 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00004306 if (opNo != StoreInst::getPointerOperandIndex())
4307 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00004308 MemoryUses.push_back(std::make_pair(SI, opNo));
4309 continue;
4310 }
Stephen Lin837bba12013-07-15 17:55:02 +00004311
Matt Arsenault02d915b2017-03-15 22:35:20 +00004312 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4313 unsigned opNo = U.getOperandNo();
4314 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4315 return true; // Storing addr, not into addr.
4316 MemoryUses.push_back(std::make_pair(RMW, opNo));
4317 continue;
4318 }
4319
4320 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4321 unsigned opNo = U.getOperandNo();
4322 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4323 return true; // Storing addr, not into addr.
4324 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4325 continue;
4326 }
4327
Chandler Carruthcdf47882014-03-09 03:16:01 +00004328 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004329 // If this is a cold call, we can sink the addressing calculation into
4330 // the cold path. See optimizeCallInst
4331 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4332 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004333
Chandler Carruthc8925912013-01-05 02:09:22 +00004334 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4335 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004336
Chandler Carruthc8925912013-01-05 02:09:22 +00004337 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004338 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004339 return true;
4340 continue;
4341 }
Stephen Lin837bba12013-07-15 17:55:02 +00004342
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004343 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4344 SeenInsts))
Chandler Carruthc8925912013-01-05 02:09:22 +00004345 return true;
4346 }
4347
4348 return false;
4349}
4350
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004351/// Return true if Val is already known to be live at the use site that we're
4352/// folding it into. If so, there is no cost to include it in the addressing
4353/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4354/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004355bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004356 Value *KnownLive2) {
4357 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004358 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004359 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004360
Chandler Carruthc8925912013-01-05 02:09:22 +00004361 // All values other than instructions and arguments (e.g. constants) are live.
4362 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004363
Chandler Carruthc8925912013-01-05 02:09:22 +00004364 // If Val is a constant sized alloca in the entry block, it is live, this is
4365 // true because it is just a reference to the stack/frame pointer, which is
4366 // live for the whole function.
4367 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4368 if (AI->isStaticAlloca())
4369 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004370
Chandler Carruthc8925912013-01-05 02:09:22 +00004371 // Check to see if this value is already used in the memory instruction's
4372 // block. If so, it's already live into the block at the very least, so we
4373 // can reasonably fold it.
4374 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4375}
4376
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004377/// It is possible for the addressing mode of the machine to fold the specified
4378/// instruction into a load or store that ultimately uses it.
4379/// However, the specified instruction has multiple uses.
4380/// Given this, it may actually increase register pressure to fold it
4381/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004382///
4383/// X = ...
4384/// Y = X+1
4385/// use(Y) -> nonload/store
4386/// Z = Y+1
4387/// load Z
4388///
4389/// In this case, Y has multiple uses, and can be folded into the load of Z
4390/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4391/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4392/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4393/// number of computations either.
4394///
4395/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4396/// X was live across 'load Z' for other reasons, we actually *would* want to
4397/// fold the addressing mode in the Z case. This would make Y die earlier.
4398bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004399isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004400 ExtAddrMode &AMAfter) {
4401 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004402
Chandler Carruthc8925912013-01-05 02:09:22 +00004403 // AMBefore is the addressing mode before this instruction was folded into it,
4404 // and AMAfter is the addressing mode after the instruction was folded. Get
4405 // the set of registers referenced by AMAfter and subtract out those
4406 // referenced by AMBefore: this is the set of values which folding in this
4407 // address extends the lifetime of.
4408 //
4409 // Note that there are only two potential values being referenced here,
4410 // BaseReg and ScaleReg (global addresses are always available, as are any
4411 // folded immediates).
4412 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004413
Chandler Carruthc8925912013-01-05 02:09:22 +00004414 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4415 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004416 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004417 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004418 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004419 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004420
4421 // If folding this instruction (and it's subexprs) didn't extend any live
4422 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004423 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004424 return true;
4425
Philip Reamesac115ed2016-03-09 23:13:12 +00004426 // If all uses of this instruction can have the address mode sunk into them,
4427 // we can remove the addressing mode and effectively trade one live register
4428 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004429 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004430 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4431 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004432 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004433 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004434
Chandler Carruthc8925912013-01-05 02:09:22 +00004435 // Now that we know that all uses of this instruction are part of a chain of
4436 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004437 // into a memory use, loop over each of these memory operation uses and see
4438 // if they could *actually* fold the instruction. The assumption is that
4439 // addressing modes are cheap and that duplicating the computation involved
4440 // many times is worthwhile, even on a fastpath. For sinking candidates
4441 // (i.e. cold call sites), this serves as a way to prevent excessive code
4442 // growth since most architectures have some reasonable small and fast way to
4443 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004444 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4445 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4446 Instruction *User = MemoryUses[i].first;
4447 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004448
Chandler Carruthc8925912013-01-05 02:09:22 +00004449 // Get the access type of this use. If the use isn't a pointer, we don't
4450 // know what it accesses.
4451 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004452 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4453 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004454 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004455 Type *AddressAccessTy = AddrTy->getElementType();
4456 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004457
Chandler Carruthc8925912013-01-05 02:09:22 +00004458 // Do a match against the root of this address, ignoring profitability. This
4459 // will tell us if the addressing mode for the memory operation will
4460 // *actually* cover the shared instruction.
4461 ExtAddrMode Result;
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004462 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4463 0);
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004464 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4465 TPT.getRestorationPoint();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004466 AddressingModeMatcher Matcher(
4467 MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result,
4468 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Chandler Carruthc8925912013-01-05 02:09:22 +00004469 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004470 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004471 (void)Success; assert(Success && "Couldn't select *anything*?");
4472
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004473 // The match was to check the profitability, the changes made are not
4474 // part of the original matcher. Therefore, they should be dropped
4475 // otherwise the original matcher will not present the right state.
4476 TPT.rollback(LastKnownGood);
4477
Chandler Carruthc8925912013-01-05 02:09:22 +00004478 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004479 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004480 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004481
Chandler Carruthc8925912013-01-05 02:09:22 +00004482 MatchedAddrModeInsts.clear();
4483 }
Stephen Lin837bba12013-07-15 17:55:02 +00004484
Chandler Carruthc8925912013-01-05 02:09:22 +00004485 return true;
4486}
4487
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004488/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004489/// different basic block than BB.
4490static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4491 if (Instruction *I = dyn_cast<Instruction>(V))
4492 return I->getParent() != BB;
4493 return false;
4494}
4495
Philip Reamesac115ed2016-03-09 23:13:12 +00004496/// Sink addressing mode computation immediate before MemoryInst if doing so
4497/// can be done without increasing register pressure. The need for the
4498/// register pressure constraint means this can end up being an all or nothing
4499/// decision for all uses of the same addressing computation.
4500///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004501/// Load and Store Instructions often have addressing modes that can do
4502/// significant amounts of computation. As such, instruction selection will try
4503/// to get the load or store to do as much computation as possible for the
4504/// program. The problem is that isel can only see within a single block. As
4505/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004506///
4507/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004508/// operands. It's also used to sink addressing computations feeding into cold
4509/// call sites into their (cold) basic block.
4510///
4511/// The motivation for handling sinking into cold blocks is that doing so can
4512/// both enable other address mode sinking (by satisfying the register pressure
4513/// constraint above), and reduce register pressure globally (by removing the
4514/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004515bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004516 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004517 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004518
4519 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004520 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004521 SmallVector<Value*, 8> worklist;
4522 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004523 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004524
John Brawneb83c752017-10-03 13:04:15 +00004525 // Use a worklist to iteratively look through PHI and select nodes, and
4526 // ensure that the addressing mode obtained from the non-PHI/select roots of
John Brawn736bf002017-10-03 13:08:22 +00004527 // the graph are compatible.
John Brawneb83c752017-10-03 13:04:15 +00004528 bool PhiOrSelectSeen = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004529 SmallVector<Instruction*, 16> AddrModeInsts;
Serguei Katkovaee63752017-11-05 07:59:02 +00004530 const SimplifyQuery SQ(*DL, TLInfo);
Serguei Katkov2673f172018-11-29 06:45:18 +00004531 AddressingModeCombiner AddrModes(SQ, Addr);
Jun Bum Limdee55652017-04-03 19:20:07 +00004532 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004533 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4534 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004535 while (!worklist.empty()) {
4536 Value *V = worklist.back();
4537 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004538
Serguei Katkov4ea855e2017-07-19 04:49:17 +00004539 // We allow traversing cyclic Phi nodes.
4540 // In case of success after this loop we ensure that traversing through
4541 // Phi nodes ends up with all cases to compute address of the form
4542 // BaseGV + Base + Scale * Index + Offset
4543 // where Scale and Offset are constans and BaseGV, Base and Index
4544 // are exactly the same Values in all cases.
4545 // It means that BaseGV, Scale and Offset dominate our memory instruction
4546 // and have the same value as they had in address computation represented
4547 // as Phi. So we can safely sink address computation to memory instruction.
4548 if (!Visited.insert(V).second)
4549 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00004550
Owen Anderson8ba5f392010-11-27 08:15:55 +00004551 // For a PHI node, push all of its incoming values.
4552 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004553 for (Value *IncValue : P->incoming_values())
4554 worklist.push_back(IncValue);
John Brawneb83c752017-10-03 13:04:15 +00004555 PhiOrSelectSeen = true;
4556 continue;
4557 }
4558 // Similar for select.
4559 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4560 worklist.push_back(SI->getFalseValue());
4561 worklist.push_back(SI->getTrueValue());
4562 PhiOrSelectSeen = true;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004563 continue;
4564 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004565
Philip Reamesac115ed2016-03-09 23:13:12 +00004566 // For non-PHIs, determine the addressing mode being computed. Note that
4567 // the result may differ depending on what other uses our candidate
4568 // addressing instructions might have.
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004569 AddrModeInsts.clear();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004570 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4571 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004572 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004573 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004574 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004575
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004576 GetElementPtrInst *GEP = LargeOffsetGEP.first;
4577 if (GEP && GEP->getParent() != MemoryInst->getParent() &&
4578 !NewGEPBases.count(GEP)) {
4579 // If splitting the underlying data structure can reduce the offset of a
4580 // GEP, collect the GEP. Skip the GEPs that are the new bases of
4581 // previously split data structures.
4582 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
4583 if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
4584 LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
4585 }
4586
4587 NewAddrMode.OriginalValue = V;
John Brawn736bf002017-10-03 13:08:22 +00004588 if (!AddrModes.addNewAddrMode(NewAddrMode))
4589 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004590 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004591
John Brawn736bf002017-10-03 13:08:22 +00004592 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4593 // or we have multiple but either couldn't combine them or combining them
4594 // wouldn't do anything useful, bail out now.
4595 if (!AddrModes.combineAddrModes()) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004596 TPT.rollback(LastKnownGood);
4597 return false;
4598 }
4599 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004600
John Brawn736bf002017-10-03 13:08:22 +00004601 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4602 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4603
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004604 // If all the instructions matched are already in this BB, don't do anything.
John Brawneb83c752017-10-03 13:04:15 +00004605 // If we saw a Phi node then it is not local definitely, and if we saw a select
4606 // then we want to push the address calculation past it even if it's already
4607 // in this BB.
4608 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
Justin Lebar838c7f52016-11-21 22:49:11 +00004609 return IsNonLocalValue(V, MemoryInst->getParent());
Serguei Katkov0b7b59a2017-07-11 06:24:44 +00004610 })) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004611 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
4612 << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004613 return false;
4614 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004615
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004616 // Insert this computation right after this user. Since our caller is
4617 // scanning from the top of the BB to the bottom, reuse of the expr are
4618 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004619 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004620
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004621 // Now that we determined the addressing expression we want to use and know
4622 // that we have to sink it into this block. Check to see if we have already
Simon Dardis230f4532017-11-24 16:45:28 +00004623 // done this for some other load/store instr in this block. If so, reuse
4624 // the computation. Before attempting reuse, check if the address is valid
4625 // as it may have been erased.
4626
4627 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
4628
4629 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004630 if (SunkAddr) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004631 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
4632 << " for " << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004633 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004634 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004635 } else if (AddrSinkUsingGEPs ||
David Blaikie8ad9a972018-03-28 22:28:50 +00004636 (!AddrSinkUsingGEPs.getNumOccurrences() && TM && TTI->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004637 // By default, we use the GEP-based method when AA is used later. This
4638 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004639 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4640 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004641 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004642 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004643
4644 // First, find the pointer.
4645 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4646 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004647 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004648 }
4649
4650 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4651 // We can't add more than one pointer together, nor can we scale a
4652 // pointer (both of which seem meaningless).
4653 if (ResultPtr || AddrMode.Scale != 1)
4654 return false;
4655
4656 ResultPtr = AddrMode.ScaledReg;
4657 AddrMode.Scale = 0;
4658 }
4659
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004660 // It is only safe to sign extend the BaseReg if we know that the math
4661 // required to create it did not overflow before we extend it. Since
4662 // the original IR value was tossed in favor of a constant back when
4663 // the AddrMode was created we need to bail out gracefully if widths
4664 // do not match instead of extending it.
4665 //
4666 // (See below for code to add the scale.)
4667 if (AddrMode.Scale) {
4668 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4669 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4670 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4671 return false;
4672 }
4673
Hal Finkelc3998302014-04-12 00:59:48 +00004674 if (AddrMode.BaseGV) {
4675 if (ResultPtr)
4676 return false;
4677
4678 ResultPtr = AddrMode.BaseGV;
4679 }
4680
4681 // If the real base value actually came from an inttoptr, then the matcher
4682 // will look through it and provide only the integer value. In that case,
4683 // use it here.
Keno Fischer05e4ac22017-06-29 20:28:59 +00004684 if (!DL->isNonIntegralPointerType(Addr->getType())) {
4685 if (!ResultPtr && AddrMode.BaseReg) {
David L. Jonesd81f2302019-01-31 03:28:46 +00004686 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4687 "sunkaddr");
Keno Fischer05e4ac22017-06-29 20:28:59 +00004688 AddrMode.BaseReg = nullptr;
4689 } else if (!ResultPtr && AddrMode.Scale == 1) {
David L. Jonesd81f2302019-01-31 03:28:46 +00004690 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4691 "sunkaddr");
Keno Fischer05e4ac22017-06-29 20:28:59 +00004692 AddrMode.Scale = 0;
4693 }
Hal Finkelc3998302014-04-12 00:59:48 +00004694 }
4695
4696 if (!ResultPtr &&
4697 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4698 SunkAddr = Constant::getNullValue(Addr->getType());
4699 } else if (!ResultPtr) {
4700 return false;
4701 } else {
4702 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004703 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4704 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004705
4706 // Start with the base register. Do this first so that subsequent address
4707 // matching finds it last, which will prevent it from trying to match it
4708 // as the scaled value in case it happens to be a mul. That would be
4709 // problematic if we've sunk a different mul for the scale, because then
4710 // we'd end up sinking both muls.
4711 if (AddrMode.BaseReg) {
4712 Value *V = AddrMode.BaseReg;
4713 if (V->getType() != IntPtrTy)
4714 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4715
4716 ResultIndex = V;
4717 }
4718
4719 // Add the scale value.
4720 if (AddrMode.Scale) {
4721 Value *V = AddrMode.ScaledReg;
4722 if (V->getType() == IntPtrTy) {
4723 // done.
Hal Finkelc3998302014-04-12 00:59:48 +00004724 } else {
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004725 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4726 cast<IntegerType>(V->getType())->getBitWidth() &&
4727 "We can't transform if ScaledReg is too narrow");
4728 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004729 }
4730
4731 if (AddrMode.Scale != 1)
4732 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4733 "sunkaddr");
4734 if (ResultIndex)
4735 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4736 else
4737 ResultIndex = V;
4738 }
4739
4740 // Add in the Base Offset if present.
4741 if (AddrMode.BaseOffs) {
4742 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4743 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004744 // We need to add this separately from the scale above to help with
4745 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004746 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004747 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004748 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004749 }
4750
4751 ResultIndex = V;
4752 }
4753
4754 if (!ResultIndex) {
4755 SunkAddr = ResultPtr;
4756 } else {
4757 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004758 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004759 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004760 }
4761
4762 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004763 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004764 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004765 } else {
Keno Fischer05e4ac22017-06-29 20:28:59 +00004766 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4767 // non-integral pointers, so in that case bail out now.
4768 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4769 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4770 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4771 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4772 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4773 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4774 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4775 (AddrMode.BaseGV &&
4776 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4777 return false;
4778
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004779 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4780 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004781 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004782 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004783
4784 // Start with the base register. Do this first so that subsequent address
4785 // matching finds it last, which will prevent it from trying to match it
4786 // as the scaled value in case it happens to be a mul. That would be
4787 // problematic if we've sunk a different mul for the scale, because then
4788 // we'd end up sinking both muls.
4789 if (AddrMode.BaseReg) {
4790 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004791 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004792 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004793 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004794 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004795 Result = V;
4796 }
4797
4798 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004799 if (AddrMode.Scale) {
4800 Value *V = AddrMode.ScaledReg;
4801 if (V->getType() == IntPtrTy) {
4802 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004803 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004804 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004805 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4806 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004807 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004808 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004809 // It is only safe to sign extend the BaseReg if we know that the math
4810 // required to create it did not overflow before we extend it. Since
4811 // the original IR value was tossed in favor of a constant back when
4812 // the AddrMode was created we need to bail out gracefully if widths
4813 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004814 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004815 if (I && (Result != AddrMode.BaseReg))
4816 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004817 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004818 }
4819 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004820 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4821 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004822 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004823 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004824 else
4825 Result = V;
4826 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004827
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004828 // Add in the BaseGV if present.
4829 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004830 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004831 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004832 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004833 else
4834 Result = V;
4835 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004836
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004837 // Add in the Base Offset if present.
4838 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004839 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004840 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004841 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004842 else
4843 Result = V;
4844 }
4845
Craig Topperc0196b12014-04-14 00:51:57 +00004846 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004847 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004848 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004849 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004850 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004851
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004852 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Simon Dardis230f4532017-11-24 16:45:28 +00004853 // Store the newly computed address into the cache. In the case we reused a
4854 // value, this should be idempotent.
4855 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004856
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004857 // If we have no uses, recursively delete the value and all dead instructions
4858 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004859 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004860 // This can cause recursive deletion, which can invalidate our iterator.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004861 // Use a WeakTrackingVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004862 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004863 WeakTrackingVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004864 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004865
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004866 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004867
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004868 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004869 // If the iterator instruction was recursively deleted, start over at the
4870 // start of the block.
4871 CurInstIterator = BB->begin();
4872 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004873 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004874 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004875 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004876 return true;
4877}
4878
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004879/// If there are any memory operands, use OptimizeMemoryInst to sink their
4880/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004881bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004882 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004883
Eric Christopher11e4df72015-02-26 22:38:43 +00004884 const TargetRegisterInfo *TRI =
Sanjay Patel4137d512017-06-07 14:29:52 +00004885 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004886 TargetLowering::AsmOperandInfoVector TargetConstraints =
4887 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004888 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004889 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4890 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004891
Evan Cheng1da25002008-02-26 02:42:37 +00004892 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004893 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004894
Eli Friedman666bbe32008-02-26 18:37:49 +00004895 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4896 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004897 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004898 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004899 } else if (OpInfo.Type == InlineAsm::isInput)
4900 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004901 }
4902
4903 return MadeChange;
4904}
4905
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004906/// Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004907/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00004908static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4909 assert(!Val->use_empty() && "Input must have at least one use");
4910 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004911 bool IsSExt = isa<SExtInst>(FirstUser);
4912 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00004913 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004914 const Instruction *UI = cast<Instruction>(U);
4915 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4916 return false;
4917 Type *CurTy = UI->getType();
4918 // Same input and output types: Same instruction after CSE.
4919 if (CurTy == ExtTy)
4920 continue;
4921
4922 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00004923 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004924 // b = sext ty1 a to ty2
4925 // c = sext ty1 a to ty3
4926 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00004927 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004928 // b = sext ty1 a to ty2
4929 // c = sext ty2 b to ty3
4930 // However, the last sext is not free.
4931 if (IsSExt)
4932 return false;
4933
4934 // This is a ZExt, maybe this is free to extend from one type to another.
4935 // In that case, we would not account for a different use.
4936 Type *NarrowTy;
4937 Type *LargeTy;
4938 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4939 CurTy->getScalarType()->getIntegerBitWidth()) {
4940 NarrowTy = CurTy;
4941 LargeTy = ExtTy;
4942 } else {
4943 NarrowTy = ExtTy;
4944 LargeTy = CurTy;
4945 }
4946
4947 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4948 return false;
4949 }
4950 // All uses are the same or can be derived from one another for free.
4951 return true;
4952}
4953
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004954/// Try to speculatively promote extensions in \p Exts and continue
Jun Bum Lim42301012017-03-17 19:05:21 +00004955/// promoting through newly promoted operands recursively as far as doing so is
4956/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4957/// When some promotion happened, \p TPT contains the proper state to revert
4958/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004959///
Jun Bum Lim42301012017-03-17 19:05:21 +00004960/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00004961bool CodeGenPrepare::tryToPromoteExts(
4962 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4963 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4964 unsigned CreatedInstsCost) {
4965 bool Promoted = false;
4966
4967 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004968 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004969 // Early check if we directly have ext(load).
4970 if (isa<LoadInst>(I->getOperand(0))) {
4971 ProfitablyMovedExts.push_back(I);
4972 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004973 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004974
4975 // Check whether or not we want to do any promotion. The reason we have
4976 // this check inside the for loop is to catch the case where an extension
4977 // is directly fed by a load because in such case the extension can be moved
4978 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004979 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00004980 return false;
4981
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004982 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00004983 TypePromotionHelper::Action TPH =
4984 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004985 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00004986 if (!TPH) {
4987 // Save the current extension as we cannot move up through its operand.
4988 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004989 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00004990 }
4991
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004992 // Save the current state.
4993 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4994 TPT.getRestorationPoint();
4995 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004996 unsigned NewCreatedInstsCost = 0;
4997 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004998 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004999 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
5000 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005001 assert(PromotedVal &&
5002 "TypePromotionHelper should have filtered out those cases");
5003
5004 // We would be able to merge only one extension in a load.
5005 // Therefore, if we have more than 1 new extension we heuristically
5006 // cut this search path, because it means we degrade the code quality.
5007 // With exactly 2, the transformation is neutral, because we will merge
5008 // one extension but leave one. However, we optimistically keep going,
5009 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00005010 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00005011 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00005012 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00005013 TotalCreatedInstsCost =
5014 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005015 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00005016 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00005017 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00005018 // This promotion is not profitable, rollback to the previous state, and
5019 // save the current extension in ProfitablyMovedExts as the latest
5020 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005021 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00005022 ProfitablyMovedExts.push_back(I);
5023 continue;
5024 }
5025 // Continue promoting NewExts as far as doing so is profitable.
5026 SmallVector<Instruction *, 2> NewlyMovedExts;
5027 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
5028 bool NewPromoted = false;
5029 for (auto ExtInst : NewlyMovedExts) {
5030 Instruction *MovedExt = cast<Instruction>(ExtInst);
5031 Value *ExtOperand = MovedExt->getOperand(0);
5032 // If we have reached to a load, we need this extra profitability check
5033 // as it could potentially be merged into an ext(load).
5034 if (isa<LoadInst>(ExtOperand) &&
5035 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
5036 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
5037 continue;
5038
5039 ProfitablyMovedExts.push_back(MovedExt);
5040 NewPromoted = true;
5041 }
5042
5043 // If none of speculative promotions for NewExts is profitable, rollback
5044 // and save the current extension (I) as the last profitable extension.
5045 if (!NewPromoted) {
5046 TPT.rollback(LastKnownGood);
5047 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005048 continue;
5049 }
5050 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00005051 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005052 }
Jun Bum Lim42301012017-03-17 19:05:21 +00005053 return Promoted;
5054}
5055
Jun Bum Limdee55652017-04-03 19:20:07 +00005056/// Merging redundant sexts when one is dominating the other.
5057bool CodeGenPrepare::mergeSExts(Function &F) {
5058 DominatorTree DT(F);
5059 bool Changed = false;
5060 for (auto &Entry : ValToSExtendedUses) {
5061 SExts &Insts = Entry.second;
5062 SExts CurPts;
5063 for (Instruction *Inst : Insts) {
5064 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
5065 Inst->getOperand(0) != Entry.first)
5066 continue;
5067 bool inserted = false;
5068 for (auto &Pt : CurPts) {
5069 if (DT.dominates(Inst, Pt)) {
5070 Pt->replaceAllUsesWith(Inst);
5071 RemovedInsts.insert(Pt);
5072 Pt->removeFromParent();
5073 Pt = Inst;
5074 inserted = true;
5075 Changed = true;
5076 break;
5077 }
5078 if (!DT.dominates(Pt, Inst))
5079 // Give up if we need to merge in a common dominator as the
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00005080 // experiments show it is not profitable.
Jun Bum Limdee55652017-04-03 19:20:07 +00005081 continue;
5082 Inst->replaceAllUsesWith(Pt);
5083 RemovedInsts.insert(Inst);
5084 Inst->removeFromParent();
5085 inserted = true;
5086 Changed = true;
5087 break;
5088 }
5089 if (!inserted)
5090 CurPts.push_back(Inst);
5091 }
5092 }
5093 return Changed;
5094}
5095
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005096// Spliting large data structures so that the GEPs accessing them can have
5097// smaller offsets so that they can be sunk to the same blocks as their users.
5098// For example, a large struct starting from %base is splitted into two parts
5099// where the second part starts from %new_base.
5100//
5101// Before:
5102// BB0:
5103// %base =
5104//
5105// BB1:
5106// %gep0 = gep %base, off0
5107// %gep1 = gep %base, off1
5108// %gep2 = gep %base, off2
5109//
5110// BB2:
5111// %load1 = load %gep0
5112// %load2 = load %gep1
5113// %load3 = load %gep2
5114//
5115// After:
5116// BB0:
5117// %base =
5118// %new_base = gep %base, off0
5119//
5120// BB1:
5121// %new_gep0 = %new_base
5122// %new_gep1 = gep %new_base, off1 - off0
5123// %new_gep2 = gep %new_base, off2 - off0
5124//
5125// BB2:
5126// %load1 = load i32, i32* %new_gep0
5127// %load2 = load i32, i32* %new_gep1
5128// %load3 = load i32, i32* %new_gep2
5129//
5130// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
5131// their offsets are smaller enough to fit into the addressing mode.
5132bool CodeGenPrepare::splitLargeGEPOffsets() {
5133 bool Changed = false;
5134 for (auto &Entry : LargeOffsetGEPMap) {
5135 Value *OldBase = Entry.first;
5136 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
5137 &LargeOffsetGEPs = Entry.second;
5138 auto compareGEPOffset =
5139 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
5140 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
5141 if (LHS.first == RHS.first)
5142 return false;
5143 if (LHS.second != RHS.second)
5144 return LHS.second < RHS.second;
5145 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
5146 };
5147 // Sorting all the GEPs of the same data structures based on the offsets.
Fangrui Song0cac7262018-09-27 02:13:45 +00005148 llvm::sort(LargeOffsetGEPs, compareGEPOffset);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005149 LargeOffsetGEPs.erase(
5150 std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()),
5151 LargeOffsetGEPs.end());
5152 // Skip if all the GEPs have the same offsets.
5153 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
5154 continue;
5155 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
5156 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
5157 Value *NewBaseGEP = nullptr;
5158
5159 auto LargeOffsetGEP = LargeOffsetGEPs.begin();
5160 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
5161 GetElementPtrInst *GEP = LargeOffsetGEP->first;
5162 int64_t Offset = LargeOffsetGEP->second;
5163 if (Offset != BaseOffset) {
5164 TargetLowering::AddrMode AddrMode;
5165 AddrMode.BaseOffs = Offset - BaseOffset;
5166 // The result type of the GEP might not be the type of the memory
5167 // access.
5168 if (!TLI->isLegalAddressingMode(*DL, AddrMode,
5169 GEP->getResultElementType(),
5170 GEP->getAddressSpace())) {
5171 // We need to create a new base if the offset to the current base is
5172 // too large to fit into the addressing mode. So, a very large struct
5173 // may be splitted into several parts.
5174 BaseGEP = GEP;
5175 BaseOffset = Offset;
5176 NewBaseGEP = nullptr;
5177 }
5178 }
5179
5180 // Generate a new GEP to replace the current one.
Eli Friedmana69084f2018-12-19 22:52:04 +00005181 LLVMContext &Ctx = GEP->getContext();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005182 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
5183 Type *I8PtrTy =
Eli Friedmana69084f2018-12-19 22:52:04 +00005184 Type::getInt8PtrTy(Ctx, GEP->getType()->getPointerAddressSpace());
5185 Type *I8Ty = Type::getInt8Ty(Ctx);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005186
5187 if (!NewBaseGEP) {
5188 // Create a new base if we don't have one yet. Find the insertion
5189 // pointer for the new base first.
5190 BasicBlock::iterator NewBaseInsertPt;
5191 BasicBlock *NewBaseInsertBB;
5192 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
5193 // If the base of the struct is an instruction, the new base will be
5194 // inserted close to it.
5195 NewBaseInsertBB = BaseI->getParent();
5196 if (isa<PHINode>(BaseI))
5197 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5198 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
5199 NewBaseInsertBB =
5200 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
5201 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5202 } else
5203 NewBaseInsertPt = std::next(BaseI->getIterator());
5204 } else {
5205 // If the current base is an argument or global value, the new base
5206 // will be inserted to the entry block.
5207 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
5208 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5209 }
5210 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
5211 // Create a new base.
5212 Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset);
5213 NewBaseGEP = OldBase;
5214 if (NewBaseGEP->getType() != I8PtrTy)
5215 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
5216 NewBaseGEP =
5217 NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep");
5218 NewGEPBases.insert(NewBaseGEP);
5219 }
5220
Eli Friedmana69084f2018-12-19 22:52:04 +00005221 IRBuilder<> Builder(GEP);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005222 Value *NewGEP = NewBaseGEP;
5223 if (Offset == BaseOffset) {
5224 if (GEP->getType() != I8PtrTy)
5225 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5226 } else {
5227 // Calculate the new offset for the new GEP.
5228 Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset);
5229 NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index);
5230
5231 if (GEP->getType() != I8PtrTy)
5232 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5233 }
5234 GEP->replaceAllUsesWith(NewGEP);
5235 LargeOffsetGEPID.erase(GEP);
5236 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
5237 GEP->eraseFromParent();
5238 Changed = true;
5239 }
5240 }
5241 return Changed;
5242}
5243
Jun Bum Lim42301012017-03-17 19:05:21 +00005244/// Return true, if an ext(load) can be formed from an extension in
5245/// \p MovedExts.
5246bool CodeGenPrepare::canFormExtLd(
5247 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
5248 Instruction *&Inst, bool HasPromoted) {
5249 for (auto *MovedExtInst : MovedExts) {
5250 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
5251 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
5252 Inst = MovedExtInst;
5253 break;
5254 }
5255 }
5256 if (!LI)
5257 return false;
5258
5259 // If they're already in the same block, there's nothing to do.
5260 // Make the cheap checks first if we did not promote.
5261 // If we promoted, we need to check if it is indeed profitable.
5262 if (!HasPromoted && LI->getParent() == Inst->getParent())
5263 return false;
5264
Haicheng Wuabdef9e2017-07-15 02:12:16 +00005265 return TLI->isExtLoad(LI, Inst, *DL);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005266}
5267
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005268/// Move a zext or sext fed by a load into the same basic block as the load,
5269/// unless conditions are unfavorable. This allows SelectionDAG to fold the
5270/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00005271///
Jun Bum Limdee55652017-04-03 19:20:07 +00005272/// E.g.,
5273/// \code
5274/// %ld = load i32* %addr
5275/// %add = add nuw i32 %ld, 4
5276/// %zext = zext i32 %add to i64
5277// \endcode
5278/// =>
5279/// \code
5280/// %ld = load i32* %addr
5281/// %zext = zext i32 %ld to i64
5282/// %add = add nuw i64 %zext, 4
5283/// \encode
5284/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
5285/// allow us to match zext(load i32*) to i64.
5286///
5287/// Also, try to promote the computations used to obtain a sign extended
5288/// value used into memory accesses.
5289/// E.g.,
5290/// \code
5291/// a = add nsw i32 b, 3
5292/// d = sext i32 a to i64
5293/// e = getelementptr ..., i64 d
5294/// \endcode
5295/// =>
5296/// \code
5297/// f = sext i32 b to i64
5298/// a = add nsw i64 f, 3
5299/// e = getelementptr ..., i64 a
5300/// \endcode
5301///
5302/// \p Inst[in/out] the extension may be modified during the process if some
5303/// promotions apply.
5304bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
5305 // ExtLoad formation and address type promotion infrastructure requires TLI to
5306 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00005307 if (!TLI)
5308 return false;
5309
Jun Bum Limdee55652017-04-03 19:20:07 +00005310 bool AllowPromotionWithoutCommonHeader = false;
5311 /// See if it is an interesting sext operations for the address type
5312 /// promotion before trying to promote it, e.g., the ones with the right
5313 /// type and used in memory accesses.
5314 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
5315 *Inst, AllowPromotionWithoutCommonHeader);
5316 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005317 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00005318 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005319 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00005320 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
5321 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00005322
Jun Bum Limdee55652017-04-03 19:20:07 +00005323 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00005324
Dan Gohman99429a02009-10-16 20:59:35 +00005325 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005326 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00005327 Instruction *ExtFedByLoad;
5328
5329 // Try to promote a chain of computation if it allows to form an extended
5330 // load.
5331 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
5332 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
5333 TPT.commit();
5334 // Move the extend into the same block as the load
Sanjay Patel674d2c22017-08-29 14:07:48 +00005335 ExtFedByLoad->moveAfter(LI);
Jun Bum Limdee55652017-04-03 19:20:07 +00005336 // CGP does not check if the zext would be speculatively executed when moved
5337 // to the same basic block as the load. Preserving its original location
5338 // would pessimize the debugging experience, as well as negatively impact
5339 // the quality of sample pgo. We don't want to use "line 0" as that has a
5340 // size cost in the line-table section and logically the zext can be seen as
5341 // part of the load. Therefore we conservatively reuse the same debug
5342 // location for the load and the zext.
5343 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
5344 ++NumExtsMoved;
5345 Inst = ExtFedByLoad;
5346 return true;
5347 }
5348
5349 // Continue promoting SExts if known as considerable depending on targets.
5350 if (ATPConsiderable &&
5351 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
5352 HasPromoted, TPT, SpeculativelyMovedExts))
5353 return true;
5354
5355 TPT.rollback(LastKnownGood);
5356 return false;
5357}
5358
5359// Perform address type promotion if doing so is profitable.
5360// If AllowPromotionWithoutCommonHeader == false, we should find other sext
5361// instructions that sign extended the same initial value. However, if
5362// AllowPromotionWithoutCommonHeader == true, we expect promoting the
5363// extension is just profitable.
5364bool CodeGenPrepare::performAddressTypePromotion(
5365 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
5366 bool HasPromoted, TypePromotionTransaction &TPT,
5367 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
5368 bool Promoted = false;
5369 SmallPtrSet<Instruction *, 1> UnhandledExts;
5370 bool AllSeenFirst = true;
5371 for (auto I : SpeculativelyMovedExts) {
5372 Value *HeadOfChain = I->getOperand(0);
5373 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
5374 SeenChainsForSExt.find(HeadOfChain);
5375 // If there is an unhandled SExt which has the same header, try to promote
5376 // it as well.
5377 if (AlreadySeen != SeenChainsForSExt.end()) {
5378 if (AlreadySeen->second != nullptr)
5379 UnhandledExts.insert(AlreadySeen->second);
5380 AllSeenFirst = false;
5381 }
5382 }
5383
5384 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
5385 SpeculativelyMovedExts.size() == 1)) {
5386 TPT.commit();
5387 if (HasPromoted)
5388 Promoted = true;
5389 for (auto I : SpeculativelyMovedExts) {
5390 Value *HeadOfChain = I->getOperand(0);
5391 SeenChainsForSExt[HeadOfChain] = nullptr;
5392 ValToSExtendedUses[HeadOfChain].push_back(I);
5393 }
5394 // Update Inst as promotion happen.
5395 Inst = SpeculativelyMovedExts.pop_back_val();
5396 } else {
5397 // This is the first chain visited from the header, keep the current chain
5398 // as unhandled. Defer to promote this until we encounter another SExt
5399 // chain derived from the same header.
5400 for (auto I : SpeculativelyMovedExts) {
5401 Value *HeadOfChain = I->getOperand(0);
5402 SeenChainsForSExt[HeadOfChain] = Inst;
5403 }
Dan Gohman99429a02009-10-16 20:59:35 +00005404 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005405 }
Dan Gohman99429a02009-10-16 20:59:35 +00005406
Jun Bum Limdee55652017-04-03 19:20:07 +00005407 if (!AllSeenFirst && !UnhandledExts.empty())
5408 for (auto VisitedSExt : UnhandledExts) {
5409 if (RemovedInsts.count(VisitedSExt))
5410 continue;
5411 TypePromotionTransaction TPT(RemovedInsts);
5412 SmallVector<Instruction *, 1> Exts;
5413 SmallVector<Instruction *, 2> Chains;
5414 Exts.push_back(VisitedSExt);
5415 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
5416 TPT.commit();
5417 if (HasPromoted)
5418 Promoted = true;
5419 for (auto I : Chains) {
5420 Value *HeadOfChain = I->getOperand(0);
5421 // Mark this as handled.
5422 SeenChainsForSExt[HeadOfChain] = nullptr;
5423 ValToSExtendedUses[HeadOfChain].push_back(I);
5424 }
5425 }
5426 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00005427}
5428
Sanjay Patelfc580a62015-09-21 23:03:16 +00005429bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00005430 BasicBlock *DefBB = I->getParent();
5431
Bob Wilsonff714f92010-09-21 21:44:14 +00005432 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00005433 // other uses of the source with result of extension.
5434 Value *Src = I->getOperand(0);
5435 if (Src->hasOneUse())
5436 return false;
5437
Evan Cheng2011df42007-12-13 07:50:36 +00005438 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00005439 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00005440 return false;
5441
Evan Cheng7bc89422007-12-12 00:51:06 +00005442 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00005443 // this block.
5444 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00005445 return false;
5446
Evan Chengd3d80172007-12-05 23:58:20 +00005447 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005448 for (User *U : I->users()) {
5449 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00005450
5451 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005452 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00005453 if (UserBB == DefBB) continue;
5454 DefIsLiveOut = true;
5455 break;
5456 }
5457 if (!DefIsLiveOut)
5458 return false;
5459
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00005460 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005461 for (User *U : Src->users()) {
5462 Instruction *UI = cast<Instruction>(U);
5463 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00005464 if (UserBB == DefBB) continue;
5465 // Be conservative. We don't want this xform to end up introducing
5466 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005467 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00005468 return false;
5469 }
5470
Evan Chengd3d80172007-12-05 23:58:20 +00005471 // InsertedTruncs - Only insert one trunc in each block once.
5472 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5473
5474 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005475 for (Use &U : Src->uses()) {
5476 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00005477
5478 // Figure out which BB this ext is used in.
5479 BasicBlock *UserBB = User->getParent();
5480 if (UserBB == DefBB) continue;
5481
5482 // Both src and def are live in this block. Rewrite the use.
5483 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5484
5485 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00005486 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005487 assert(InsertPt != UserBB->end());
5488 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005489 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00005490 }
5491
5492 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005493 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00005494 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00005495 MadeChange = true;
5496 }
5497
5498 return MadeChange;
5499}
5500
Geoff Berry5256fca2015-11-20 22:34:39 +00005501// Find loads whose uses only use some of the loaded value's bits. Add an "and"
5502// just after the load if the target can fold this into one extload instruction,
5503// with the hope of eliminating some of the other later "and" instructions using
5504// the loaded value. "and"s that are made trivially redundant by the insertion
5505// of the new "and" are removed by this function, while others (e.g. those whose
5506// path from the load goes through a phi) are left for isel to potentially
5507// remove.
5508//
5509// For example:
5510//
5511// b0:
5512// x = load i32
5513// ...
5514// b1:
5515// y = and x, 0xff
5516// z = use y
5517//
5518// becomes:
5519//
5520// b0:
5521// x = load i32
5522// x' = and x, 0xff
5523// ...
5524// b1:
5525// z = use x'
5526//
5527// whereas:
5528//
5529// b0:
5530// x1 = load i32
5531// ...
5532// b1:
5533// x2 = load i32
5534// ...
5535// b2:
5536// x = phi x1, x2
5537// y = and x, 0xff
5538//
5539// becomes (after a call to optimizeLoadExt for each load):
5540//
5541// b0:
5542// x1 = load i32
5543// x1' = and x1, 0xff
5544// ...
5545// b1:
5546// x2 = load i32
5547// x2' = and x2, 0xff
5548// ...
5549// b2:
5550// x = phi x1', x2'
5551// y = and x, 0xff
Geoff Berry5256fca2015-11-20 22:34:39 +00005552bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
Vedant Kumarb3091da2018-07-06 20:17:42 +00005553 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
Geoff Berry5256fca2015-11-20 22:34:39 +00005554 return false;
5555
Geoff Berry5d534b62017-02-21 18:53:14 +00005556 // Skip loads we've already transformed.
5557 if (Load->hasOneUse() &&
5558 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5559 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005560
5561 // Look at all uses of Load, looking through phis, to determine how many bits
5562 // of the loaded value are needed.
5563 SmallVector<Instruction *, 8> WorkList;
5564 SmallPtrSet<Instruction *, 16> Visited;
5565 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5566 for (auto *U : Load->users())
5567 WorkList.push_back(cast<Instruction>(U));
5568
5569 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5570 unsigned BitWidth = LoadResultVT.getSizeInBits();
5571 APInt DemandBits(BitWidth, 0);
5572 APInt WidestAndBits(BitWidth, 0);
5573
5574 while (!WorkList.empty()) {
5575 Instruction *I = WorkList.back();
5576 WorkList.pop_back();
5577
5578 // Break use-def graph loops.
5579 if (!Visited.insert(I).second)
5580 continue;
5581
5582 // For a PHI node, push all of its users.
5583 if (auto *Phi = dyn_cast<PHINode>(I)) {
5584 for (auto *U : Phi->users())
5585 WorkList.push_back(cast<Instruction>(U));
5586 continue;
5587 }
5588
5589 switch (I->getOpcode()) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005590 case Instruction::And: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005591 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5592 if (!AndC)
5593 return false;
5594 APInt AndBits = AndC->getValue();
5595 DemandBits |= AndBits;
5596 // Keep track of the widest and mask we see.
5597 if (AndBits.ugt(WidestAndBits))
5598 WidestAndBits = AndBits;
5599 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5600 AndsToMaybeRemove.push_back(I);
5601 break;
5602 }
5603
Eugene Zelenko900b6332017-08-29 22:32:07 +00005604 case Instruction::Shl: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005605 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5606 if (!ShlC)
5607 return false;
5608 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00005609 DemandBits.setLowBits(BitWidth - ShiftAmt);
Geoff Berry5256fca2015-11-20 22:34:39 +00005610 break;
5611 }
5612
Eugene Zelenko900b6332017-08-29 22:32:07 +00005613 case Instruction::Trunc: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005614 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5615 unsigned TruncBitWidth = TruncVT.getSizeInBits();
Craig Topperfc947bc2017-04-18 17:14:21 +00005616 DemandBits.setLowBits(TruncBitWidth);
Geoff Berry5256fca2015-11-20 22:34:39 +00005617 break;
5618 }
5619
5620 default:
5621 return false;
5622 }
5623 }
5624
5625 uint32_t ActiveBits = DemandBits.getActiveBits();
5626 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5627 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5628 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5629 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5630 // followed by an AND.
5631 // TODO: Look into removing this restriction by fixing backends to either
5632 // return false for isLoadExtLegal for i1 or have them select this pattern to
5633 // a single instruction.
5634 //
5635 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5636 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005637 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005638 WidestAndBits != DemandBits)
5639 return false;
5640
5641 LLVMContext &Ctx = Load->getType()->getContext();
5642 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5643 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5644
5645 // Reject cases that won't be matched as extloads.
5646 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5647 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5648 return false;
5649
5650 IRBuilder<> Builder(Load->getNextNode());
5651 auto *NewAnd = dyn_cast<Instruction>(
5652 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005653 // Mark this instruction as "inserted by CGP", so that other
5654 // optimizations don't touch it.
5655 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005656
5657 // Replace all uses of load with new and (except for the use of load in the
5658 // new and itself).
5659 Load->replaceAllUsesWith(NewAnd);
5660 NewAnd->setOperand(0, Load);
5661
5662 // Remove any and instructions that are now redundant.
5663 for (auto *And : AndsToMaybeRemove)
5664 // Check that the and mask is the same as the one we decided to put on the
5665 // new and.
5666 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5667 And->replaceAllUsesWith(NewAnd);
5668 if (&*CurInstIterator == And)
5669 CurInstIterator = std::next(And->getIterator());
5670 And->eraseFromParent();
5671 ++NumAndUses;
5672 }
5673
5674 ++NumAndsAdded;
5675 return true;
5676}
5677
Sanjay Patel69a50a12015-10-19 21:59:12 +00005678/// Check if V (an operand of a select instruction) is an expensive instruction
5679/// that is only used once.
5680static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5681 auto *I = dyn_cast<Instruction>(V);
5682 // If it's safe to speculatively execute, then it should not have side
5683 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005684 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5685 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005686}
5687
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005688/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005689static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005690 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005691 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005692 // If even a predictable select is cheap, then a branch can't be cheaper.
5693 if (!TLI->isPredictableSelectExpensive())
5694 return false;
5695
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005696 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005697 // whether a select is better represented as a branch.
5698
5699 // If metadata tells us that the select condition is obviously predictable,
5700 // then we want to replace the select with a branch.
5701 uint64_t TrueWeight, FalseWeight;
5702 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5703 uint64_t Max = std::max(TrueWeight, FalseWeight);
5704 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005705 if (Sum != 0) {
5706 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5707 if (Probability > TLI->getPredictableBranchThreshold())
5708 return true;
5709 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005710 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005711
5712 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5713
Sanjay Patel4e652762015-09-28 22:14:51 +00005714 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5715 // comparison condition. If the compare has more than one use, there's
5716 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005717 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005718 return false;
5719
Sanjay Patel69a50a12015-10-19 21:59:12 +00005720 // If either operand of the select is expensive and only needed on one side
5721 // of the select, we should form a branch.
5722 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5723 sinkSelectOperand(TTI, SI->getFalseValue()))
5724 return true;
5725
5726 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005727}
5728
Dehao Chen9bbb9412016-09-12 20:23:28 +00005729/// If \p isTrue is true, return the true value of \p SI, otherwise return
5730/// false value of \p SI. If the true/false value of \p SI is defined by any
5731/// select instructions in \p Selects, look through the defining select
5732/// instruction until the true/false value is not defined in \p Selects.
5733static Value *getTrueOrFalseValue(
5734 SelectInst *SI, bool isTrue,
5735 const SmallPtrSet<const Instruction *, 2> &Selects) {
5736 Value *V;
5737
5738 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5739 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005740 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005741 "The condition of DefSI does not match with SI");
5742 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5743 }
5744 return V;
5745}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005746
Nadav Rotem9d832022012-09-02 12:10:19 +00005747/// If we have a SelectInst that will likely profit from branch prediction,
5748/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005749bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Vedant Kumarfbc38732018-08-21 23:42:23 +00005750 // If branch conversion isn't desirable, exit early.
5751 if (DisableSelectToBranch || OptSize || !TLI)
5752 return false;
5753
Dehao Chen9bbb9412016-09-12 20:23:28 +00005754 // Find all consecutive select instructions that share the same condition.
5755 SmallVector<SelectInst *, 2> ASI;
5756 ASI.push_back(SI);
David Blaikie7d306532018-08-28 00:55:19 +00005757 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5758 It != SI->getParent()->end(); ++It) {
5759 SelectInst *I = dyn_cast<SelectInst>(&*It);
Dehao Chen9bbb9412016-09-12 20:23:28 +00005760 if (I && SI->getCondition() == I->getCondition()) {
5761 ASI.push_back(I);
5762 } else {
5763 break;
5764 }
5765 }
5766
5767 SelectInst *LastSI = ASI.back();
5768 // Increment the current iterator to skip all the rest of select instructions
5769 // because they will be either "not lowered" or "all lowered" to branch.
5770 CurInstIterator = std::next(LastSI->getIterator());
5771
Nadav Rotem9d832022012-09-02 12:10:19 +00005772 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5773
5774 // Can we convert the 'select' to CF ?
Vedant Kumarfbc38732018-08-21 23:42:23 +00005775 if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005776 return false;
5777
Nadav Rotem9d832022012-09-02 12:10:19 +00005778 TargetLowering::SelectSupportKind SelectKind;
5779 if (VectorCond)
5780 SelectKind = TargetLowering::VectorMaskSelect;
5781 else if (SI->getType()->isVectorTy())
5782 SelectKind = TargetLowering::ScalarCondVectorVal;
5783 else
5784 SelectKind = TargetLowering::ScalarValSelect;
5785
Sanjay Pateld66607b2016-04-26 17:11:17 +00005786 if (TLI->isSelectSupported(SelectKind) &&
5787 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5788 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005789
5790 ModifiedDT = true;
5791
Sanjay Patel69a50a12015-10-19 21:59:12 +00005792 // Transform a sequence like this:
5793 // start:
5794 // %cmp = cmp uge i32 %a, %b
5795 // %sel = select i1 %cmp, i32 %c, i32 %d
5796 //
5797 // Into:
5798 // start:
5799 // %cmp = cmp uge i32 %a, %b
5800 // br i1 %cmp, label %select.true, label %select.false
5801 // select.true:
5802 // br label %select.end
5803 // select.false:
5804 // br label %select.end
5805 // select.end:
5806 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5807 //
5808 // In addition, we may sink instructions that produce %c or %d from
5809 // the entry block into the destination(s) of the new branch.
5810 // If the true or false blocks do not contain a sunken instruction, that
5811 // block and its branch may be optimized away. In that case, one side of the
5812 // first branch will point directly to select.end, and the corresponding PHI
5813 // predecessor block will be the start block.
5814
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005815 // First, we split the block containing the select into 2 blocks.
5816 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005817 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005818 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005819
Sanjay Patel69a50a12015-10-19 21:59:12 +00005820 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005821 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005822
5823 // These are the new basic blocks for the conditional branch.
5824 // At least one will become an actual new basic block.
5825 BasicBlock *TrueBlock = nullptr;
5826 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005827 BranchInst *TrueBranch = nullptr;
5828 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005829
5830 // Sink expensive instructions into the conditional blocks to avoid executing
5831 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005832 for (SelectInst *SI : ASI) {
5833 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5834 if (TrueBlock == nullptr) {
5835 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5836 EndBlock->getParent(), EndBlock);
5837 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00005838 TrueBranch->setDebugLoc(SI->getDebugLoc());
Dehao Chen9bbb9412016-09-12 20:23:28 +00005839 }
5840 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5841 TrueInst->moveBefore(TrueBranch);
5842 }
5843 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5844 if (FalseBlock == nullptr) {
5845 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5846 EndBlock->getParent(), EndBlock);
5847 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00005848 FalseBranch->setDebugLoc(SI->getDebugLoc());
Dehao Chen9bbb9412016-09-12 20:23:28 +00005849 }
5850 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5851 FalseInst->moveBefore(FalseBranch);
5852 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005853 }
5854
5855 // If there was nothing to sink, then arbitrarily choose the 'false' side
5856 // for a new input value to the PHI.
5857 if (TrueBlock == FalseBlock) {
5858 assert(TrueBlock == nullptr &&
5859 "Unexpected basic block transform while optimizing select");
5860
5861 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5862 EndBlock->getParent(), EndBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00005863 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5864 FalseBranch->setDebugLoc(SI->getDebugLoc());
Sanjay Patel69a50a12015-10-19 21:59:12 +00005865 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005866
5867 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005868 // If we did not create a new block for one of the 'true' or 'false' paths
5869 // of the condition, it means that side of the branch goes to the end block
5870 // directly and the path originates from the start block from the point of
5871 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005872 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005873 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005874 TT = EndBlock;
5875 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005876 TrueBlock = StartBlock;
5877 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005878 TT = TrueBlock;
5879 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005880 FalseBlock = StartBlock;
5881 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005882 TT = TrueBlock;
5883 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005884 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005885 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005886
Dehao Chen9bbb9412016-09-12 20:23:28 +00005887 SmallPtrSet<const Instruction *, 2> INS;
5888 INS.insert(ASI.begin(), ASI.end());
5889 // Use reverse iterator because later select may use the value of the
5890 // earlier select, and we need to propagate value through earlier select
5891 // to get the PHI operand.
5892 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5893 SelectInst *SI = *It;
5894 // The select itself is replaced with a PHI Node.
5895 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5896 PN->takeName(SI);
5897 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5898 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00005899 PN->setDebugLoc(SI->getDebugLoc());
Sanjay Patel69a50a12015-10-19 21:59:12 +00005900
Dehao Chen9bbb9412016-09-12 20:23:28 +00005901 SI->replaceAllUsesWith(PN);
5902 SI->eraseFromParent();
5903 INS.erase(SI);
5904 ++NumSelectsExpanded;
5905 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005906
5907 // Instruct OptimizeBlock to skip to the next block.
5908 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005909 return true;
5910}
5911
Benjamin Kramer573ff362014-03-01 17:24:40 +00005912static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005913 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5914 int SplatElem = -1;
5915 for (unsigned i = 0; i < Mask.size(); ++i) {
5916 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5917 return false;
5918 SplatElem = Mask[i];
5919 }
5920
5921 return true;
5922}
5923
5924/// Some targets have expensive vector shifts if the lanes aren't all the same
5925/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5926/// it's often worth sinking a shufflevector splat down to its use so that
5927/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005928bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005929 BasicBlock *DefBB = SVI->getParent();
5930
5931 // Only do this xform if variable vector shifts are particularly expensive.
5932 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5933 return false;
5934
5935 // We only expect better codegen by sinking a shuffle if we can recognise a
5936 // constant splat.
5937 if (!isBroadcastShuffle(SVI))
5938 return false;
5939
5940 // InsertedShuffles - Only insert a shuffle in each block once.
5941 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5942
5943 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005944 for (User *U : SVI->users()) {
5945 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005946
5947 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005948 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005949 if (UserBB == DefBB) continue;
5950
5951 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005952 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005953
5954 // Everything checks out, sink the shuffle if the user's block doesn't
5955 // already have a copy.
5956 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5957
5958 if (!InsertedShuffle) {
5959 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005960 assert(InsertPt != UserBB->end());
5961 InsertedShuffle =
5962 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5963 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005964 }
5965
Chandler Carruthcdf47882014-03-09 03:16:01 +00005966 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005967 MadeChange = true;
5968 }
5969
5970 // If we removed all uses, nuke the shuffle.
5971 if (SVI->use_empty()) {
5972 SVI->eraseFromParent();
5973 MadeChange = true;
5974 }
5975
5976 return MadeChange;
5977}
5978
Florian Hahn3b251962019-02-05 10:27:40 +00005979bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
5980 // If the operands of I can be folded into a target instruction together with
5981 // I, duplicate and sink them.
5982 SmallVector<Use *, 4> OpsToSink;
5983 if (!TLI || !TLI->shouldSinkOperands(I, OpsToSink))
5984 return false;
5985
5986 // OpsToSink can contain multiple uses in a use chain (e.g.
5987 // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating
5988 // uses must come first, which means they are sunk first, temporarily creating
5989 // invalid IR. This will be fixed once their dominated users are sunk and
5990 // updated.
5991 BasicBlock *TargetBB = I->getParent();
5992 bool Changed = false;
5993 SmallVector<Use *, 4> ToReplace;
5994 for (Use *U : OpsToSink) {
5995 auto *UI = cast<Instruction>(U->get());
5996 if (UI->getParent() == TargetBB || isa<PHINode>(UI))
5997 continue;
5998 ToReplace.push_back(U);
5999 }
6000
6001 SmallPtrSet<Instruction *, 4> MaybeDead;
6002 for (Use *U : ToReplace) {
6003 auto *UI = cast<Instruction>(U->get());
6004 Instruction *NI = UI->clone();
6005 MaybeDead.insert(UI);
6006 LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
6007 NI->insertBefore(I);
6008 InsertedInsts.insert(NI);
6009 U->set(NI);
6010 Changed = true;
6011 }
6012
6013 // Remove instructions that are dead after sinking.
6014 for (auto *I : MaybeDead)
6015 if (!I->hasNUsesOrMore(1))
6016 I->eraseFromParent();
6017
6018 return Changed;
6019}
6020
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006021bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
6022 if (!TLI || !DL)
6023 return false;
6024
6025 Value *Cond = SI->getCondition();
6026 Type *OldType = Cond->getType();
6027 LLVMContext &Context = Cond->getContext();
6028 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
6029 unsigned RegWidth = RegType.getSizeInBits();
6030
6031 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
6032 return false;
6033
6034 // If the register width is greater than the type width, expand the condition
6035 // of the switch instruction and each case constant to the width of the
6036 // register. By widening the type of the switch condition, subsequent
6037 // comparisons (for case comparisons) will not need to be extended to the
6038 // preferred register width, so we will potentially eliminate N-1 extends,
6039 // where N is the number of cases in the switch.
6040 auto *NewType = Type::getIntNTy(Context, RegWidth);
6041
6042 // Zero-extend the switch condition and case constants unless the switch
6043 // condition is a function argument that is already being sign-extended.
6044 // In that case, we can avoid an unnecessary mask/extension by sign-extending
6045 // everything instead.
6046 Instruction::CastOps ExtType = Instruction::ZExt;
6047 if (auto *Arg = dyn_cast<Argument>(Cond))
6048 if (Arg->hasSExtAttr())
6049 ExtType = Instruction::SExt;
6050
6051 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
6052 ExtInst->insertBefore(SI);
Vedant Kumar47606862018-08-22 01:23:31 +00006053 ExtInst->setDebugLoc(SI->getDebugLoc());
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006054 SI->setCondition(ExtInst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00006055 for (auto Case : SI->cases()) {
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006056 APInt NarrowConst = Case.getCaseValue()->getValue();
6057 APInt WideConst = (ExtType == Instruction::ZExt) ?
6058 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
6059 Case.setValue(ConstantInt::get(Context, WideConst));
6060 }
6061
6062 return true;
6063}
6064
Zaara Syeda3a7578c2017-05-31 17:12:38 +00006065
Quentin Colombetc32615d2014-10-31 17:52:53 +00006066namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006067
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006068/// Helper class to promote a scalar operation to a vector one.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006069/// This class is used to move downward extractelement transition.
6070/// E.g.,
6071/// a = vector_op <2 x i32>
6072/// b = extractelement <2 x i32> a, i32 0
6073/// c = scalar_op b
6074/// store c
6075///
6076/// =>
6077/// a = vector_op <2 x i32>
6078/// c = vector_op a (equivalent to scalar_op on the related lane)
6079/// * d = extractelement <2 x i32> c, i32 0
6080/// * store d
6081/// Assuming both extractelement and store can be combine, we get rid of the
6082/// transition.
6083class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00006084 /// DataLayout associated with the current module.
6085 const DataLayout &DL;
6086
Quentin Colombetc32615d2014-10-31 17:52:53 +00006087 /// Used to perform some checks on the legality of vector operations.
6088 const TargetLowering &TLI;
6089
6090 /// Used to estimated the cost of the promoted chain.
6091 const TargetTransformInfo &TTI;
6092
6093 /// The transition being moved downwards.
6094 Instruction *Transition;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006095
Quentin Colombetc32615d2014-10-31 17:52:53 +00006096 /// The sequence of instructions to be promoted.
6097 SmallVector<Instruction *, 4> InstsToBePromoted;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006098
Quentin Colombetc32615d2014-10-31 17:52:53 +00006099 /// Cost of combining a store and an extract.
6100 unsigned StoreExtractCombineCost;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006101
Quentin Colombetc32615d2014-10-31 17:52:53 +00006102 /// Instruction that will be combined with the transition.
Eugene Zelenko900b6332017-08-29 22:32:07 +00006103 Instruction *CombineInst = nullptr;
Quentin Colombetc32615d2014-10-31 17:52:53 +00006104
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006105 /// The instruction that represents the current end of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006106 /// Since we are faking the promotion until we reach the end of the chain
6107 /// of computation, we need a way to get the current end of the transition.
6108 Instruction *getEndOfTransition() const {
6109 if (InstsToBePromoted.empty())
6110 return Transition;
6111 return InstsToBePromoted.back();
6112 }
6113
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006114 /// Return the index of the original value in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006115 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
6116 /// c, is at index 0.
6117 unsigned getTransitionOriginalValueIdx() const {
6118 assert(isa<ExtractElementInst>(Transition) &&
6119 "Other kind of transitions are not supported yet");
6120 return 0;
6121 }
6122
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006123 /// Return the index of the index in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006124 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
6125 /// is at index 1.
6126 unsigned getTransitionIdx() const {
6127 assert(isa<ExtractElementInst>(Transition) &&
6128 "Other kind of transitions are not supported yet");
6129 return 1;
6130 }
6131
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006132 /// Get the type of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006133 /// This is the type of the original value.
6134 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
6135 /// transition is <2 x i32>.
6136 Type *getTransitionType() const {
6137 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
6138 }
6139
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006140 /// Promote \p ToBePromoted by moving \p Def downward through.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006141 /// I.e., we have the following sequence:
6142 /// Def = Transition <ty1> a to <ty2>
6143 /// b = ToBePromoted <ty2> Def, ...
6144 /// =>
6145 /// b = ToBePromoted <ty1> a, ...
6146 /// Def = Transition <ty1> ToBePromoted to <ty2>
6147 void promoteImpl(Instruction *ToBePromoted);
6148
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006149 /// Check whether or not it is profitable to promote all the
Quentin Colombetc32615d2014-10-31 17:52:53 +00006150 /// instructions enqueued to be promoted.
6151 bool isProfitableToPromote() {
6152 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
6153 unsigned Index = isa<ConstantInt>(ValIdx)
6154 ? cast<ConstantInt>(ValIdx)->getZExtValue()
6155 : -1;
6156 Type *PromotedType = getTransitionType();
6157
6158 StoreInst *ST = cast<StoreInst>(CombineInst);
6159 unsigned AS = ST->getPointerAddressSpace();
6160 unsigned Align = ST->getAlignment();
6161 // Check if this store is supported.
6162 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00006163 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
6164 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00006165 // If this is not supported, there is no way we can combine
6166 // the extract with the store.
6167 return false;
6168 }
6169
6170 // The scalar chain of computation has to pay for the transition
6171 // scalar to vector.
6172 // The vector chain has to account for the combining cost.
6173 uint64_t ScalarCost =
6174 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
6175 uint64_t VectorCost = StoreExtractCombineCost;
6176 for (const auto &Inst : InstsToBePromoted) {
6177 // Compute the cost.
6178 // By construction, all instructions being promoted are arithmetic ones.
6179 // Moreover, one argument is a constant that can be viewed as a splat
6180 // constant.
6181 Value *Arg0 = Inst->getOperand(0);
6182 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
6183 isa<ConstantFP>(Arg0);
6184 TargetTransformInfo::OperandValueKind Arg0OVK =
6185 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
6186 : TargetTransformInfo::OK_AnyValue;
6187 TargetTransformInfo::OperandValueKind Arg1OVK =
6188 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
6189 : TargetTransformInfo::OK_AnyValue;
6190 ScalarCost += TTI.getArithmeticInstrCost(
6191 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
6192 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
6193 Arg0OVK, Arg1OVK);
6194 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006195 LLVM_DEBUG(
6196 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
6197 << ScalarCost << "\nVector: " << VectorCost << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006198 return ScalarCost > VectorCost;
6199 }
6200
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006201 /// Generate a constant vector with \p Val with the same
Quentin Colombetc32615d2014-10-31 17:52:53 +00006202 /// number of elements as the transition.
6203 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00006204 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006205 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
6206 /// otherwise we generate a vector with as many undef as possible:
6207 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
6208 /// used at the index of the extract.
6209 Value *getConstantVector(Constant *Val, bool UseSplat) const {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006210 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006211 if (!UseSplat) {
6212 // If we cannot determine where the constant must be, we have to
6213 // use a splat constant.
6214 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
6215 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
6216 ExtractIdx = CstVal->getSExtValue();
6217 else
6218 UseSplat = true;
6219 }
6220
6221 unsigned End = getTransitionType()->getVectorNumElements();
6222 if (UseSplat)
6223 return ConstantVector::getSplat(End, Val);
6224
6225 SmallVector<Constant *, 4> ConstVec;
6226 UndefValue *UndefVal = UndefValue::get(Val->getType());
6227 for (unsigned Idx = 0; Idx != End; ++Idx) {
6228 if (Idx == ExtractIdx)
6229 ConstVec.push_back(Val);
6230 else
6231 ConstVec.push_back(UndefVal);
6232 }
6233 return ConstantVector::get(ConstVec);
6234 }
6235
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006236 /// Check if promoting to a vector type an operand at \p OperandIdx
Quentin Colombetc32615d2014-10-31 17:52:53 +00006237 /// in \p Use can trigger undefined behavior.
6238 static bool canCauseUndefinedBehavior(const Instruction *Use,
6239 unsigned OperandIdx) {
6240 // This is not safe to introduce undef when the operand is on
6241 // the right hand side of a division-like instruction.
6242 if (OperandIdx != 1)
6243 return false;
6244 switch (Use->getOpcode()) {
6245 default:
6246 return false;
6247 case Instruction::SDiv:
6248 case Instruction::UDiv:
6249 case Instruction::SRem:
6250 case Instruction::URem:
6251 return true;
6252 case Instruction::FDiv:
6253 case Instruction::FRem:
6254 return !Use->hasNoNaNs();
6255 }
6256 llvm_unreachable(nullptr);
6257 }
6258
6259public:
Mehdi Amini44ede332015-07-09 02:09:04 +00006260 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
6261 const TargetTransformInfo &TTI, Instruction *Transition,
6262 unsigned CombineCost)
6263 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Eugene Zelenko900b6332017-08-29 22:32:07 +00006264 StoreExtractCombineCost(CombineCost) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00006265 assert(Transition && "Do not know how to promote null");
6266 }
6267
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006268 /// Check if we can promote \p ToBePromoted to \p Type.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006269 bool canPromote(const Instruction *ToBePromoted) const {
6270 // We could support CastInst too.
6271 return isa<BinaryOperator>(ToBePromoted);
6272 }
6273
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006274 /// Check if it is profitable to promote \p ToBePromoted
Quentin Colombetc32615d2014-10-31 17:52:53 +00006275 /// by moving downward the transition through.
6276 bool shouldPromote(const Instruction *ToBePromoted) const {
6277 // Promote only if all the operands can be statically expanded.
6278 // Indeed, we do not want to introduce any new kind of transitions.
6279 for (const Use &U : ToBePromoted->operands()) {
6280 const Value *Val = U.get();
6281 if (Val == getEndOfTransition()) {
6282 // If the use is a division and the transition is on the rhs,
6283 // we cannot promote the operation, otherwise we may create a
6284 // division by zero.
6285 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
6286 return false;
6287 continue;
6288 }
6289 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
6290 !isa<ConstantFP>(Val))
6291 return false;
6292 }
6293 // Check that the resulting operation is legal.
6294 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
6295 if (!ISDOpcode)
6296 return false;
6297 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00006298 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00006299 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00006300 }
6301
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006302 /// Check whether or not \p Use can be combined
Quentin Colombetc32615d2014-10-31 17:52:53 +00006303 /// with the transition.
6304 /// I.e., is it possible to do Use(Transition) => AnotherUse?
6305 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
6306
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006307 /// Record \p ToBePromoted as part of the chain to be promoted.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006308 void enqueueForPromotion(Instruction *ToBePromoted) {
6309 InstsToBePromoted.push_back(ToBePromoted);
6310 }
6311
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006312 /// Set the instruction that will be combined with the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006313 void recordCombineInstruction(Instruction *ToBeCombined) {
6314 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
6315 CombineInst = ToBeCombined;
6316 }
6317
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006318 /// Promote all the instructions enqueued for promotion if it is
Quentin Colombetc32615d2014-10-31 17:52:53 +00006319 /// is profitable.
6320 /// \return True if the promotion happened, false otherwise.
6321 bool promote() {
6322 // Check if there is something to promote.
6323 // Right now, if we do not have anything to combine with,
6324 // we assume the promotion is not profitable.
6325 if (InstsToBePromoted.empty() || !CombineInst)
6326 return false;
6327
6328 // Check cost.
6329 if (!StressStoreExtract && !isProfitableToPromote())
6330 return false;
6331
6332 // Promote.
6333 for (auto &ToBePromoted : InstsToBePromoted)
6334 promoteImpl(ToBePromoted);
6335 InstsToBePromoted.clear();
6336 return true;
6337 }
6338};
Eugene Zelenko900b6332017-08-29 22:32:07 +00006339
6340} // end anonymous namespace
Quentin Colombetc32615d2014-10-31 17:52:53 +00006341
6342void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
6343 // At this point, we know that all the operands of ToBePromoted but Def
6344 // can be statically promoted.
6345 // For Def, we need to use its parameter in ToBePromoted:
6346 // b = ToBePromoted ty1 a
6347 // Def = Transition ty1 b to ty2
6348 // Move the transition down.
6349 // 1. Replace all uses of the promoted operation by the transition.
6350 // = ... b => = ... Def.
6351 assert(ToBePromoted->getType() == Transition->getType() &&
6352 "The type of the result of the transition does not match "
6353 "the final type");
6354 ToBePromoted->replaceAllUsesWith(Transition);
6355 // 2. Update the type of the uses.
6356 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
6357 Type *TransitionTy = getTransitionType();
6358 ToBePromoted->mutateType(TransitionTy);
6359 // 3. Update all the operands of the promoted operation with promoted
6360 // operands.
6361 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
6362 for (Use &U : ToBePromoted->operands()) {
6363 Value *Val = U.get();
6364 Value *NewVal = nullptr;
6365 if (Val == Transition)
6366 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
6367 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
6368 isa<ConstantFP>(Val)) {
6369 // Use a splat constant if it is not safe to use undef.
6370 NewVal = getConstantVector(
6371 cast<Constant>(Val),
6372 isa<UndefValue>(Val) ||
6373 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
6374 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00006375 llvm_unreachable("Did you modified shouldPromote and forgot to update "
6376 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006377 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
6378 }
Sanjay Patel674d2c22017-08-29 14:07:48 +00006379 Transition->moveAfter(ToBePromoted);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006380 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6381}
6382
6383/// Some targets can do store(extractelement) with one instruction.
6384/// Try to push the extractelement towards the stores when the target
6385/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006386bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006387 unsigned CombineCost = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006388 if (DisableStoreExtract || !TLI ||
6389 (!StressStoreExtract &&
6390 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
6391 Inst->getOperand(1), CombineCost)))
6392 return false;
6393
6394 // At this point we know that Inst is a vector to scalar transition.
6395 // Try to move it down the def-use chain, until:
6396 // - We can combine the transition with its single use
6397 // => we got rid of the transition.
6398 // - We escape the current basic block
6399 // => we would need to check that we are moving it at a cheaper place and
6400 // we do not do that for now.
6401 BasicBlock *Parent = Inst->getParent();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006402 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00006403 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006404 // If the transition has more than one use, assume this is not going to be
6405 // beneficial.
6406 while (Inst->hasOneUse()) {
6407 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006408 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006409
6410 if (ToBePromoted->getParent() != Parent) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006411 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
6412 << ToBePromoted->getParent()->getName()
6413 << ") than the transition (" << Parent->getName()
6414 << ").\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006415 return false;
6416 }
6417
6418 if (VPH.canCombine(ToBePromoted)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006419 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
6420 << "will be combined with: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006421 VPH.recordCombineInstruction(ToBePromoted);
6422 bool Changed = VPH.promote();
6423 NumStoreExtractExposed += Changed;
6424 return Changed;
6425 }
6426
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006427 LLVM_DEBUG(dbgs() << "Try promoting.\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006428 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6429 return false;
6430
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006431 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006432
6433 VPH.enqueueForPromotion(ToBePromoted);
6434 Inst = ToBePromoted;
6435 }
6436 return false;
6437}
6438
Wei Mia2f0b592016-12-22 19:44:45 +00006439/// For the instruction sequence of store below, F and I values
6440/// are bundled together as an i64 value before being stored into memory.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006441/// Sometimes it is more efficient to generate separate stores for F and I,
Wei Mia2f0b592016-12-22 19:44:45 +00006442/// which can remove the bitwise instructions or sink them to colder places.
6443///
6444/// (store (or (zext (bitcast F to i32) to i64),
6445/// (shl (zext I to i64), 32)), addr) -->
6446/// (store F, addr) and (store I, addr+4)
6447///
6448/// Similarly, splitting for other merged store can also be beneficial, like:
6449/// For pair of {i32, i32}, i64 store --> two i32 stores.
6450/// For pair of {i32, i16}, i64 store --> two i32 stores.
6451/// For pair of {i16, i16}, i32 store --> two i16 stores.
6452/// For pair of {i16, i8}, i32 store --> two i16 stores.
6453/// For pair of {i8, i8}, i16 store --> two i8 stores.
6454///
6455/// We allow each target to determine specifically which kind of splitting is
6456/// supported.
6457///
6458/// The store patterns are commonly seen from the simple code snippet below
6459/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
6460/// void goo(const std::pair<int, float> &);
6461/// hoo() {
6462/// ...
6463/// goo(std::make_pair(tmp, ftmp));
6464/// ...
6465/// }
6466///
6467/// Although we already have similar splitting in DAG Combine, we duplicate
6468/// it in CodeGenPrepare to catch the case in which pattern is across
6469/// multiple BBs. The logic in DAG Combine is kept to catch case generated
6470/// during code expansion.
6471static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
6472 const TargetLowering &TLI) {
6473 // Handle simple but common cases only.
6474 Type *StoreType = SI.getValueOperand()->getType();
6475 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6476 DL.getTypeSizeInBits(StoreType) == 0)
6477 return false;
6478
6479 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6480 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6481 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6482 DL.getTypeSizeInBits(SplitStoreType))
6483 return false;
6484
6485 // Match the following patterns:
6486 // (store (or (zext LValue to i64),
6487 // (shl (zext HValue to i64), 32)), HalfValBitSize)
6488 // or
6489 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6490 // (zext LValue to i64),
6491 // Expect both operands of OR and the first operand of SHL have only
6492 // one use.
6493 Value *LValue, *HValue;
6494 if (!match(SI.getValueOperand(),
6495 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6496 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6497 m_SpecificInt(HalfValBitSize))))))
6498 return false;
6499
6500 // Check LValue and HValue are int with size less or equal than 32.
6501 if (!LValue->getType()->isIntegerTy() ||
6502 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6503 !HValue->getType()->isIntegerTy() ||
6504 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6505 return false;
6506
6507 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6508 // as the input of target query.
6509 auto *LBC = dyn_cast<BitCastInst>(LValue);
6510 auto *HBC = dyn_cast<BitCastInst>(HValue);
6511 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6512 : EVT::getEVT(LValue->getType());
6513 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6514 : EVT::getEVT(HValue->getType());
6515 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6516 return false;
6517
6518 // Start to split store.
6519 IRBuilder<> Builder(SI.getContext());
6520 Builder.SetInsertPoint(&SI);
6521
6522 // If LValue/HValue is a bitcast in another BB, create a new one in current
6523 // BB so it may be merged with the splitted stores by dag combiner.
6524 if (LBC && LBC->getParent() != SI.getParent())
6525 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6526 if (HBC && HBC->getParent() != SI.getParent())
6527 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6528
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006529 bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
Wei Mia2f0b592016-12-22 19:44:45 +00006530 auto CreateSplitStore = [&](Value *V, bool Upper) {
6531 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6532 Value *Addr = Builder.CreateBitCast(
6533 SI.getOperand(1),
6534 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006535 if ((IsLE && Upper) || (!IsLE && !Upper))
Wei Mia2f0b592016-12-22 19:44:45 +00006536 Addr = Builder.CreateGEP(
6537 SplitStoreType, Addr,
6538 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6539 Builder.CreateAlignedStore(
6540 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6541 };
6542
6543 CreateSplitStore(LValue, false);
6544 CreateSplitStore(HValue, true);
6545
6546 // Delete the old store.
6547 SI.eraseFromParent();
6548 return true;
6549}
6550
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006551// Return true if the GEP has two operands, the first operand is of a sequential
6552// type, and the second operand is a constant.
6553static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6554 gep_type_iterator I = gep_type_begin(*GEP);
6555 return GEP->getNumOperands() == 2 &&
6556 I.isSequential() &&
6557 isa<ConstantInt>(GEP->getOperand(1));
6558}
6559
6560// Try unmerging GEPs to reduce liveness interference (register pressure) across
6561// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6562// reducing liveness interference across those edges benefits global register
6563// allocation. Currently handles only certain cases.
6564//
6565// For example, unmerge %GEPI and %UGEPI as below.
6566//
6567// ---------- BEFORE ----------
6568// SrcBlock:
6569// ...
6570// %GEPIOp = ...
6571// ...
6572// %GEPI = gep %GEPIOp, Idx
6573// ...
6574// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6575// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6576// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6577// %UGEPI)
6578//
6579// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6580// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6581// ...
6582//
6583// DstBi:
6584// ...
6585// %UGEPI = gep %GEPIOp, UIdx
6586// ...
6587// ---------------------------
6588//
6589// ---------- AFTER ----------
6590// SrcBlock:
6591// ... (same as above)
6592// (* %GEPI is still alive on the indirectbr edges)
6593// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6594// unmerging)
6595// ...
6596//
6597// DstBi:
6598// ...
6599// %UGEPI = gep %GEPI, (UIdx-Idx)
6600// ...
6601// ---------------------------
6602//
6603// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6604// no longer alive on them.
6605//
6606// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6607// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6608// not to disable further simplications and optimizations as a result of GEP
6609// merging.
6610//
6611// Note this unmerging may increase the length of the data flow critical path
6612// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6613// between the register pressure and the length of data-flow critical
6614// path. Restricting this to the uncommon IndirectBr case would minimize the
6615// impact of potentially longer critical path, if any, and the impact on compile
6616// time.
6617static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6618 const TargetTransformInfo *TTI) {
6619 BasicBlock *SrcBlock = GEPI->getParent();
6620 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6621 // (non-IndirectBr) cases exit early here.
6622 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6623 return false;
6624 // Check that GEPI is a simple gep with a single constant index.
6625 if (!GEPSequentialConstIndexed(GEPI))
6626 return false;
6627 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6628 // Check that GEPI is a cheap one.
6629 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6630 > TargetTransformInfo::TCC_Basic)
6631 return false;
6632 Value *GEPIOp = GEPI->getOperand(0);
6633 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6634 if (!isa<Instruction>(GEPIOp))
6635 return false;
6636 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6637 if (GEPIOpI->getParent() != SrcBlock)
6638 return false;
6639 // Check that GEP is used outside the block, meaning it's alive on the
6640 // IndirectBr edge(s).
6641 if (find_if(GEPI->users(), [&](User *Usr) {
6642 if (auto *I = dyn_cast<Instruction>(Usr)) {
6643 if (I->getParent() != SrcBlock) {
6644 return true;
6645 }
6646 }
6647 return false;
6648 }) == GEPI->users().end())
6649 return false;
6650 // The second elements of the GEP chains to be unmerged.
6651 std::vector<GetElementPtrInst *> UGEPIs;
6652 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6653 // on IndirectBr edges.
6654 for (User *Usr : GEPIOp->users()) {
6655 if (Usr == GEPI) continue;
6656 // Check if Usr is an Instruction. If not, give up.
6657 if (!isa<Instruction>(Usr))
6658 return false;
6659 auto *UI = cast<Instruction>(Usr);
6660 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6661 if (UI->getParent() == SrcBlock)
6662 continue;
6663 // Check if Usr is a GEP. If not, give up.
6664 if (!isa<GetElementPtrInst>(Usr))
6665 return false;
6666 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6667 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6668 // the pointer operand to it. If so, record it in the vector. If not, give
6669 // up.
6670 if (!GEPSequentialConstIndexed(UGEPI))
6671 return false;
6672 if (UGEPI->getOperand(0) != GEPIOp)
6673 return false;
6674 if (GEPIIdx->getType() !=
6675 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6676 return false;
6677 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6678 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6679 > TargetTransformInfo::TCC_Basic)
6680 return false;
6681 UGEPIs.push_back(UGEPI);
6682 }
6683 if (UGEPIs.size() == 0)
6684 return false;
6685 // Check the materializing cost of (Uidx-Idx).
6686 for (GetElementPtrInst *UGEPI : UGEPIs) {
6687 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6688 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6689 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6690 if (ImmCost > TargetTransformInfo::TCC_Basic)
6691 return false;
6692 }
6693 // Now unmerge between GEPI and UGEPIs.
6694 for (GetElementPtrInst *UGEPI : UGEPIs) {
6695 UGEPI->setOperand(0, GEPI);
6696 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6697 Constant *NewUGEPIIdx =
6698 ConstantInt::get(GEPIIdx->getType(),
6699 UGEPIIdx->getValue() - GEPIIdx->getValue());
6700 UGEPI->setOperand(1, NewUGEPIIdx);
6701 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6702 // inbounds to avoid UB.
6703 if (!GEPI->isInBounds()) {
6704 UGEPI->setIsInBounds(false);
6705 }
6706 }
6707 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6708 // alive on IndirectBr edges).
6709 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6710 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6711 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6712 return true;
6713}
6714
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006715bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00006716 // Bail out if we inserted the instruction to prevent optimizations from
6717 // stepping on each other's toes.
6718 if (InsertedInsts.count(I))
6719 return false;
6720
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006721 if (PHINode *P = dyn_cast<PHINode>(I)) {
6722 // It is possible for very late stage optimizations (such as SimplifyCFG)
6723 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6724 // trivial PHI, go ahead and zap it here.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00006725 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006726 P->replaceAllUsesWith(V);
6727 P->eraseFromParent();
6728 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00006729 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006730 }
Chris Lattneree588de2011-01-15 07:29:01 +00006731 return false;
6732 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006733
Chris Lattneree588de2011-01-15 07:29:01 +00006734 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006735 // If the source of the cast is a constant, then this should have
6736 // already been constant folded. The only reason NOT to constant fold
6737 // it is if something (e.g. LSR) was careful to place the constant
6738 // evaluation in a block other than then one that uses it (e.g. to hoist
6739 // the address of globals out of a loop). If this is the case, we don't
6740 // want to forward-subst the cast.
6741 if (isa<Constant>(CI->getOperand(0)))
6742 return false;
6743
Mehdi Amini44ede332015-07-09 02:09:04 +00006744 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00006745 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006746
Chris Lattneree588de2011-01-15 07:29:01 +00006747 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006748 /// Sink a zext or sext into its user blocks if the target type doesn't
6749 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00006750 if (TLI &&
6751 TLI->getTypeAction(CI->getContext(),
6752 TLI->getValueType(*DL, CI->getType())) ==
6753 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006754 return SinkCast(CI);
6755 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00006756 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00006757 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006758 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006759 }
Chris Lattneree588de2011-01-15 07:29:01 +00006760 return false;
6761 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006762
Chris Lattneree588de2011-01-15 07:29:01 +00006763 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Sanjay Patel84ceae62019-02-03 17:53:09 +00006764 if (TLI && optimizeCmpExpression(CI, *TLI, *DL))
Sanjay Patel00fcc742019-02-03 13:48:03 +00006765 return true;
Nadav Rotem465834c2012-07-24 10:51:42 +00006766
Chris Lattneree588de2011-01-15 07:29:01 +00006767 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006768 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006769 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006770 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006771 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006772 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6773 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006774 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006775 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006776 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006777
Chris Lattneree588de2011-01-15 07:29:01 +00006778 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006779 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6780 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006781 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006782 if (TLI) {
6783 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006784 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006785 SI->getOperand(0)->getType(), AS);
6786 }
Chris Lattneree588de2011-01-15 07:29:01 +00006787 return false;
6788 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006789
Matt Arsenault02d915b2017-03-15 22:35:20 +00006790 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6791 unsigned AS = RMW->getPointerAddressSpace();
6792 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6793 RMW->getType(), AS);
6794 }
6795
6796 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6797 unsigned AS = CmpX->getPointerAddressSpace();
6798 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6799 CmpX->getCompareOperand()->getType(), AS);
6800 }
6801
Yi Jiangd069f632014-04-21 19:34:27 +00006802 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6803
Geoff Berry5d534b62017-02-21 18:53:14 +00006804 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6805 EnableAndCmpSinking && TLI)
6806 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6807
Yi Jiangd069f632014-04-21 19:34:27 +00006808 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6809 BinOp->getOpcode() == Instruction::LShr)) {
6810 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6811 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006812 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006813
6814 return false;
6815 }
6816
Chris Lattneree588de2011-01-15 07:29:01 +00006817 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006818 if (GEPI->hasAllZeroIndices()) {
6819 /// The GEP operand must be a pointer, so must its result -> BitCast
6820 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6821 GEPI->getName(), GEPI);
Vedant Kumar40399a22018-05-24 23:00:21 +00006822 NC->setDebugLoc(GEPI->getDebugLoc());
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006823 GEPI->replaceAllUsesWith(NC);
6824 GEPI->eraseFromParent();
6825 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00006826 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00006827 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006828 }
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006829 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
6830 return true;
6831 }
Chris Lattneree588de2011-01-15 07:29:01 +00006832 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006833 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006834
Florian Hahn3b251962019-02-05 10:27:40 +00006835 if (tryToSinkFreeOperands(I))
6836 return true;
6837
Chris Lattneree588de2011-01-15 07:29:01 +00006838 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006839 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006840
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006841 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006842 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006843
Tim Northoveraeb8e062014-02-19 10:02:43 +00006844 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006845 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006846
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006847 if (auto *Switch = dyn_cast<SwitchInst>(I))
6848 return optimizeSwitchInst(Switch);
6849
Quentin Colombetc32615d2014-10-31 17:52:53 +00006850 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006851 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006852
Chris Lattneree588de2011-01-15 07:29:01 +00006853 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006854}
6855
James Molloyf01488e2016-01-15 09:20:19 +00006856/// Given an OR instruction, check to see if this is a bitreverse
6857/// idiom. If so, insert the new intrinsic and return true.
6858static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6859 const TargetLowering &TLI) {
6860 if (!I.getType()->isIntegerTy() ||
6861 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6862 TLI.getValueType(DL, I.getType(), true)))
6863 return false;
6864
6865 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00006866 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00006867 return false;
6868 Instruction *LastInst = Insts.back();
6869 I.replaceAllUsesWith(LastInst);
6870 RecursivelyDeleteTriviallyDeadInstructions(&I);
6871 return true;
6872}
6873
Chris Lattnerf2836d12007-03-31 04:06:36 +00006874// In this pass we look for GEP and cast instructions that are used
6875// across basic blocks and rewrite them to improve basic-block-at-a-time
6876// selection.
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006877bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00006878 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00006879 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00006880
Chris Lattner7a277142011-01-15 07:14:54 +00006881 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006882 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006883 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006884 if (ModifiedDT)
6885 return true;
6886 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00006887
James Molloyf01488e2016-01-15 09:20:19 +00006888 bool MadeBitReverse = true;
6889 while (TLI && MadeBitReverse) {
6890 MadeBitReverse = false;
6891 for (auto &I : reverse(BB)) {
6892 if (makeBitReverse(I, *DL, *TLI)) {
6893 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00006894 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00006895 break;
6896 }
6897 }
6898 }
James Molloy3ef84c42016-01-15 10:36:01 +00006899 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00006900
Chris Lattnerf2836d12007-03-31 04:06:36 +00006901 return MadeChange;
6902}
Devang Patel53771ba2011-08-18 00:50:51 +00006903
6904// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00006905// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00006906// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006907bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00006908 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006909 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00006910 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006911 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006912 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00006913 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00006914 // Leave dbg.values that refer to an alloca alone. These
Craig Topper87e715f2017-11-07 20:56:17 +00006915 // intrinsics describe the address of a variable (= the alloca)
Adrian Prantl32da8892014-04-25 20:49:25 +00006916 // being taken. They should not be moved next to the alloca
6917 // (and to the beginning of the scope), but rather stay close to
6918 // where said address is used.
6919 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00006920 PrevNonDbgInst = Insn;
6921 continue;
6922 }
6923
6924 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6925 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00006926 // If VI is a phi in a block with an EHPad terminator, we can't insert
6927 // after it.
6928 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6929 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006930 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
6931 << *DVI << ' ' << *VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006932 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00006933 if (isa<PHINode>(VI))
6934 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6935 else
6936 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006937 MadeChange = true;
6938 ++NumDbgValueMoved;
6939 }
6940 }
6941 }
6942 return MadeChange;
6943}
Tim Northovercea0abb2014-03-29 08:22:29 +00006944
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006945/// Scale down both weights to fit into uint32_t.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006946static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6947 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006948 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006949 NewTrue = NewTrue / Scale;
6950 NewFalse = NewFalse / Scale;
6951}
6952
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006953/// Some targets prefer to split a conditional branch like:
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006954/// \code
6955/// %0 = icmp ne i32 %a, 0
6956/// %1 = icmp ne i32 %b, 0
6957/// %or.cond = or i1 %0, %1
6958/// br i1 %or.cond, label %TrueBB, label %FalseBB
6959/// \endcode
6960/// into multiple branch instructions like:
6961/// \code
6962/// bb1:
6963/// %0 = icmp ne i32 %a, 0
6964/// br i1 %0, label %TrueBB, label %bb2
6965/// bb2:
6966/// %1 = icmp ne i32 %b, 0
6967/// br i1 %1, label %TrueBB, label %FalseBB
6968/// \endcode
6969/// This usually allows instruction selection to do even further optimizations
6970/// and combine the compare with the branch instruction. Currently this is
6971/// applied for targets which have "cheap" jump instructions.
6972///
6973/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6974///
6975bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006976 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006977 return false;
6978
6979 bool MadeChange = false;
6980 for (auto &BB : F) {
6981 // Does this BB end with the following?
6982 // %cond1 = icmp|fcmp|binary instruction ...
6983 // %cond2 = icmp|fcmp|binary instruction ...
6984 // %cond.or = or|and i1 %cond1, cond2
6985 // br i1 %cond.or label %dest1, label %dest2"
6986 BinaryOperator *LogicOp;
6987 BasicBlock *TBB, *FBB;
6988 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6989 continue;
6990
Sanjay Patel42574202015-09-02 19:23:23 +00006991 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6992 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6993 continue;
6994
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006995 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006996 Value *Cond1, *Cond2;
6997 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6998 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006999 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00007000 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
7001 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007002 Opc = Instruction::Or;
7003 else
7004 continue;
7005
7006 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
7007 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
7008 continue;
7009
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007010 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007011
7012 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00007013 auto TmpBB =
7014 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
7015 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007016
7017 // Update original basic block by using the first condition directly by the
7018 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007019 Br1->setCondition(Cond1);
7020 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00007021
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00007022 // Depending on the condition we have to either replace the true or the
7023 // false successor of the original branch instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007024 if (Opc == Instruction::And)
7025 Br1->setSuccessor(0, TmpBB);
7026 else
7027 Br1->setSuccessor(1, TmpBB);
7028
7029 // Fill in the new basic block.
7030 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00007031 if (auto *I = dyn_cast<Instruction>(Cond2)) {
7032 I->removeFromParent();
7033 I->insertBefore(Br2);
7034 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007035
7036 // Update PHI nodes in both successors. The original BB needs to be
Hiroshi Inoue6a391bb2017-06-27 10:35:37 +00007037 // replaced in one successor's PHI nodes, because the branch comes now from
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007038 // the newly generated BB (NewBB). In the other successor we need to add one
7039 // incoming edge to the PHI nodes, because both branch instructions target
7040 // now the same successor. Depending on the original branch condition
7041 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00007042 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007043 // This doesn't change the successor order of the just created branch
7044 // instruction (or any other instruction).
7045 if (Opc == Instruction::Or)
7046 std::swap(TBB, FBB);
7047
7048 // Replace the old BB with the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00007049 for (PHINode &PN : TBB->phis()) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007050 int i;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00007051 while ((i = PN.getBasicBlockIndex(&BB)) >= 0)
7052 PN.setIncomingBlock(i, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007053 }
7054
7055 // Add another incoming edge form the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00007056 for (PHINode &PN : FBB->phis()) {
7057 auto *Val = PN.getIncomingValueForBlock(&BB);
7058 PN.addIncoming(Val, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007059 }
7060
7061 // Update the branch weights (from SelectionDAGBuilder::
7062 // FindMergedConditions).
7063 if (Opc == Instruction::Or) {
7064 // Codegen X | Y as:
7065 // BB1:
7066 // jmp_if_X TBB
7067 // jmp TmpBB
7068 // TmpBB:
7069 // jmp_if_Y TBB
7070 // jmp FBB
7071 //
7072
7073 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
7074 // The requirement is that
7075 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00007076 // = TrueProb for original BB.
7077 // Assuming the original weights are A and B, one choice is to set BB1's
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007078 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
7079 // assumes that
7080 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
7081 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
7082 // TmpBB, but the math is more complicated.
7083 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00007084 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007085 uint64_t NewTrueWeight = TrueWeight;
7086 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
7087 scaleWeights(NewTrueWeight, NewFalseWeight);
7088 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
7089 .createBranchWeights(TrueWeight, FalseWeight));
7090
7091 NewTrueWeight = TrueWeight;
7092 NewFalseWeight = 2 * FalseWeight;
7093 scaleWeights(NewTrueWeight, NewFalseWeight);
7094 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
7095 .createBranchWeights(TrueWeight, FalseWeight));
7096 }
7097 } else {
7098 // Codegen X & Y as:
7099 // BB1:
7100 // jmp_if_X TmpBB
7101 // jmp FBB
7102 // TmpBB:
7103 // jmp_if_Y TBB
7104 // jmp FBB
7105 //
7106 // This requires creation of TmpBB after CurBB.
7107
7108 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
7109 // The requirement is that
7110 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00007111 // = FalseProb for original BB.
7112 // Assuming the original weights are A and B, one choice is to set BB1's
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007113 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
7114 // assumes that
7115 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
7116 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00007117 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007118 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
7119 uint64_t NewFalseWeight = FalseWeight;
7120 scaleWeights(NewTrueWeight, NewFalseWeight);
7121 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
7122 .createBranchWeights(TrueWeight, FalseWeight));
7123
7124 NewTrueWeight = 2 * TrueWeight;
7125 NewFalseWeight = FalseWeight;
7126 scaleWeights(NewTrueWeight, NewFalseWeight);
7127 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
7128 .createBranchWeights(TrueWeight, FalseWeight));
7129 }
7130 }
7131
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007132 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00007133 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007134 ModifiedDT = true;
7135
7136 MadeChange = true;
7137
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007138 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
7139 TmpBB->dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007140 }
7141 return MadeChange;
7142}