blob: 422a0a972fb440f14dc9cec77241255a1fef69e7 [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf2836d12007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
Eugene Zelenko900b6332017-08-29 22:32:07 +000016#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000019#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/STLExtras.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/Statistic.h"
Jun Bum Lim90b6b502016-12-16 20:38:39 +000024#include "llvm/Analysis/BlockFrequencyInfo.h"
25#include "llvm/Analysis/BranchProbabilityInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000026#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000028#include "llvm/Analysis/LoopInfo.h"
Zaara Syeda3a7578c2017-05-31 17:12:38 +000029#include "llvm/Analysis/MemoryBuiltins.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000030#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000031#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000032#include "llvm/Analysis/TargetTransformInfo.h"
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"
36#include "llvm/CodeGen/MachineValueType.h"
37#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000038#include "llvm/CodeGen/TargetLowering.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000039#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000040#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000041#include "llvm/CodeGen/ValueTypes.h"
42#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"
82#include "llvm/Support/MathExtras.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000083#include "llvm/Support/raw_ostream.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000084#include "llvm/Target/TargetMachine.h"
85#include "llvm/Target/TargetOptions.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000086#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000087#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000088#include "llvm/Transforms/Utils/Local.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
Eric Christopherc1ea1492008-09-24 05:32:41 +0000218namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000219
220using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
221using TypeIsSExt = PointerIntPair<Type *, 1, bool>;
222using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
223using SExts = SmallVector<Instruction *, 16>;
224using ValueToSExts = DenseMap<Value *, SExts>;
225
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000226class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000227
Chris Lattner2dd09db2009-09-02 06:11:42 +0000228 class CodeGenPrepare : public FunctionPass {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000229 const TargetMachine *TM = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000230 const TargetSubtargetInfo *SubtargetInfo;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000231 const TargetLowering *TLI = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000232 const TargetRegisterInfo *TRI;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000233 const TargetTransformInfo *TTI = nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000234 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000235 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000236 std::unique_ptr<BlockFrequencyInfo> BFI;
237 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000238
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000239 /// As we scan instructions optimizing them, this is the next instruction
240 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000241 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000242
Evan Cheng0663f232011-03-21 01:19:09 +0000243 /// Keeps track of non-local addresses that have been sunk into a block.
244 /// This allows us to avoid inserting duplicate code for blocks with
Simon Dardis230f4532017-11-24 16:45:28 +0000245 /// multiple load/stores of the same address. The usage of WeakTrackingVH
246 /// enables SunkAddrs to be treated as a cache whose entries can be
247 /// invalidated if a sunken address computation has been erased.
248 ValueMap<Value*, WeakTrackingVH> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000249
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000250 /// Keeps track of all instructions inserted for the current function.
251 SetOfInstrs InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000252
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000253 /// Keeps track of the type of the related instruction before their
254 /// promotion for the current function.
255 InstrToOrigTy PromotedInsts;
256
Jun Bum Limdee55652017-04-03 19:20:07 +0000257 /// Keep track of instructions removed during promotion.
258 SetOfInstrs RemovedInsts;
259
260 /// Keep track of sext chains based on their initial value.
261 DenseMap<Value *, Instruction *> SeenChainsForSExt;
262
263 /// Keep track of SExt promoted.
264 ValueToSExts ValToSExtendedUses;
265
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000266 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000267 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000268
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000269 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000270 bool OptSize;
271
Mehdi Amini4fe37982015-07-07 18:45:17 +0000272 /// DataLayout for the Function being processed.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000273 const DataLayout *DL = nullptr;
Mehdi Amini4fe37982015-07-07 18:45:17 +0000274
Chris Lattnerf2836d12007-03-31 04:06:36 +0000275 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000276 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000277
278 CodeGenPrepare() : FunctionPass(ID) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000279 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
280 }
Eugene Zelenko900b6332017-08-29 22:32:07 +0000281
Craig Topper4584cd52014-03-07 09:26:03 +0000282 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000283
Mehdi Amini117296c2016-10-01 02:56:57 +0000284 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000285
Craig Topper4584cd52014-03-07 09:26:03 +0000286 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000287 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000288 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000289 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000290 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000291 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000292 }
293
Chris Lattnerf2836d12007-03-31 04:06:36 +0000294 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000295 bool eliminateFallThrough(Function &F);
296 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000297 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000298 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
299 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000300 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
301 bool isPreheader);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000302 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
303 bool optimizeInst(Instruction *I, bool &ModifiedDT);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000304 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000305 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000306 bool optimizeInlineAsmInst(CallInst *CS);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000307 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000308 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000309 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000310 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000311 bool optimizeSelectInst(SelectInst *SI);
312 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000313 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000314 bool optimizeExtractElementInst(Instruction *Inst);
315 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
316 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000317 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
318 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
319 bool tryToPromoteExts(TypePromotionTransaction &TPT,
320 const SmallVectorImpl<Instruction *> &Exts,
321 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
322 unsigned CreatedInstsCost = 0);
Jun Bum Limdee55652017-04-03 19:20:07 +0000323 bool mergeSExts(Function &F);
324 bool performAddressTypePromotion(
325 Instruction *&Inst,
326 bool AllowPromotionWithoutCommonHeader,
327 bool HasPromoted, TypePromotionTransaction &TPT,
328 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000329 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000330 bool simplifyOffsetableRelocate(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000331 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000332
333} // end anonymous namespace
Devang Patel09f162c2007-05-01 21:15:47 +0000334
Devang Patel8c78a0b2007-05-03 01:11:54 +0000335char CodeGenPrepare::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000336
Matthias Braun1527baa2017-05-25 21:26:32 +0000337INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000338 "Optimize for code generation", false, false)
Dehao Chen302b69c2016-10-18 20:42:47 +0000339INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000340INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000341 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000342
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000343FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000344
Chris Lattnerf2836d12007-03-31 04:06:36 +0000345bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000346 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000347 return false;
348
Mehdi Amini4fe37982015-07-07 18:45:17 +0000349 DL = &F.getParent()->getDataLayout();
350
Chris Lattnerf2836d12007-03-31 04:06:36 +0000351 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000352 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000353 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000354 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000355
Devang Patel8f606d72011-03-24 15:35:25 +0000356 ModifiedDT = false;
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000357 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
358 TM = &TPC->getTM<TargetMachine>();
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000359 SubtargetInfo = TM->getSubtargetImpl(F);
360 TLI = SubtargetInfo->getTargetLowering();
361 TRI = SubtargetInfo->getRegisterInfo();
362 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000363 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000364 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000365 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000366 BPI.reset(new BranchProbabilityInfo(F, *LI));
367 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000368 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000369
Easwaran Raman0d55b552017-11-14 19:31:51 +0000370 ProfileSummaryInfo *PSI =
371 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen302b69c2016-10-18 20:42:47 +0000372 if (ProfileGuidedSectionPrefix) {
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000373 if (PSI->isFunctionHotInCallGraph(&F, *BFI))
Dehao Chen302b69c2016-10-18 20:42:47 +0000374 F.setSectionPrefix(".hot");
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000375 else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
Teresa Johnson720d9b42017-05-09 01:43:24 +0000376 F.setSectionPrefix(".unlikely");
Dehao Chen302b69c2016-10-18 20:42:47 +0000377 }
378
Preston Gurdcdf540d2012-09-04 18:22:17 +0000379 /// This optimization identifies DIV instructions that can be
380 /// profitably bypassed and carried out with a shorter, faster divide.
Easwaran Raman0d55b552017-11-14 19:31:51 +0000381 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
382 TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000383 const DenseMap<unsigned int, unsigned int> &BypassWidths =
384 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000385 BasicBlock* BB = &*F.begin();
386 while (BB != nullptr) {
387 // bypassSlowDivision may create new BBs, but we don't want to reapply the
388 // optimization to those blocks.
389 BasicBlock* Next = BB->getNextNode();
390 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
391 BB = Next;
392 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000393 }
394
395 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000396 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000397 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000398
Devang Patel53771ba2011-08-18 00:50:51 +0000399 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000400 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000401 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000402 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000403
Geoff Berry5d534b62017-02-21 18:53:14 +0000404 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000405 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000406
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000407 // Split some critical edges where one of the sources is an indirect branch,
408 // to help generate sane code for PHIs involving such edges.
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000409 EverMadeChange |= SplitIndirectBrCriticalEdges(F);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000410
Chris Lattnerc3748562007-04-02 01:35:34 +0000411 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000412 while (MadeChange) {
413 MadeChange = false;
Jun Bum Limdee55652017-04-03 19:20:07 +0000414 SeenChainsForSExt.clear();
415 ValToSExtendedUses.clear();
416 RemovedInsts.clear();
Hans Wennborg02fbc712012-09-19 07:48:16 +0000417 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000418 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000419 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000420 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000421
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000422 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000423 if (ModifiedDTOnIteration)
424 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000425 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000426 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
427 MadeChange |= mergeSExts(F);
428
429 // Really free removed instructions during promotion.
430 for (Instruction *I : RemovedInsts)
Reid Kleckner96ab8722017-05-18 17:24:10 +0000431 I->deleteValue();
Jun Bum Limdee55652017-04-03 19:20:07 +0000432
Chris Lattnerf2836d12007-03-31 04:06:36 +0000433 EverMadeChange |= MadeChange;
434 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000435
436 SunkAddrs.clear();
437
Cameron Zwarich338d3622011-03-11 21:52:04 +0000438 if (!DisableBranchOpts) {
439 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000440 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000441 for (BasicBlock &BB : F) {
442 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
443 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000444 if (!MadeChange) continue;
445
446 for (SmallVectorImpl<BasicBlock*>::iterator
447 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
448 if (pred_begin(*II) == pred_end(*II))
449 WorkList.insert(*II);
450 }
451
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000452 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000453 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000454 while (!WorkList.empty()) {
455 BasicBlock *BB = *WorkList.begin();
456 WorkList.erase(BB);
457 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
458
459 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000460
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000461 for (SmallVectorImpl<BasicBlock*>::iterator
462 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
463 if (pred_begin(*II) == pred_end(*II))
464 WorkList.insert(*II);
465 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000466
Nadav Rotem70409992012-08-14 05:19:07 +0000467 // Merge pairs of basic blocks with unconditional branches, connected by
468 // a single edge.
469 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000470 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000471
Cameron Zwarich338d3622011-03-11 21:52:04 +0000472 EverMadeChange |= MadeChange;
473 }
474
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000475 if (!DisableGCOpts) {
476 SmallVector<Instruction *, 2> Statepoints;
477 for (BasicBlock &BB : F)
478 for (Instruction &I : BB)
479 if (isStatepoint(I))
480 Statepoints.push_back(&I);
481 for (auto &I : Statepoints)
482 EverMadeChange |= simplifyOffsetableRelocate(*I);
483 }
484
Chris Lattnerf2836d12007-03-31 04:06:36 +0000485 return EverMadeChange;
486}
487
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000488/// Merge basic blocks which are connected by a single edge, where one of the
489/// basic blocks has a single successor pointing to the other basic block,
490/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000491bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000492 bool Changed = false;
493 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000494 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000495 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000496 // If the destination block has a single pred, then this is a trivial
497 // edge, just collapse it.
498 BasicBlock *SinglePred = BB->getSinglePredecessor();
499
Evan Cheng64a223a2012-09-28 23:58:57 +0000500 // Don't merge if BB's address is taken.
501 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000502
503 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
504 if (Term && !Term->isConditional()) {
505 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000506 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000507 // Remember if SinglePred was the entry block of the function.
508 // If so, we will need to move BB back to the entry position.
509 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000510 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000511
512 if (isEntry && BB != &BB->getParent()->getEntryBlock())
513 BB->moveBefore(&BB->getParent()->getEntryBlock());
514
515 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000516 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000517 }
518 }
519 return Changed;
520}
521
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000522/// Find a destination block from BB if BB is mergeable empty block.
523BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
524 // If this block doesn't end with an uncond branch, ignore it.
525 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
526 if (!BI || !BI->isUnconditional())
527 return nullptr;
528
529 // If the instruction before the branch (skipping debug info) isn't a phi
530 // node, then other stuff is happening here.
531 BasicBlock::iterator BBI = BI->getIterator();
532 if (BBI != BB->begin()) {
533 --BBI;
534 while (isa<DbgInfoIntrinsic>(BBI)) {
535 if (BBI == BB->begin())
536 break;
537 --BBI;
538 }
539 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
540 return nullptr;
541 }
542
543 // Do not break infinite loops.
544 BasicBlock *DestBB = BI->getSuccessor(0);
545 if (DestBB == BB)
546 return nullptr;
547
548 if (!canMergeBlocks(BB, DestBB))
549 DestBB = nullptr;
550
551 return DestBB;
552}
553
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000554/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
555/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
556/// edges in ways that are non-optimal for isel. Start by eliminating these
557/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000558bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000559 SmallPtrSet<BasicBlock *, 16> Preheaders;
560 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
561 while (!LoopList.empty()) {
562 Loop *L = LoopList.pop_back_val();
563 LoopList.insert(LoopList.end(), L->begin(), L->end());
564 if (BasicBlock *Preheader = L->getLoopPreheader())
565 Preheaders.insert(Preheader);
566 }
567
Chris Lattnerc3748562007-04-02 01:35:34 +0000568 bool MadeChange = false;
569 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000570 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000571 BasicBlock *BB = &*I++;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000572 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
573 if (!DestBB ||
574 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000575 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000576
Sanjay Patelfc580a62015-09-21 23:03:16 +0000577 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000578 MadeChange = true;
579 }
580 return MadeChange;
581}
582
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000583bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
584 BasicBlock *DestBB,
585 bool isPreheader) {
586 // Do not delete loop preheaders if doing so would create a critical edge.
587 // Loop preheaders can be good locations to spill registers. If the
588 // preheader is deleted and we create a critical edge, registers may be
589 // spilled in the loop body instead.
590 if (!DisablePreheaderProtect && isPreheader &&
591 !(BB->getSinglePredecessor() &&
592 BB->getSinglePredecessor()->getSingleSuccessor()))
593 return false;
594
595 // Try to skip merging if the unique predecessor of BB is terminated by a
596 // switch or indirect branch instruction, and BB is used as an incoming block
597 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
598 // add COPY instructions in the predecessor of BB instead of BB (if it is not
599 // merged). Note that the critical edge created by merging such blocks wont be
600 // split in MachineSink because the jump table is not analyzable. By keeping
601 // such empty block (BB), ISel will place COPY instructions in BB, not in the
602 // predecessor of BB.
603 BasicBlock *Pred = BB->getUniquePredecessor();
604 if (!Pred ||
605 !(isa<SwitchInst>(Pred->getTerminator()) ||
606 isa<IndirectBrInst>(Pred->getTerminator())))
607 return true;
608
609 if (BB->getTerminator() != BB->getFirstNonPHI())
610 return true;
611
612 // We use a simple cost heuristic which determine skipping merging is
613 // profitable if the cost of skipping merging is less than the cost of
614 // merging : Cost(skipping merging) < Cost(merging BB), where the
615 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
616 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
617 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
618 // Freq(Pred) / Freq(BB) > 2.
619 // Note that if there are multiple empty blocks sharing the same incoming
620 // value for the PHIs in the DestBB, we consider them together. In such
621 // case, Cost(merging BB) will be the sum of their frequencies.
622
623 if (!isa<PHINode>(DestBB->begin()))
624 return true;
625
626 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
627
628 // Find all other incoming blocks from which incoming values of all PHIs in
629 // DestBB are the same as the ones from BB.
630 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
631 ++PI) {
632 BasicBlock *DestBBPred = *PI;
633 if (DestBBPred == BB)
634 continue;
635
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000636 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
637 return DestPN.getIncomingValueForBlock(BB) ==
638 DestPN.getIncomingValueForBlock(DestBBPred);
639 }))
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000640 SameIncomingValueBBs.insert(DestBBPred);
641 }
642
643 // See if all BB's incoming values are same as the value from Pred. In this
644 // case, no reason to skip merging because COPYs are expected to be place in
645 // Pred already.
646 if (SameIncomingValueBBs.count(Pred))
647 return true;
648
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000649 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
650 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
651
652 for (auto SameValueBB : SameIncomingValueBBs)
653 if (SameValueBB->getUniquePredecessor() == Pred &&
654 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
655 BBFreq += BFI->getBlockFreq(SameValueBB);
656
657 return PredFreq.getFrequency() <=
658 BBFreq.getFrequency() * FreqRatioToSkipMerge;
659}
660
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000661/// Return true if we can merge BB into DestBB if there is a single
662/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000663/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000664bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000665 const BasicBlock *DestBB) const {
666 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
667 // the successor. If there are more complex condition (e.g. preheaders),
668 // don't mess around with them.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000669 for (const PHINode &PN : BB->phis()) {
670 for (const User *U : PN.users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000671 const Instruction *UI = cast<Instruction>(U);
672 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000673 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000674 // If User is inside DestBB block and it is a PHINode then check
675 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000676 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000677 if (UI->getParent() == DestBB) {
678 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000679 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
680 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
681 if (Insn && Insn->getParent() == BB &&
682 Insn->getParent() != UPN->getIncomingBlock(I))
683 return false;
684 }
685 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000686 }
687 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000688
Chris Lattnerc3748562007-04-02 01:35:34 +0000689 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
690 // and DestBB may have conflicting incoming values for the block. If so, we
691 // can't merge the block.
692 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
693 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000694
Chris Lattnerc3748562007-04-02 01:35:34 +0000695 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000696 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000697 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
698 // It is faster to get preds from a PHI than with pred_iterator.
699 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
700 BBPreds.insert(BBPN->getIncomingBlock(i));
701 } else {
702 BBPreds.insert(pred_begin(BB), pred_end(BB));
703 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000704
Chris Lattnerc3748562007-04-02 01:35:34 +0000705 // Walk the preds of DestBB.
706 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
707 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
708 if (BBPreds.count(Pred)) { // Common predecessor?
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000709 for (const PHINode &PN : DestBB->phis()) {
710 const Value *V1 = PN.getIncomingValueForBlock(Pred);
711 const Value *V2 = PN.getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000712
Chris Lattnerc3748562007-04-02 01:35:34 +0000713 // If V2 is a phi node in BB, look up what the mapped value will be.
714 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
715 if (V2PN->getParent() == BB)
716 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000717
Chris Lattnerc3748562007-04-02 01:35:34 +0000718 // If there is a conflict, bail out.
719 if (V1 != V2) return false;
720 }
721 }
722 }
723
724 return true;
725}
726
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000727/// Eliminate a basic block that has only phi's and an unconditional branch in
728/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000729void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000730 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
731 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000732
David Greene74e2d492010-01-05 01:27:11 +0000733 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000734
Chris Lattnerc3748562007-04-02 01:35:34 +0000735 // If the destination block has a single pred, then this is a trivial edge,
736 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000737 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000738 if (SinglePred != DestBB) {
739 // Remember if SinglePred was the entry block of the function. If so, we
740 // will need to move BB back to the entry position.
741 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Balaram Makam32bcb5d2017-10-27 00:35:18 +0000742 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000743
Chris Lattner8a172da2008-11-28 19:54:49 +0000744 if (isEntry && BB != &BB->getParent()->getEntryBlock())
745 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000746
David Greene74e2d492010-01-05 01:27:11 +0000747 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000748 return;
749 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000750 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000751
Chris Lattnerc3748562007-04-02 01:35:34 +0000752 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
753 // to handle the new incoming edges it is about to have.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000754 for (PHINode &PN : DestBB->phis()) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000755 // Remove the incoming value for BB, and remember it.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000756 Value *InVal = PN.removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000757
Chris Lattnerc3748562007-04-02 01:35:34 +0000758 // Two options: either the InVal is a phi node defined in BB or it is some
759 // value that dominates BB.
760 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
761 if (InValPhi && InValPhi->getParent() == BB) {
762 // Add all of the input values of the input PHI as inputs of this phi.
763 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000764 PN.addIncoming(InValPhi->getIncomingValue(i),
765 InValPhi->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000766 } else {
767 // Otherwise, add one instance of the dominating value for each edge that
768 // we will be adding.
769 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
770 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000771 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000772 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000773 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000774 PN.addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000775 }
776 }
777 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000778
Chris Lattnerc3748562007-04-02 01:35:34 +0000779 // The PHIs are now updated, change everything that refers to BB to use
780 // DestBB and remove BB.
781 BB->replaceAllUsesWith(DestBB);
782 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000783 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000784
David Greene74e2d492010-01-05 01:27:11 +0000785 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000786}
787
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000788// Computes a map of base pointer relocation instructions to corresponding
789// derived pointer relocation instructions given a vector of all relocate calls
790static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000791 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
792 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
793 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000794 // Collect information in two maps: one primarily for locating the base object
795 // while filling the second map; the second map is the final structure holding
796 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000797 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
798 for (auto *ThisRelocate : AllRelocateCalls) {
799 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
800 ThisRelocate->getDerivedPtrIndex());
801 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000802 }
803 for (auto &Item : RelocateIdxMap) {
804 std::pair<unsigned, unsigned> Key = Item.first;
805 if (Key.first == Key.second)
806 // Base relocation: nothing to insert
807 continue;
808
Manuel Jacob83eefa62016-01-05 04:03:00 +0000809 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000810 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000811
812 // We're iterating over RelocateIdxMap so we cannot modify it.
813 auto MaybeBase = RelocateIdxMap.find(BaseKey);
814 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000815 // TODO: We might want to insert a new base object relocate and gep off
816 // that, if there are enough derived object relocates.
817 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000818
819 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000820 }
821}
822
823// Accepts a GEP and extracts the operands into a vector provided they're all
824// small integer constants
825static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
826 SmallVectorImpl<Value *> &OffsetV) {
827 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
828 // Only accept small constant integer operands
829 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
830 if (!Op || Op->getZExtValue() > 20)
831 return false;
832 }
833
834 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
835 OffsetV.push_back(GEP->getOperand(i));
836 return true;
837}
838
839// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
840// replace, computes a replacement, and affects it.
841static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000842simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
843 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000844 bool MadeChange = false;
Serguei Katkov9e5604d2017-08-17 05:48:30 +0000845 // We must ensure the relocation of derived pointer is defined after
846 // relocation of base pointer. If we find a relocation corresponding to base
847 // defined earlier than relocation of base then we move relocation of base
848 // right before found relocation. We consider only relocation in the same
849 // basic block as relocation of base. Relocations from other basic block will
850 // be skipped by optimization and we do not care about them.
851 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
852 &*R != RelocatedBase; ++R)
853 if (auto RI = dyn_cast<GCRelocateInst>(R))
854 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
855 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
856 RelocatedBase->moveBefore(RI);
857 break;
858 }
859
Manuel Jacob83eefa62016-01-05 04:03:00 +0000860 for (GCRelocateInst *ToReplace : Targets) {
861 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000862 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000863 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000864 // A duplicate relocate call. TODO: coalesce duplicates.
865 continue;
866 }
867
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000868 if (RelocatedBase->getParent() != ToReplace->getParent()) {
869 // Base and derived relocates are in different basic blocks.
870 // In this case transform is only valid when base dominates derived
871 // relocate. However it would be too expensive to check dominance
872 // for each such relocate, so we skip the whole transformation.
873 continue;
874 }
875
Manuel Jacob83eefa62016-01-05 04:03:00 +0000876 Value *Base = ToReplace->getBasePtr();
877 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000878 if (!Derived || Derived->getPointerOperand() != Base)
879 continue;
880
881 SmallVector<Value *, 2> OffsetV;
882 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
883 continue;
884
885 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000886 assert(RelocatedBase->getNextNode() &&
887 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000888
889 // Insert after RelocatedBase
890 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000891 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000892
893 // If gc_relocate does not match the actual type, cast it to the right type.
894 // In theory, there must be a bitcast after gc_relocate if the type does not
895 // match, and we should reuse it to get the derived pointer. But it could be
896 // cases like this:
897 // bb1:
898 // ...
899 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
900 // br label %merge
901 //
902 // bb2:
903 // ...
904 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
905 // br label %merge
906 //
907 // merge:
908 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
909 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
910 //
911 // In this case, we can not find the bitcast any more. So we insert a new bitcast
912 // no matter there is already one or not. In this way, we can handle all cases, and
913 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000914 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000915 if (RelocatedBase->getType() != Base->getType()) {
916 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000917 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000918 }
David Blaikie68d535c2015-03-24 22:38:16 +0000919 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000920 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000921 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000922 // If the newly generated derived pointer's type does not match the original derived
923 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000924 Value *ActualReplacement = Replacement;
925 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000926 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000927 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000928 }
929 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000930 ToReplace->eraseFromParent();
931
932 MadeChange = true;
933 }
934 return MadeChange;
935}
936
937// Turns this:
938//
939// %base = ...
940// %ptr = gep %base + 15
941// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
942// %base' = relocate(%tok, i32 4, i32 4)
943// %ptr' = relocate(%tok, i32 4, i32 5)
944// %val = load %ptr'
945//
946// into this:
947//
948// %base = ...
949// %ptr = gep %base + 15
950// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
951// %base' = gc.relocate(%tok, i32 4, i32 4)
952// %ptr' = gep %base' + 15
953// %val = load %ptr'
954bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
955 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000956 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000957
958 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000959 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000960 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000961 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000962
963 // We need atleast one base pointer relocation + one derived pointer
964 // relocation to mangle
965 if (AllRelocateCalls.size() < 2)
966 return false;
967
968 // RelocateInstMap is a mapping from the base relocate instruction to the
969 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +0000970 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000971 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
972 if (RelocateInstMap.empty())
973 return false;
974
975 for (auto &Item : RelocateInstMap)
976 // Item.first is the RelocatedBase to offset against
977 // Item.second is the vector of Targets to replace
978 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
979 return MadeChange;
980}
981
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000982/// SinkCast - Sink the specified cast instruction into its user blocks
983static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000984 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000985
Chris Lattnerf2836d12007-03-31 04:06:36 +0000986 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000987 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000988
Chris Lattnerf2836d12007-03-31 04:06:36 +0000989 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000990 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000991 UI != E; ) {
992 Use &TheUse = UI.getUse();
993 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000994
Chris Lattnerf2836d12007-03-31 04:06:36 +0000995 // Figure out which BB this cast is used in. For PHI's this is the
996 // appropriate predecessor block.
997 BasicBlock *UserBB = User->getParent();
998 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000999 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001000 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001001
Chris Lattnerf2836d12007-03-31 04:06:36 +00001002 // Preincrement use iterator so we don't invalidate it.
1003 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001004
David Majnemer0c80e2e2016-04-27 19:36:38 +00001005 // The first insertion point of a block containing an EH pad is after the
1006 // pad. If the pad is the user, we cannot sink the cast past the pad.
1007 if (User->isEHPad())
1008 continue;
1009
Andrew Kaylord0430e82015-11-23 19:16:15 +00001010 // If the block selected to receive the cast is an EH pad that does not
1011 // allow non-PHI instructions before the terminator, we can't sink the
1012 // cast.
1013 if (UserBB->getTerminator()->isEHPad())
1014 continue;
1015
Chris Lattnerf2836d12007-03-31 04:06:36 +00001016 // If this user is in the same block as the cast, don't change the cast.
1017 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001018
Chris Lattnerf2836d12007-03-31 04:06:36 +00001019 // If we have already inserted a cast into this block, use it.
1020 CastInst *&InsertedCast = InsertedCasts[UserBB];
1021
1022 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001023 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001024 assert(InsertPt != UserBB->end());
1025 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1026 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001027 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001028
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001029 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001030 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001031 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001032 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001033 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001034
Chris Lattnerf2836d12007-03-31 04:06:36 +00001035 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001036 if (CI->use_empty()) {
Adrian Prantl261ac8b2017-11-03 21:55:03 +00001037 salvageDebugInfo(*CI);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001038 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001039 MadeChange = true;
1040 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001041
Chris Lattnerf2836d12007-03-31 04:06:36 +00001042 return MadeChange;
1043}
1044
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001045/// If the specified cast instruction is a noop copy (e.g. it's casting from
1046/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1047/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001048///
1049/// Return true if any changes are made.
Mehdi Amini44ede332015-07-09 02:09:04 +00001050static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1051 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001052 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1053 // than sinking only nop casts, but is helpful on some platforms.
1054 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1055 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1056 ASC->getDestAddressSpace()))
1057 return false;
1058 }
1059
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001060 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001061 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1062 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001063
1064 // This is an fp<->int conversion?
1065 if (SrcVT.isInteger() != DstVT.isInteger())
1066 return false;
1067
1068 // If this is an extension, it will be a zero or sign extension, which
1069 // isn't a noop.
1070 if (SrcVT.bitsLT(DstVT)) return false;
1071
1072 // If these values will be promoted, find out what they will be promoted
1073 // to. This helps us consider truncates on PPC as noop copies when they
1074 // are.
1075 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1076 TargetLowering::TypePromoteInteger)
1077 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1078 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1079 TargetLowering::TypePromoteInteger)
1080 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1081
1082 // If, after promotion, these are the same types, this is a noop copy.
1083 if (SrcVT != DstVT)
1084 return false;
1085
1086 return SinkCast(CI);
1087}
1088
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001089/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1090/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001091///
1092/// Return true if any changes were made.
1093static bool CombineUAddWithOverflow(CmpInst *CI) {
1094 Value *A, *B;
1095 Instruction *AddI;
1096 if (!match(CI,
1097 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1098 return false;
1099
1100 Type *Ty = AddI->getType();
1101 if (!isa<IntegerType>(Ty))
1102 return false;
1103
1104 // We don't want to move around uses of condition values this late, so we we
1105 // check if it is legal to create the call to the intrinsic in the basic
1106 // block containing the icmp:
1107
1108 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1109 return false;
1110
1111#ifndef NDEBUG
1112 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1113 // for now:
1114 if (AddI->hasOneUse())
1115 assert(*AddI->user_begin() == CI && "expected!");
1116#endif
1117
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001118 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001119 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1120
1121 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1122
1123 auto *UAddWithOverflow =
1124 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1125 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1126 auto *Overflow =
1127 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1128
1129 CI->replaceAllUsesWith(Overflow);
1130 AddI->replaceAllUsesWith(UAdd);
1131 CI->eraseFromParent();
1132 AddI->eraseFromParent();
1133 return true;
1134}
1135
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001136/// Sink the given CmpInst into user blocks to reduce the number of virtual
1137/// registers that must be created and coalesced. This is a clear win except on
1138/// targets with multiple condition code registers (PowerPC), where it might
1139/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001140///
1141/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001142static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001143 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001144
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001145 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001146 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001147 return false;
1148
1149 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001150 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001151
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001152 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001153 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001154 UI != E; ) {
1155 Use &TheUse = UI.getUse();
1156 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001157
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001158 // Preincrement use iterator so we don't invalidate it.
1159 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001160
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001161 // Don't bother for PHI nodes.
1162 if (isa<PHINode>(User))
1163 continue;
1164
1165 // Figure out which BB this cmp is used in.
1166 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001167
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001168 // If this user is in the same block as the cmp, don't change the cmp.
1169 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001170
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001171 // If we have already inserted a cmp into this block, use it.
1172 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1173
1174 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001175 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001176 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001177 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001178 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1179 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001180 // Propagate the debug info.
1181 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001182 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001183
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001184 // Replace a use of the cmp with a use of the new cmp.
1185 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001186 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001187 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001188 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001189
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001190 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001191 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001192 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001193 MadeChange = true;
1194 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001195
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001196 return MadeChange;
1197}
1198
Peter Zotovf87e5502016-04-03 17:11:53 +00001199static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001200 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001201 return true;
1202
1203 if (CombineUAddWithOverflow(CI))
1204 return true;
1205
1206 return false;
1207}
1208
Geoff Berry5d534b62017-02-21 18:53:14 +00001209/// Duplicate and sink the given 'and' instruction into user blocks where it is
1210/// used in a compare to allow isel to generate better code for targets where
1211/// this operation can be combined.
1212///
1213/// Return true if any changes are made.
1214static bool sinkAndCmp0Expression(Instruction *AndI,
1215 const TargetLowering &TLI,
1216 SetOfInstrs &InsertedInsts) {
1217 // Double-check that we're not trying to optimize an instruction that was
1218 // already optimized by some other part of this pass.
1219 assert(!InsertedInsts.count(AndI) &&
1220 "Attempting to optimize already optimized and instruction");
1221 (void) InsertedInsts;
1222
1223 // Nothing to do for single use in same basic block.
1224 if (AndI->hasOneUse() &&
1225 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1226 return false;
1227
1228 // Try to avoid cases where sinking/duplicating is likely to increase register
1229 // pressure.
1230 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1231 !isa<ConstantInt>(AndI->getOperand(1)) &&
1232 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1233 return false;
1234
1235 for (auto *U : AndI->users()) {
1236 Instruction *User = cast<Instruction>(U);
1237
1238 // Only sink for and mask feeding icmp with 0.
1239 if (!isa<ICmpInst>(User))
1240 return false;
1241
1242 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1243 if (!CmpC || !CmpC->isZero())
1244 return false;
1245 }
1246
1247 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1248 return false;
1249
1250 DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1251 DEBUG(AndI->getParent()->dump());
1252
1253 // Push the 'and' into the same block as the icmp 0. There should only be
1254 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1255 // others, so we don't need to keep track of which BBs we insert into.
1256 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1257 UI != E; ) {
1258 Use &TheUse = UI.getUse();
1259 Instruction *User = cast<Instruction>(*UI);
1260
1261 // Preincrement use iterator so we don't invalidate it.
1262 ++UI;
1263
1264 DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1265
1266 // Keep the 'and' in the same place if the use is already in the same block.
1267 Instruction *InsertPt =
1268 User->getParent() == AndI->getParent() ? AndI : User;
1269 Instruction *InsertedAnd =
1270 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1271 AndI->getOperand(1), "", InsertPt);
1272 // Propagate the debug info.
1273 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1274
1275 // Replace a use of the 'and' with a use of the new 'and'.
1276 TheUse = InsertedAnd;
1277 ++NumAndUses;
1278 DEBUG(User->getParent()->dump());
1279 }
1280
1281 // We removed all uses, nuke the and.
1282 AndI->eraseFromParent();
1283 return true;
1284}
1285
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001286/// Check if the candidates could be combined with a shift instruction, which
1287/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001288/// 1. Truncate instruction
1289/// 2. And instruction and the imm is a mask of the low bits:
1290/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001291static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001292 if (!isa<TruncInst>(User)) {
1293 if (User->getOpcode() != Instruction::And ||
1294 !isa<ConstantInt>(User->getOperand(1)))
1295 return false;
1296
Quentin Colombetd4f44692014-04-22 01:20:34 +00001297 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001298
Quentin Colombetd4f44692014-04-22 01:20:34 +00001299 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001300 return false;
1301 }
1302 return true;
1303}
1304
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001305/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001306static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001307SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1308 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001309 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001310 BasicBlock *UserBB = User->getParent();
1311 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1312 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1313 bool MadeChange = false;
1314
1315 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1316 TruncE = TruncI->user_end();
1317 TruncUI != TruncE;) {
1318
1319 Use &TruncTheUse = TruncUI.getUse();
1320 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1321 // Preincrement use iterator so we don't invalidate it.
1322
1323 ++TruncUI;
1324
1325 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1326 if (!ISDOpcode)
1327 continue;
1328
Tim Northovere2239ff2014-07-29 10:20:22 +00001329 // If the use is actually a legal node, there will not be an
1330 // implicit truncate.
1331 // FIXME: always querying the result type is just an
1332 // approximation; some nodes' legality is determined by the
1333 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001334 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001335 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001336 continue;
1337
1338 // Don't bother for PHI nodes.
1339 if (isa<PHINode>(TruncUser))
1340 continue;
1341
1342 BasicBlock *TruncUserBB = TruncUser->getParent();
1343
1344 if (UserBB == TruncUserBB)
1345 continue;
1346
1347 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1348 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1349
1350 if (!InsertedShift && !InsertedTrunc) {
1351 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001352 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001353 // Sink the shift
1354 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001355 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1356 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001357 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001358 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1359 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001360
1361 // Sink the trunc
1362 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1363 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001364 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001365
1366 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001367 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001368
1369 MadeChange = true;
1370
1371 TruncTheUse = InsertedTrunc;
1372 }
1373 }
1374 return MadeChange;
1375}
1376
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001377/// Sink the shift *right* instruction into user blocks if the uses could
1378/// potentially be combined with this shift instruction and generate BitExtract
1379/// instruction. It will only be applied if the architecture supports BitExtract
1380/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001381/// BB1:
1382/// %x.extract.shift = lshr i64 %arg1, 32
1383/// BB2:
1384/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1385/// ==>
1386///
1387/// BB2:
1388/// %x.extract.shift.1 = lshr i64 %arg1, 32
1389/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1390///
1391/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1392/// instruction.
1393/// Return true if any changes are made.
1394static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001395 const TargetLowering &TLI,
1396 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001397 BasicBlock *DefBB = ShiftI->getParent();
1398
1399 /// Only insert instructions in each block once.
1400 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1401
Mehdi Amini44ede332015-07-09 02:09:04 +00001402 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001403
1404 bool MadeChange = false;
1405 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1406 UI != E;) {
1407 Use &TheUse = UI.getUse();
1408 Instruction *User = cast<Instruction>(*UI);
1409 // Preincrement use iterator so we don't invalidate it.
1410 ++UI;
1411
1412 // Don't bother for PHI nodes.
1413 if (isa<PHINode>(User))
1414 continue;
1415
1416 if (!isExtractBitsCandidateUse(User))
1417 continue;
1418
1419 BasicBlock *UserBB = User->getParent();
1420
1421 if (UserBB == DefBB) {
1422 // If the shift and truncate instruction are in the same BB. The use of
1423 // the truncate(TruncUse) may still introduce another truncate if not
1424 // legal. In this case, we would like to sink both shift and truncate
1425 // instruction to the BB of TruncUse.
1426 // for example:
1427 // BB1:
1428 // i64 shift.result = lshr i64 opnd, imm
1429 // trunc.result = trunc shift.result to i16
1430 //
1431 // BB2:
1432 // ----> We will have an implicit truncate here if the architecture does
1433 // not have i16 compare.
1434 // cmp i16 trunc.result, opnd2
1435 //
1436 if (isa<TruncInst>(User) && shiftIsLegal
1437 // If the type of the truncate is legal, no trucate will be
1438 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001439 &&
1440 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001441 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001442 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001443
1444 continue;
1445 }
1446 // If we have already inserted a shift into this block, use it.
1447 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1448
1449 if (!InsertedShift) {
1450 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001451 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001452
1453 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001454 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1455 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001456 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001457 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1458 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001459
1460 MadeChange = true;
1461 }
1462
1463 // Replace a use of the shift with a use of the new shift.
1464 TheUse = InsertedShift;
1465 }
1466
1467 // If we removed all uses, nuke the shift.
1468 if (ShiftI->use_empty())
1469 ShiftI->eraseFromParent();
1470
1471 return MadeChange;
1472}
1473
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001474/// If counting leading or trailing zeros is an expensive operation and a zero
1475/// input is defined, add a check for zero to avoid calling the intrinsic.
1476///
1477/// We want to transform:
1478/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1479///
1480/// into:
1481/// entry:
1482/// %cmpz = icmp eq i64 %A, 0
1483/// br i1 %cmpz, label %cond.end, label %cond.false
1484/// cond.false:
1485/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1486/// br label %cond.end
1487/// cond.end:
1488/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1489///
1490/// If the transform is performed, return true and set ModifiedDT to true.
1491static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1492 const TargetLowering *TLI,
1493 const DataLayout *DL,
1494 bool &ModifiedDT) {
1495 if (!TLI || !DL)
1496 return false;
1497
1498 // If a zero input is undefined, it doesn't make sense to despeculate that.
1499 if (match(CountZeros->getOperand(1), m_One()))
1500 return false;
1501
1502 // If it's cheap to speculate, there's nothing to do.
1503 auto IntrinsicID = CountZeros->getIntrinsicID();
1504 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1505 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1506 return false;
1507
1508 // Only handle legal scalar cases. Anything else requires too much work.
1509 Type *Ty = CountZeros->getType();
1510 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001511 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001512 return false;
1513
1514 // The intrinsic will be sunk behind a compare against zero and branch.
1515 BasicBlock *StartBlock = CountZeros->getParent();
1516 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1517
1518 // Create another block after the count zero intrinsic. A PHI will be added
1519 // in this block to select the result of the intrinsic or the bit-width
1520 // constant if the input to the intrinsic is zero.
1521 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1522 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1523
1524 // Set up a builder to create a compare, conditional branch, and PHI.
1525 IRBuilder<> Builder(CountZeros->getContext());
1526 Builder.SetInsertPoint(StartBlock->getTerminator());
1527 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1528
1529 // Replace the unconditional branch that was created by the first split with
1530 // a compare against zero and a conditional branch.
1531 Value *Zero = Constant::getNullValue(Ty);
1532 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1533 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1534 StartBlock->getTerminator()->eraseFromParent();
1535
1536 // Create a PHI in the end block to select either the output of the intrinsic
1537 // or the bit width of the operand.
1538 Builder.SetInsertPoint(&EndBlock->front());
1539 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1540 CountZeros->replaceAllUsesWith(PN);
1541 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1542 PN->addIncoming(BitWidth, StartBlock);
1543 PN->addIncoming(CountZeros, CallBlock);
1544
1545 // We are explicitly handling the zero case, so we can set the intrinsic's
1546 // undefined zero argument to 'true'. This will also prevent reprocessing the
1547 // intrinsic; we only despeculate when a zero input is defined.
1548 CountZeros->setArgOperand(1, Builder.getTrue());
1549 ModifiedDT = true;
1550 return true;
1551}
1552
Sanjay Patel3b8974b2017-06-08 20:00:09 +00001553bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001554 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001555
Chris Lattner7a277142011-01-15 07:14:54 +00001556 // Lower inline assembly if we can.
1557 // If we found an inline asm expession, and if the target knows how to
1558 // lower it to normal LLVM code, do so now.
1559 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1560 if (TLI->ExpandInlineAsm(CI)) {
1561 // Avoid invalidating the iterator.
1562 CurInstIterator = BB->begin();
1563 // Avoid processing instructions out of order, which could cause
1564 // reuse before a value is defined.
1565 SunkAddrs.clear();
1566 return true;
1567 }
1568 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001569 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001570 return true;
1571 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001572
John Brawn0dbcd652015-03-18 12:01:59 +00001573 // Align the pointer arguments to this call if the target thinks it's a good
1574 // idea
1575 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001576 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001577 for (auto &Arg : CI->arg_operands()) {
1578 // We want to align both objects whose address is used directly and
1579 // objects whose address is used in casts and GEPs, though it only makes
1580 // sense for GEPs if the offset is a multiple of the desired alignment and
1581 // if size - offset meets the size threshold.
1582 if (!Arg->getType()->isPointerTy())
1583 continue;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001584 APInt Offset(DL->getIndexSizeInBits(
Mehdi Amini4fe37982015-07-07 18:45:17 +00001585 cast<PointerType>(Arg->getType())->getAddressSpace()),
1586 0);
1587 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001588 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001589 if ((Offset2 & (PrefAlign-1)) != 0)
1590 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001591 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001592 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1593 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001594 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001595 // Global variables can only be aligned if they are defined in this
1596 // object (i.e. they are uniquely initialized in this object), and
1597 // over-aligning global variables that have an explicit section is
1598 // forbidden.
1599 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001600 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001601 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001602 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001603 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001604 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001605 }
1606 // If this is a memcpy (or similar) then we may be able to improve the
1607 // alignment
1608 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Daniel Neilsonbe58a222018-01-31 17:24:53 +00001609 unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
1610 if (DestAlign > MI->getDestAlignment())
1611 MI->setDestAlignment(DestAlign);
1612 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1613 unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
1614 if (SrcAlign > MTI->getSourceAlignment())
1615 MTI->setSourceAlignment(SrcAlign);
1616 }
John Brawn0dbcd652015-03-18 12:01:59 +00001617 }
1618 }
1619
Philip Reamesac115ed2016-03-09 23:13:12 +00001620 // If we have a cold call site, try to sink addressing computation into the
1621 // cold block. This interacts with our handling for loads and stores to
1622 // ensure that we can fold all uses of a potential addressing computation
1623 // into their uses. TODO: generalize this to work over profiling data
1624 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1625 for (auto &Arg : CI->arg_operands()) {
1626 if (!Arg->getType()->isPointerTy())
1627 continue;
1628 unsigned AS = Arg->getType()->getPointerAddressSpace();
1629 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1630 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001631
Eric Christopher4b7948e2010-03-11 02:41:03 +00001632 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001633 if (II) {
1634 switch (II->getIntrinsicID()) {
1635 default: break;
1636 case Intrinsic::objectsize: {
1637 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00001638 ConstantInt *RetVal =
1639 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001640 // Substituting this can cause recursive simplifications, which can
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001641 // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case
1642 // this
Sanjoy Das2cbeb002017-04-26 16:37:05 +00001643 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001644 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001645 WeakTrackingVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001646
Sanjay Patel545a4562016-01-20 18:59:16 +00001647 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001648
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001649 // If the iterator instruction was recursively deleted, start over at the
1650 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001651 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001652 CurInstIterator = BB->begin();
1653 SunkAddrs.clear();
1654 }
1655 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001656 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001657 case Intrinsic::aarch64_stlxr:
1658 case Intrinsic::aarch64_stxr: {
1659 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1660 if (!ExtVal || !ExtVal->hasOneUse() ||
1661 ExtVal->getParent() == CI->getParent())
1662 return false;
1663 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1664 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001665 // Mark this instruction as "inserted by CGP", so that other
1666 // optimizations don't touch it.
1667 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001668 return true;
1669 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001670 case Intrinsic::invariant_group_barrier:
1671 II->replaceAllUsesWith(II->getArgOperand(0));
1672 II->eraseFromParent();
1673 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001674
1675 case Intrinsic::cttz:
1676 case Intrinsic::ctlz:
1677 // If counting zeros is expensive, try to avoid it.
1678 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001679 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001680
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001681 if (TLI) {
1682 SmallVector<Value*, 2> PtrOps;
1683 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001684 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1685 while (!PtrOps.empty()) {
1686 Value *PtrVal = PtrOps.pop_back_val();
1687 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1688 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001689 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001690 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001691 }
Pete Cooper615fd892012-03-13 20:59:56 +00001692 }
1693
Eric Christopher4b7948e2010-03-11 02:41:03 +00001694 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001695 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001696
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001697 // Lower all default uses of _chk calls. This is very similar
1698 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001699 // to fortified library functions (e.g. __memcpy_chk) that have the default
1700 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001701 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001702 if (Value *V = Simplifier.optimizeCall(CI)) {
1703 CI->replaceAllUsesWith(V);
1704 CI->eraseFromParent();
1705 return true;
1706 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001707
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001708 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001709}
Chris Lattner1b93be52011-01-15 07:25:29 +00001710
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001711/// Look for opportunities to duplicate return instructions to the predecessor
1712/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001713/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001714/// bb0:
1715/// %tmp0 = tail call i32 @f0()
1716/// br label %return
1717/// bb1:
1718/// %tmp1 = tail call i32 @f1()
1719/// br label %return
1720/// bb2:
1721/// %tmp2 = tail call i32 @f2()
1722/// br label %return
1723/// return:
1724/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1725/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001726/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001727///
1728/// =>
1729///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001730/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001731/// bb0:
1732/// %tmp0 = tail call i32 @f0()
1733/// ret i32 %tmp0
1734/// bb1:
1735/// %tmp1 = tail call i32 @f1()
1736/// ret i32 %tmp1
1737/// bb2:
1738/// %tmp2 = tail call i32 @f2()
1739/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001740/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001741bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001742 if (!TLI)
1743 return false;
1744
Michael Kuperstein71321562016-09-07 20:29:49 +00001745 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1746 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001747 return false;
1748
Craig Topperc0196b12014-04-14 00:51:57 +00001749 PHINode *PN = nullptr;
1750 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001751 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001752 if (V) {
1753 BCI = dyn_cast<BitCastInst>(V);
1754 if (BCI)
1755 V = BCI->getOperand(0);
1756
1757 PN = dyn_cast<PHINode>(V);
1758 if (!PN)
1759 return false;
1760 }
Evan Cheng0663f232011-03-21 01:19:09 +00001761
Cameron Zwarich4649f172011-03-24 04:52:10 +00001762 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001763 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001764
Cameron Zwarich4649f172011-03-24 04:52:10 +00001765 // Make sure there are no instructions between the PHI and return, or that the
1766 // return is the first instruction in the block.
1767 if (PN) {
1768 BasicBlock::iterator BI = BB->begin();
1769 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001770 if (&*BI == BCI)
1771 // Also skip over the bitcast.
1772 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001773 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001774 return false;
1775 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001776 BasicBlock::iterator BI = BB->begin();
1777 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001778 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001779 return false;
1780 }
Evan Cheng0663f232011-03-21 01:19:09 +00001781
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001782 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1783 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001784 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001785 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001786 if (PN) {
1787 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1788 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1789 // Make sure the phi value is indeed produced by the tail call.
1790 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001791 TLI->mayBeEmittedAsTailCall(CI) &&
1792 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001793 TailCalls.push_back(CI);
1794 }
1795 } else {
1796 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001797 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001798 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001799 continue;
1800
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001801 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001802 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1803 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001804 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1805 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001806 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001807
Cameron Zwarich4649f172011-03-24 04:52:10 +00001808 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001809 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1810 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001811 TailCalls.push_back(CI);
1812 }
Evan Cheng0663f232011-03-21 01:19:09 +00001813 }
1814
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001815 bool Changed = false;
1816 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1817 CallInst *CI = TailCalls[i];
1818 CallSite CS(CI);
1819
1820 // Conservatively require the attributes of the call to match those of the
1821 // return. Ignore noalias because it doesn't affect the call sequence.
Reid Klecknerb5180542017-03-21 16:57:19 +00001822 AttributeList CalleeAttrs = CS.getAttributes();
1823 if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1824 .removeAttribute(Attribute::NoAlias) !=
1825 AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1826 .removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001827 continue;
1828
1829 // Make sure the call instruction is followed by an unconditional branch to
1830 // the return block.
1831 BasicBlock *CallBB = CI->getParent();
1832 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1833 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1834 continue;
1835
1836 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00001837 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001838 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001839 ++NumRetsDup;
1840 }
1841
1842 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001843 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001844 BB->eraseFromParent();
1845
1846 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001847}
1848
Chris Lattner728f9022008-11-25 07:09:13 +00001849//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001850// Memory Optimization
1851//===----------------------------------------------------------------------===//
1852
Chandler Carruthc8925912013-01-05 02:09:22 +00001853namespace {
1854
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001855/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00001856/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001857struct ExtAddrMode : public TargetLowering::AddrMode {
Eugene Zelenko900b6332017-08-29 22:32:07 +00001858 Value *BaseReg = nullptr;
1859 Value *ScaledReg = nullptr;
John Brawn736bf002017-10-03 13:08:22 +00001860 Value *OriginalValue = nullptr;
1861
1862 enum FieldName {
1863 NoField = 0x00,
1864 BaseRegField = 0x01,
1865 BaseGVField = 0x02,
1866 BaseOffsField = 0x04,
1867 ScaledRegField = 0x08,
1868 ScaleField = 0x10,
1869 MultipleFields = 0xff
1870 };
Eugene Zelenko900b6332017-08-29 22:32:07 +00001871
1872 ExtAddrMode() = default;
1873
Chandler Carruthc8925912013-01-05 02:09:22 +00001874 void print(raw_ostream &OS) const;
1875 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001876
John Brawn736bf002017-10-03 13:08:22 +00001877 FieldName compare(const ExtAddrMode &other) {
1878 // First check that the types are the same on each field, as differing types
1879 // is something we can't cope with later on.
1880 if (BaseReg && other.BaseReg &&
1881 BaseReg->getType() != other.BaseReg->getType())
1882 return MultipleFields;
1883 if (BaseGV && other.BaseGV &&
1884 BaseGV->getType() != other.BaseGV->getType())
1885 return MultipleFields;
1886 if (ScaledReg && other.ScaledReg &&
1887 ScaledReg->getType() != other.ScaledReg->getType())
1888 return MultipleFields;
1889
1890 // Check each field to see if it differs.
1891 unsigned Result = NoField;
1892 if (BaseReg != other.BaseReg)
1893 Result |= BaseRegField;
1894 if (BaseGV != other.BaseGV)
1895 Result |= BaseGVField;
1896 if (BaseOffs != other.BaseOffs)
1897 Result |= BaseOffsField;
1898 if (ScaledReg != other.ScaledReg)
1899 Result |= ScaledRegField;
1900 // Don't count 0 as being a different scale, because that actually means
1901 // unscaled (which will already be counted by having no ScaledReg).
1902 if (Scale && other.Scale && Scale != other.Scale)
1903 Result |= ScaleField;
1904
1905 if (countPopulation(Result) > 1)
1906 return MultipleFields;
1907 else
1908 return static_cast<FieldName>(Result);
1909 }
1910
John Brawn4b476482017-11-27 11:29:15 +00001911 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
1912 // with no offset.
John Brawn736bf002017-10-03 13:08:22 +00001913 bool isTrivial() {
John Brawn4b476482017-11-27 11:29:15 +00001914 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
1915 // trivial if at most one of these terms is nonzero, except that BaseGV and
1916 // BaseReg both being zero actually means a null pointer value, which we
1917 // consider to be 'non-zero' here.
1918 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
Chandler Carruthc8925912013-01-05 02:09:22 +00001919 }
John Brawn70cdb5b2017-11-24 14:10:45 +00001920
1921 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
1922 switch (Field) {
1923 default:
1924 return nullptr;
1925 case BaseRegField:
1926 return BaseReg;
1927 case BaseGVField:
1928 return BaseGV;
1929 case ScaledRegField:
1930 return ScaledReg;
1931 case BaseOffsField:
1932 return ConstantInt::get(IntPtrTy, BaseOffs);
1933 }
1934 }
1935
1936 void SetCombinedField(FieldName Field, Value *V,
1937 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
1938 switch (Field) {
1939 default:
1940 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
1941 break;
1942 case ExtAddrMode::BaseRegField:
1943 BaseReg = V;
1944 break;
1945 case ExtAddrMode::BaseGVField:
1946 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
1947 // in the BaseReg field.
1948 assert(BaseReg == nullptr);
1949 BaseReg = V;
1950 BaseGV = nullptr;
1951 break;
1952 case ExtAddrMode::ScaledRegField:
1953 ScaledReg = V;
1954 // If we have a mix of scaled and unscaled addrmodes then we want scale
1955 // to be the scale and not zero.
1956 if (!Scale)
1957 for (const ExtAddrMode &AM : AddrModes)
1958 if (AM.Scale) {
1959 Scale = AM.Scale;
1960 break;
1961 }
1962 break;
1963 case ExtAddrMode::BaseOffsField:
1964 // The offset is no longer a constant, so it goes in ScaledReg with a
1965 // scale of 1.
1966 assert(ScaledReg == nullptr);
1967 ScaledReg = V;
1968 Scale = 1;
1969 BaseOffs = 0;
1970 break;
1971 }
1972 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001973};
1974
Eugene Zelenko900b6332017-08-29 22:32:07 +00001975} // end anonymous namespace
1976
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001977#ifndef NDEBUG
1978static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1979 AM.print(OS);
1980 return OS;
1981}
1982#endif
1983
Aaron Ballman615eb472017-10-15 14:32:27 +00001984#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthc8925912013-01-05 02:09:22 +00001985void ExtAddrMode::print(raw_ostream &OS) const {
1986 bool NeedPlus = false;
1987 OS << "[";
1988 if (BaseGV) {
1989 OS << (NeedPlus ? " + " : "")
1990 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001991 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001992 NeedPlus = true;
1993 }
1994
Richard Trieuc0f91212014-05-30 03:15:17 +00001995 if (BaseOffs) {
1996 OS << (NeedPlus ? " + " : "")
1997 << BaseOffs;
1998 NeedPlus = true;
1999 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002000
2001 if (BaseReg) {
2002 OS << (NeedPlus ? " + " : "")
2003 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002004 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002005 NeedPlus = true;
2006 }
2007 if (Scale) {
2008 OS << (NeedPlus ? " + " : "")
2009 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002010 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002011 }
2012
2013 OS << ']';
2014}
2015
Yaron Kereneb2a2542016-01-29 20:50:44 +00002016LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002017 print(dbgs());
2018 dbgs() << '\n';
2019}
2020#endif
2021
Eugene Zelenko900b6332017-08-29 22:32:07 +00002022namespace {
2023
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002024/// \brief This class provides transaction based operation on the IR.
2025/// Every change made through this class is recorded in the internal state and
2026/// can be undone (rollback) until commit is called.
2027class TypePromotionTransaction {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002028 /// \brief This represents the common interface of the individual transaction.
2029 /// Each class implements the logic for doing one specific modification on
2030 /// the IR via the TypePromotionTransaction.
2031 class TypePromotionAction {
2032 protected:
2033 /// The Instruction modified.
2034 Instruction *Inst;
2035
2036 public:
2037 /// \brief Constructor of the action.
2038 /// The constructor performs the related action on the IR.
2039 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2040
Eugene Zelenko900b6332017-08-29 22:32:07 +00002041 virtual ~TypePromotionAction() = default;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002042
2043 /// \brief Undo the modification done by this action.
2044 /// When this method is called, the IR must be in the same state as it was
2045 /// before this action was applied.
2046 /// \pre Undoing the action works if and only if the IR is in the exact same
2047 /// state as it was directly after this action was applied.
2048 virtual void undo() = 0;
2049
2050 /// \brief Advocate every change made by this action.
2051 /// When the results on the IR of the action are to be kept, it is important
2052 /// to call this function, otherwise hidden information may be kept forever.
2053 virtual void commit() {
2054 // Nothing to be done, this action is not doing anything.
2055 }
2056 };
2057
2058 /// \brief Utility to remember the position of an instruction.
2059 class InsertionHandler {
2060 /// Position of an instruction.
2061 /// Either an instruction:
2062 /// - Is the first in a basic block: BB is used.
2063 /// - Has a previous instructon: PrevInst is used.
2064 union {
2065 Instruction *PrevInst;
2066 BasicBlock *BB;
2067 } Point;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002068
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002069 /// Remember whether or not the instruction had a previous instruction.
2070 bool HasPrevInstruction;
2071
2072 public:
2073 /// \brief Record the position of \p Inst.
2074 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002075 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002076 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2077 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002078 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002079 else
2080 Point.BB = Inst->getParent();
2081 }
2082
2083 /// \brief Insert \p Inst at the recorded position.
2084 void insert(Instruction *Inst) {
2085 if (HasPrevInstruction) {
2086 if (Inst->getParent())
2087 Inst->removeFromParent();
2088 Inst->insertAfter(Point.PrevInst);
2089 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002090 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002091 if (Inst->getParent())
2092 Inst->moveBefore(Position);
2093 else
2094 Inst->insertBefore(Position);
2095 }
2096 }
2097 };
2098
2099 /// \brief Move an instruction before another.
2100 class InstructionMoveBefore : public TypePromotionAction {
2101 /// Original position of the instruction.
2102 InsertionHandler Position;
2103
2104 public:
2105 /// \brief Move \p Inst before \p Before.
2106 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2107 : TypePromotionAction(Inst), Position(Inst) {
2108 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2109 Inst->moveBefore(Before);
2110 }
2111
2112 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002113 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002114 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2115 Position.insert(Inst);
2116 }
2117 };
2118
2119 /// \brief Set the operand of an instruction with a new value.
2120 class OperandSetter : public TypePromotionAction {
2121 /// Original operand of the instruction.
2122 Value *Origin;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002123
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002124 /// Index of the modified instruction.
2125 unsigned Idx;
2126
2127 public:
2128 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2129 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2130 : TypePromotionAction(Inst), Idx(Idx) {
2131 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2132 << "for:" << *Inst << "\n"
2133 << "with:" << *NewVal << "\n");
2134 Origin = Inst->getOperand(Idx);
2135 Inst->setOperand(Idx, NewVal);
2136 }
2137
2138 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002139 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002140 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2141 << "for: " << *Inst << "\n"
2142 << "with: " << *Origin << "\n");
2143 Inst->setOperand(Idx, Origin);
2144 }
2145 };
2146
2147 /// \brief Hide the operands of an instruction.
2148 /// Do as if this instruction was not using any of its operands.
2149 class OperandsHider : public TypePromotionAction {
2150 /// The list of original operands.
2151 SmallVector<Value *, 4> OriginalValues;
2152
2153 public:
2154 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2155 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2156 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2157 unsigned NumOpnds = Inst->getNumOperands();
2158 OriginalValues.reserve(NumOpnds);
2159 for (unsigned It = 0; It < NumOpnds; ++It) {
2160 // Save the current operand.
2161 Value *Val = Inst->getOperand(It);
2162 OriginalValues.push_back(Val);
2163 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002164 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002165 // that we are not willing to pay.
2166 Inst->setOperand(It, UndefValue::get(Val->getType()));
2167 }
2168 }
2169
2170 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002171 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002172 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2173 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2174 Inst->setOperand(It, OriginalValues[It]);
2175 }
2176 };
2177
2178 /// \brief Build a truncate instruction.
2179 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002180 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002181
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002182 public:
2183 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2184 /// result.
2185 /// trunc Opnd to Ty.
2186 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2187 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002188 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2189 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002190 }
2191
Quentin Colombetac55b152014-09-16 22:36:07 +00002192 /// \brief Get the built value.
2193 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002194
2195 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002196 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002197 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2198 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2199 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002200 }
2201 };
2202
2203 /// \brief Build a sign extension instruction.
2204 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002205 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002206
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002207 public:
2208 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2209 /// result.
2210 /// sext Opnd to Ty.
2211 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002212 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002213 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002214 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2215 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002216 }
2217
Quentin Colombetac55b152014-09-16 22:36:07 +00002218 /// \brief Get the built value.
2219 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002220
2221 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002222 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002223 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2224 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2225 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002226 }
2227 };
2228
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002229 /// \brief Build a zero extension instruction.
2230 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002231 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002232
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002233 public:
2234 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2235 /// result.
2236 /// zext Opnd to Ty.
2237 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002238 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002239 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002240 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2241 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002242 }
2243
Quentin Colombetac55b152014-09-16 22:36:07 +00002244 /// \brief Get the built value.
2245 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002246
2247 /// \brief Remove the built instruction.
2248 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002249 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2250 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2251 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002252 }
2253 };
2254
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002255 /// \brief Mutate an instruction to another type.
2256 class TypeMutator : public TypePromotionAction {
2257 /// Record the original type.
2258 Type *OrigTy;
2259
2260 public:
2261 /// \brief Mutate the type of \p Inst into \p NewTy.
2262 TypeMutator(Instruction *Inst, Type *NewTy)
2263 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2264 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2265 << "\n");
2266 Inst->mutateType(NewTy);
2267 }
2268
2269 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002270 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002271 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2272 << "\n");
2273 Inst->mutateType(OrigTy);
2274 }
2275 };
2276
2277 /// \brief Replace the uses of an instruction by another instruction.
2278 class UsesReplacer : public TypePromotionAction {
2279 /// Helper structure to keep track of the replaced uses.
2280 struct InstructionAndIdx {
2281 /// The instruction using the instruction.
2282 Instruction *Inst;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002283
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002284 /// The index where this instruction is used for Inst.
2285 unsigned Idx;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002286
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002287 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2288 : Inst(Inst), Idx(Idx) {}
2289 };
2290
2291 /// Keep track of the original uses (pair Instruction, Index).
2292 SmallVector<InstructionAndIdx, 4> OriginalUses;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002293
2294 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002295
2296 public:
2297 /// \brief Replace all the use of \p Inst by \p New.
2298 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2299 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2300 << "\n");
2301 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002302 for (Use &U : Inst->uses()) {
2303 Instruction *UserI = cast<Instruction>(U.getUser());
2304 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002305 }
2306 // Now, we can replace the uses.
2307 Inst->replaceAllUsesWith(New);
2308 }
2309
2310 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002311 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002312 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2313 for (use_iterator UseIt = OriginalUses.begin(),
2314 EndIt = OriginalUses.end();
2315 UseIt != EndIt; ++UseIt) {
2316 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2317 }
2318 }
2319 };
2320
2321 /// \brief Remove an instruction from the IR.
2322 class InstructionRemover : public TypePromotionAction {
2323 /// Original position of the instruction.
2324 InsertionHandler Inserter;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002325
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002326 /// Helper structure to hide all the link to the instruction. In other
2327 /// words, this helps to do as if the instruction was removed.
2328 OperandsHider Hider;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002329
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002330 /// Keep track of the uses replaced, if any.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002331 UsesReplacer *Replacer = nullptr;
2332
Jun Bum Limdee55652017-04-03 19:20:07 +00002333 /// Keep track of instructions removed.
2334 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002335
2336 public:
2337 /// \brief Remove all reference of \p Inst and optinally replace all its
2338 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002339 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002340 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002341 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2342 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002343 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Eugene Zelenko900b6332017-08-29 22:32:07 +00002344 RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002345 if (New)
2346 Replacer = new UsesReplacer(Inst, New);
2347 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002348 RemovedInsts.insert(Inst);
2349 /// The instructions removed here will be freed after completing
2350 /// optimizeBlock() for all blocks as we need to keep track of the
2351 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002352 Inst->removeFromParent();
2353 }
2354
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002355 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002356
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002357 /// \brief Resurrect the instruction and reassign it to the proper uses if
2358 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002359 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002360 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2361 Inserter.insert(Inst);
2362 if (Replacer)
2363 Replacer->undo();
2364 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002365 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002366 }
2367 };
2368
2369public:
2370 /// Restoration point.
2371 /// The restoration point is a pointer to an action instead of an iterator
2372 /// because the iterator may be invalidated but not the pointer.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002373 using ConstRestorationPt = const TypePromotionAction *;
Jun Bum Limdee55652017-04-03 19:20:07 +00002374
2375 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2376 : RemovedInsts(RemovedInsts) {}
2377
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002378 /// Advocate every changes made in that transaction.
2379 void commit();
Eugene Zelenko900b6332017-08-29 22:32:07 +00002380
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002381 /// Undo all the changes made after the given point.
2382 void rollback(ConstRestorationPt Point);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002383
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002384 /// Get the current restoration point.
2385 ConstRestorationPt getRestorationPoint() const;
2386
2387 /// \name API for IR modification with state keeping to support rollback.
2388 /// @{
2389 /// Same as Instruction::setOperand.
2390 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002391
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002392 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002393 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002394
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002395 /// Same as Value::replaceAllUsesWith.
2396 void replaceAllUsesWith(Instruction *Inst, Value *New);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002397
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002398 /// Same as Value::mutateType.
2399 void mutateType(Instruction *Inst, Type *NewTy);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002400
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002401 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002402 Value *createTrunc(Instruction *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002403
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002404 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002405 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002406
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002407 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002408 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002409
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002410 /// Same as Instruction::moveBefore.
2411 void moveBefore(Instruction *Inst, Instruction *Before);
2412 /// @}
2413
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002414private:
2415 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002416 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002417
2418 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2419
Jun Bum Limdee55652017-04-03 19:20:07 +00002420 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002421};
2422
Eugene Zelenko900b6332017-08-29 22:32:07 +00002423} // end anonymous namespace
2424
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002425void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2426 Value *NewVal) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002427 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2428 Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002429}
2430
2431void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2432 Value *NewVal) {
2433 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002434 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2435 Inst, RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002436}
2437
2438void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2439 Value *New) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002440 Actions.push_back(
2441 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002442}
2443
2444void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002445 Actions.push_back(
2446 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002447}
2448
Quentin Colombetac55b152014-09-16 22:36:07 +00002449Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2450 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002451 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002452 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002453 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002454 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002455}
2456
Quentin Colombetac55b152014-09-16 22:36:07 +00002457Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2458 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002459 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002460 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002461 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002462 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002463}
2464
Quentin Colombetac55b152014-09-16 22:36:07 +00002465Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2466 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002467 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002468 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002469 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002470 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002471}
2472
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002473void TypePromotionTransaction::moveBefore(Instruction *Inst,
2474 Instruction *Before) {
2475 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002476 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2477 Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002478}
2479
2480TypePromotionTransaction::ConstRestorationPt
2481TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002482 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002483}
2484
2485void TypePromotionTransaction::commit() {
2486 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002487 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002488 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002489 Actions.clear();
2490}
2491
2492void TypePromotionTransaction::rollback(
2493 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002494 while (!Actions.empty() && Point != Actions.back().get()) {
2495 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002496 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002497 }
2498}
2499
Eugene Zelenko900b6332017-08-29 22:32:07 +00002500namespace {
2501
Chandler Carruthc8925912013-01-05 02:09:22 +00002502/// \brief A helper class for matching addressing modes.
2503///
2504/// This encapsulates the logic for matching the target-legal addressing modes.
2505class AddressingModeMatcher {
2506 SmallVectorImpl<Instruction*> &AddrModeInsts;
2507 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002508 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002509 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002510
2511 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2512 /// the memory instruction that we're computing this address for.
2513 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002514 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002515 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002516
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002517 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002518 /// part of the return value of this addressing mode matching stuff.
2519 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002520
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002521 /// The instructions inserted by other CodeGenPrepare optimizations.
2522 const SetOfInstrs &InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002523
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002524 /// A map from the instructions to their type before promotion.
2525 InstrToOrigTy &PromotedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002526
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002527 /// The ongoing transaction where every action should be registered.
2528 TypePromotionTransaction &TPT;
2529
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002530 /// This is set to true when we should not do profitability checks.
2531 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002532 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002533
Eric Christopherd75c00c2015-02-26 22:38:34 +00002534 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002535 const TargetLowering &TLI,
2536 const TargetRegisterInfo &TRI,
2537 Type *AT, unsigned AS,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002538 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002539 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002540 InstrToOrigTy &PromotedInsts,
2541 TypePromotionTransaction &TPT)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002542 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002543 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2544 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2545 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002546 IgnoreProfitability = false;
2547 }
Stephen Lin837bba12013-07-15 17:55:02 +00002548
Eugene Zelenko900b6332017-08-29 22:32:07 +00002549public:
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002550 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002551 /// give an access type of AccessTy. This returns a list of involved
2552 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002553 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002554 /// optimizations.
2555 /// \p PromotedInsts maps the instructions to their type before promotion.
2556 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002557 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002558 Instruction *MemoryInst,
2559 SmallVectorImpl<Instruction*> &AddrModeInsts,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002560 const TargetLowering &TLI,
2561 const TargetRegisterInfo &TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002562 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002563 InstrToOrigTy &PromotedInsts,
2564 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002565 ExtAddrMode Result;
2566
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002567 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
2568 AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002569 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002570 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002571 (void)Success; assert(Success && "Couldn't select *anything*?");
2572 return Result;
2573 }
Eugene Zelenko900b6332017-08-29 22:32:07 +00002574
Chandler Carruthc8925912013-01-05 02:09:22 +00002575private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002576 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2577 bool matchAddr(Value *V, unsigned Depth);
2578 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002579 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002580 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002581 ExtAddrMode &AMBefore,
2582 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002583 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2584 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002585 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002586};
2587
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002588/// \brief Keep track of simplification of Phi nodes.
2589/// Accept the set of all phi nodes and erase phi node from this set
2590/// if it is simplified.
2591class SimplificationTracker {
2592 DenseMap<Value *, Value *> Storage;
2593 const SimplifyQuery &SQ;
2594 SmallPtrSetImpl<PHINode *> &AllPhiNodes;
2595 SmallPtrSetImpl<SelectInst *> &AllSelectNodes;
2596
2597public:
2598 SimplificationTracker(const SimplifyQuery &sq,
2599 SmallPtrSetImpl<PHINode *> &APN,
2600 SmallPtrSetImpl<SelectInst *> &ASN)
2601 : SQ(sq), AllPhiNodes(APN), AllSelectNodes(ASN) {}
2602
2603 Value *Get(Value *V) {
2604 do {
2605 auto SV = Storage.find(V);
2606 if (SV == Storage.end())
2607 return V;
2608 V = SV->second;
2609 } while (true);
2610 }
2611
2612 Value *Simplify(Value *Val) {
2613 SmallVector<Value *, 32> WorkList;
2614 SmallPtrSet<Value *, 32> Visited;
2615 WorkList.push_back(Val);
2616 while (!WorkList.empty()) {
2617 auto P = WorkList.pop_back_val();
2618 if (!Visited.insert(P).second)
2619 continue;
2620 if (auto *PI = dyn_cast<Instruction>(P))
2621 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
2622 for (auto *U : PI->users())
2623 WorkList.push_back(cast<Value>(U));
2624 Put(PI, V);
2625 PI->replaceAllUsesWith(V);
2626 if (auto *PHI = dyn_cast<PHINode>(PI))
2627 AllPhiNodes.erase(PHI);
2628 if (auto *Select = dyn_cast<SelectInst>(PI))
2629 AllSelectNodes.erase(Select);
2630 PI->eraseFromParent();
2631 }
2632 }
2633 return Get(Val);
2634 }
2635
2636 void Put(Value *From, Value *To) {
2637 Storage.insert({ From, To });
2638 }
2639};
2640
John Brawn736bf002017-10-03 13:08:22 +00002641/// \brief A helper class for combining addressing modes.
2642class AddressingModeCombiner {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002643 typedef std::pair<Value *, BasicBlock *> ValueInBB;
2644 typedef DenseMap<ValueInBB, Value *> FoldAddrToValueMapping;
2645 typedef std::pair<PHINode *, PHINode *> PHIPair;
2646
John Brawn736bf002017-10-03 13:08:22 +00002647private:
2648 /// The addressing modes we've collected.
2649 SmallVector<ExtAddrMode, 16> AddrModes;
2650
2651 /// The field in which the AddrModes differ, when we have more than one.
2652 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
2653
2654 /// Are the AddrModes that we have all just equal to their original values?
2655 bool AllAddrModesTrivial = true;
2656
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002657 /// Common Type for all different fields in addressing modes.
2658 Type *CommonType;
2659
2660 /// SimplifyQuery for simplifyInstruction utility.
2661 const SimplifyQuery &SQ;
2662
2663 /// Original Address.
2664 ValueInBB Original;
2665
John Brawn736bf002017-10-03 13:08:22 +00002666public:
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002667 AddressingModeCombiner(const SimplifyQuery &_SQ, ValueInBB OriginalValue)
2668 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
2669
John Brawn736bf002017-10-03 13:08:22 +00002670 /// \brief Get the combined AddrMode
2671 const ExtAddrMode &getAddrMode() const {
2672 return AddrModes[0];
2673 }
2674
2675 /// \brief Add a new AddrMode if it's compatible with the AddrModes we already
2676 /// have.
2677 /// \return True iff we succeeded in doing so.
2678 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
2679 // Take note of if we have any non-trivial AddrModes, as we need to detect
2680 // when all AddrModes are trivial as then we would introduce a phi or select
2681 // which just duplicates what's already there.
2682 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
2683
2684 // If this is the first addrmode then everything is fine.
2685 if (AddrModes.empty()) {
2686 AddrModes.emplace_back(NewAddrMode);
2687 return true;
2688 }
2689
2690 // Figure out how different this is from the other address modes, which we
2691 // can do just by comparing against the first one given that we only care
2692 // about the cumulative difference.
2693 ExtAddrMode::FieldName ThisDifferentField =
2694 AddrModes[0].compare(NewAddrMode);
2695 if (DifferentField == ExtAddrMode::NoField)
2696 DifferentField = ThisDifferentField;
2697 else if (DifferentField != ThisDifferentField)
2698 DifferentField = ExtAddrMode::MultipleFields;
2699
Serguei Katkov17e57942018-01-23 12:07:49 +00002700 // If NewAddrMode differs in more than one dimension we cannot handle it.
2701 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
2702
2703 // If Scale Field is different then we reject.
2704 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
2705
Serguei Katkov4d1dd6b2018-01-09 04:37:06 +00002706 // We also must reject the case when base offset is different and
2707 // scale reg is not null, we cannot handle this case due to merge of
2708 // different offsets will be used as ScaleReg.
Serguei Katkov17e57942018-01-23 12:07:49 +00002709 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
2710 !NewAddrMode.ScaledReg);
John Brawn736bf002017-10-03 13:08:22 +00002711
Serguei Katkov17e57942018-01-23 12:07:49 +00002712 // We also must reject the case when GV is different and BaseReg installed
2713 // due to we want to use base reg as a merge of GV values.
2714 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
2715 !NewAddrMode.HasBaseReg);
2716
2717 // Even if NewAddMode is the same we still need to collect it due to
2718 // original value is different. And later we will need all original values
2719 // as anchors during finding the common Phi node.
2720 if (CanHandle)
2721 AddrModes.emplace_back(NewAddrMode);
2722 else
2723 AddrModes.clear();
2724
2725 return CanHandle;
John Brawn736bf002017-10-03 13:08:22 +00002726 }
2727
2728 /// \brief Combine the addressing modes we've collected into a single
2729 /// addressing mode.
2730 /// \return True iff we successfully combined them or we only had one so
2731 /// didn't need to combine them anyway.
2732 bool combineAddrModes() {
2733 // If we have no AddrModes then they can't be combined.
2734 if (AddrModes.size() == 0)
2735 return false;
2736
2737 // A single AddrMode can trivially be combined.
Serguei Katkov505359f2017-11-20 05:42:36 +00002738 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
John Brawn736bf002017-10-03 13:08:22 +00002739 return true;
2740
2741 // If the AddrModes we collected are all just equal to the value they are
2742 // derived from then combining them wouldn't do anything useful.
2743 if (AllAddrModesTrivial)
2744 return false;
2745
John Brawn70cdb5b2017-11-24 14:10:45 +00002746 if (!addrModeCombiningAllowed())
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002747 return false;
2748
2749 // Build a map between <original value, basic block where we saw it> to
2750 // value of base register.
Serguei Katkov50364592017-11-29 05:51:26 +00002751 // Bail out if there is no common type.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002752 FoldAddrToValueMapping Map;
Serguei Katkov50364592017-11-29 05:51:26 +00002753 if (!initializeMap(Map))
2754 return false;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002755
2756 Value *CommonValue = findCommon(Map);
2757 if (CommonValue)
John Brawn70cdb5b2017-11-24 14:10:45 +00002758 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002759 return CommonValue != nullptr;
2760 }
2761
2762private:
2763 /// \brief Initialize Map with anchor values. For address seen in some BB
2764 /// we set the value of different field saw in this address.
2765 /// If address is not an instruction than basic block is set to null.
2766 /// At the same time we find a common type for different field we will
2767 /// use to create new Phi/Select nodes. Keep it in CommonType field.
Serguei Katkov50364592017-11-29 05:51:26 +00002768 /// Return false if there is no common type found.
2769 bool initializeMap(FoldAddrToValueMapping &Map) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002770 // Keep track of keys where the value is null. We will need to replace it
2771 // with constant null when we know the common type.
2772 SmallVector<ValueInBB, 2> NullValue;
John Brawn70cdb5b2017-11-24 14:10:45 +00002773 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002774 for (auto &AM : AddrModes) {
2775 BasicBlock *BB = nullptr;
2776 if (Instruction *I = dyn_cast<Instruction>(AM.OriginalValue))
2777 BB = I->getParent();
2778
John Brawn70cdb5b2017-11-24 14:10:45 +00002779 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002780 if (DV) {
Serguei Katkov50364592017-11-29 05:51:26 +00002781 auto *Type = DV->getType();
2782 if (CommonType && CommonType != Type)
2783 return false;
2784 CommonType = Type;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002785 Map[{ AM.OriginalValue, BB }] = DV;
2786 } else {
2787 NullValue.push_back({ AM.OriginalValue, BB });
2788 }
2789 }
2790 assert(CommonType && "At least one non-null value must be!");
2791 for (auto VIBB : NullValue)
2792 Map[VIBB] = Constant::getNullValue(CommonType);
Serguei Katkov50364592017-11-29 05:51:26 +00002793 return true;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002794 }
2795
2796 /// \brief We have mapping between value A and basic block where value A
2797 /// seen to other value B where B was a field in addressing mode represented
2798 /// by A. Also we have an original value C representin an address in some
2799 /// basic block. Traversing from C through phi and selects we ended up with
2800 /// A's in a map. This utility function tries to find a value V which is a
2801 /// field in addressing mode C and traversing through phi nodes and selects
2802 /// we will end up in corresponded values B in a map.
2803 /// The utility will create a new Phi/Selects if needed.
2804 // The simple example looks as follows:
2805 // BB1:
2806 // p1 = b1 + 40
2807 // br cond BB2, BB3
2808 // BB2:
2809 // p2 = b2 + 40
2810 // br BB3
2811 // BB3:
2812 // p = phi [p1, BB1], [p2, BB2]
2813 // v = load p
2814 // Map is
2815 // <p1, BB1> -> b1
2816 // <p2, BB2> -> b2
2817 // Request is
2818 // <p, BB3> -> ?
2819 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3
2820 Value *findCommon(FoldAddrToValueMapping &Map) {
Eric Christopherd72f78e2018-01-09 23:25:38 +00002821 // Tracks newly created Phi nodes.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002822 SmallPtrSet<PHINode *, 32> NewPhiNodes;
Eric Christopherd72f78e2018-01-09 23:25:38 +00002823 // Tracks newly created Select nodes.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002824 SmallPtrSet<SelectInst *, 32> NewSelectNodes;
Eric Christopherd72f78e2018-01-09 23:25:38 +00002825 // Tracks the simplification of newly created phi nodes. The reason we use
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002826 // this mapping is because we will add new created Phi nodes in AddrToBase.
2827 // Simplification of Phi nodes is recursive, so some Phi node may
2828 // be simplified after we added it to AddrToBase.
2829 // Using this mapping we can find the current value in AddrToBase.
2830 SimplificationTracker ST(SQ, NewPhiNodes, NewSelectNodes);
2831
2832 // First step, DFS to create PHI nodes for all intermediate blocks.
2833 // Also fill traverse order for the second step.
2834 SmallVector<ValueInBB, 32> TraverseOrder;
2835 InsertPlaceholders(Map, TraverseOrder, NewPhiNodes, NewSelectNodes);
2836
2837 // Second Step, fill new nodes by merged values and simplify if possible.
2838 FillPlaceholders(Map, TraverseOrder, ST);
2839
2840 if (!AddrSinkNewSelects && NewSelectNodes.size() > 0) {
2841 DestroyNodes(NewPhiNodes);
2842 DestroyNodes(NewSelectNodes);
2843 return nullptr;
2844 }
2845
2846 // Now we'd like to match New Phi nodes to existed ones.
2847 unsigned PhiNotMatchedCount = 0;
2848 if (!MatchPhiSet(NewPhiNodes, ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
2849 DestroyNodes(NewPhiNodes);
2850 DestroyNodes(NewSelectNodes);
2851 return nullptr;
2852 }
2853
2854 auto *Result = ST.Get(Map.find(Original)->second);
2855 if (Result) {
2856 NumMemoryInstsPhiCreated += NewPhiNodes.size() + PhiNotMatchedCount;
2857 NumMemoryInstsSelectCreated += NewSelectNodes.size();
2858 }
2859 return Result;
2860 }
2861
2862 /// \brief Destroy nodes from a set.
2863 template <typename T> void DestroyNodes(SmallPtrSetImpl<T *> &Instructions) {
2864 // For safe erasing, replace the Phi with dummy value first.
2865 auto Dummy = UndefValue::get(CommonType);
2866 for (auto I : Instructions) {
2867 I->replaceAllUsesWith(Dummy);
2868 I->eraseFromParent();
2869 }
2870 }
2871
2872 /// \brief Try to match PHI node to Candidate.
2873 /// Matcher tracks the matched Phi nodes.
2874 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
2875 DenseSet<PHIPair> &Matcher,
2876 SmallPtrSetImpl<PHINode *> &PhiNodesToMatch) {
2877 SmallVector<PHIPair, 8> WorkList;
2878 Matcher.insert({ PHI, Candidate });
2879 WorkList.push_back({ PHI, Candidate });
2880 SmallSet<PHIPair, 8> Visited;
2881 while (!WorkList.empty()) {
2882 auto Item = WorkList.pop_back_val();
2883 if (!Visited.insert(Item).second)
2884 continue;
2885 // We iterate over all incoming values to Phi to compare them.
2886 // If values are different and both of them Phi and the first one is a
2887 // Phi we added (subject to match) and both of them is in the same basic
2888 // block then we can match our pair if values match. So we state that
2889 // these values match and add it to work list to verify that.
2890 for (auto B : Item.first->blocks()) {
2891 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
2892 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
2893 if (FirstValue == SecondValue)
2894 continue;
2895
2896 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
2897 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
2898
2899 // One of them is not Phi or
2900 // The first one is not Phi node from the set we'd like to match or
2901 // Phi nodes from different basic blocks then
2902 // we will not be able to match.
2903 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
2904 FirstPhi->getParent() != SecondPhi->getParent())
2905 return false;
2906
2907 // If we already matched them then continue.
2908 if (Matcher.count({ FirstPhi, SecondPhi }))
2909 continue;
2910 // So the values are different and does not match. So we need them to
2911 // match.
2912 Matcher.insert({ FirstPhi, SecondPhi });
2913 // But me must check it.
2914 WorkList.push_back({ FirstPhi, SecondPhi });
2915 }
2916 }
2917 return true;
2918 }
2919
2920 /// \brief For the given set of PHI nodes try to find their equivalents.
2921 /// Returns false if this matching fails and creation of new Phi is disabled.
2922 bool MatchPhiSet(SmallPtrSetImpl<PHINode *> &PhiNodesToMatch,
2923 SimplificationTracker &ST, bool AllowNewPhiNodes,
2924 unsigned &PhiNotMatchedCount) {
2925 DenseSet<PHIPair> Matched;
2926 SmallPtrSet<PHINode *, 8> WillNotMatch;
2927 while (PhiNodesToMatch.size()) {
2928 PHINode *PHI = *PhiNodesToMatch.begin();
2929
2930 // Add us, if no Phi nodes in the basic block we do not match.
2931 WillNotMatch.clear();
2932 WillNotMatch.insert(PHI);
2933
2934 // Traverse all Phis until we found equivalent or fail to do that.
2935 bool IsMatched = false;
2936 for (auto &P : PHI->getParent()->phis()) {
2937 if (&P == PHI)
2938 continue;
2939 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
2940 break;
2941 // If it does not match, collect all Phi nodes from matcher.
2942 // if we end up with no match, them all these Phi nodes will not match
2943 // later.
2944 for (auto M : Matched)
2945 WillNotMatch.insert(M.first);
2946 Matched.clear();
2947 }
2948 if (IsMatched) {
Serguei Katkova20e05b2018-03-12 03:50:07 +00002949 // If we matched phi node to different but identical phis then
2950 // make a simplification here.
2951 DenseMap<PHINode *, PHINode *> MatchedPHINodeMapping;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002952 for (auto MV : Matched) {
Serguei Katkova20e05b2018-03-12 03:50:07 +00002953 auto AlreadyMatched = MatchedPHINodeMapping.find(MV.first);
2954 if (AlreadyMatched != MatchedPHINodeMapping.end()) {
2955 MV.second->replaceAllUsesWith(AlreadyMatched->second);
2956 ST.Put(MV.second, AlreadyMatched->second);
2957 MV.second->eraseFromParent();
2958 } else
2959 MatchedPHINodeMapping.insert({ MV.first, MV.second });
2960 }
2961 // Replace all matched values and erase them.
2962 for (auto MV : MatchedPHINodeMapping) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002963 MV.first->replaceAllUsesWith(MV.second);
2964 PhiNodesToMatch.erase(MV.first);
2965 ST.Put(MV.first, MV.second);
2966 MV.first->eraseFromParent();
2967 }
2968 Matched.clear();
2969 continue;
2970 }
2971 // If we are not allowed to create new nodes then bail out.
2972 if (!AllowNewPhiNodes)
2973 return false;
2974 // Just remove all seen values in matcher. They will not match anything.
2975 PhiNotMatchedCount += WillNotMatch.size();
2976 for (auto *P : WillNotMatch)
2977 PhiNodesToMatch.erase(P);
2978 }
2979 return true;
2980 }
2981 /// \brief Fill the placeholder with values from predecessors and simplify it.
2982 void FillPlaceholders(FoldAddrToValueMapping &Map,
2983 SmallVectorImpl<ValueInBB> &TraverseOrder,
2984 SimplificationTracker &ST) {
2985 while (!TraverseOrder.empty()) {
2986 auto Current = TraverseOrder.pop_back_val();
2987 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
2988 Value *CurrentValue = Current.first;
2989 BasicBlock *CurrentBlock = Current.second;
2990 Value *V = Map[Current];
2991
2992 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
2993 // CurrentValue also must be Select.
2994 auto *CurrentSelect = cast<SelectInst>(CurrentValue);
2995 auto *TrueValue = CurrentSelect->getTrueValue();
2996 ValueInBB TrueItem = { TrueValue, isa<Instruction>(TrueValue)
2997 ? CurrentBlock
2998 : nullptr };
2999 assert(Map.find(TrueItem) != Map.end() && "No True Value!");
Serguei Katkovb0b67a82017-12-18 04:25:07 +00003000 Select->setTrueValue(ST.Get(Map[TrueItem]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003001 auto *FalseValue = CurrentSelect->getFalseValue();
3002 ValueInBB FalseItem = { FalseValue, isa<Instruction>(FalseValue)
3003 ? CurrentBlock
3004 : nullptr };
3005 assert(Map.find(FalseItem) != Map.end() && "No False Value!");
Serguei Katkovb0b67a82017-12-18 04:25:07 +00003006 Select->setFalseValue(ST.Get(Map[FalseItem]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003007 } else {
3008 // Must be a Phi node then.
3009 PHINode *PHI = cast<PHINode>(V);
3010 // Fill the Phi node with values from predecessors.
3011 bool IsDefinedInThisBB =
3012 cast<Instruction>(CurrentValue)->getParent() == CurrentBlock;
3013 auto *CurrentPhi = dyn_cast<PHINode>(CurrentValue);
3014 for (auto B : predecessors(CurrentBlock)) {
3015 Value *PV = IsDefinedInThisBB
3016 ? CurrentPhi->getIncomingValueForBlock(B)
3017 : CurrentValue;
3018 ValueInBB item = { PV, isa<Instruction>(PV) ? B : nullptr };
3019 assert(Map.find(item) != Map.end() && "No predecessor Value!");
3020 PHI->addIncoming(ST.Get(Map[item]), B);
3021 }
3022 }
3023 // Simplify if possible.
3024 Map[Current] = ST.Simplify(V);
3025 }
3026 }
3027
3028 /// Starting from value recursively iterates over predecessors up to known
3029 /// ending values represented in a map. For each traversed block inserts
3030 /// a placeholder Phi or Select.
3031 /// Reports all new created Phi/Select nodes by adding them to set.
3032 /// Also reports and order in what basic blocks have been traversed.
3033 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3034 SmallVectorImpl<ValueInBB> &TraverseOrder,
3035 SmallPtrSetImpl<PHINode *> &NewPhiNodes,
3036 SmallPtrSetImpl<SelectInst *> &NewSelectNodes) {
3037 SmallVector<ValueInBB, 32> Worklist;
3038 assert((isa<PHINode>(Original.first) || isa<SelectInst>(Original.first)) &&
3039 "Address must be a Phi or Select node");
3040 auto *Dummy = UndefValue::get(CommonType);
3041 Worklist.push_back(Original);
3042 while (!Worklist.empty()) {
3043 auto Current = Worklist.pop_back_val();
3044 // If value is not an instruction it is something global, constant,
3045 // parameter and we can say that this value is observable in any block.
3046 // Set block to null to denote it.
3047 // Also please take into account that it is how we build anchors.
3048 if (!isa<Instruction>(Current.first))
3049 Current.second = nullptr;
3050 // if it is already visited or it is an ending value then skip it.
3051 if (Map.find(Current) != Map.end())
3052 continue;
3053 TraverseOrder.push_back(Current);
3054
3055 Value *CurrentValue = Current.first;
3056 BasicBlock *CurrentBlock = Current.second;
3057 // CurrentValue must be a Phi node or select. All others must be covered
3058 // by anchors.
3059 Instruction *CurrentI = cast<Instruction>(CurrentValue);
3060 bool IsDefinedInThisBB = CurrentI->getParent() == CurrentBlock;
3061
3062 unsigned PredCount =
3063 std::distance(pred_begin(CurrentBlock), pred_end(CurrentBlock));
3064 // if Current Value is not defined in this basic block we are interested
3065 // in values in predecessors.
3066 if (!IsDefinedInThisBB) {
3067 assert(PredCount && "Unreachable block?!");
3068 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3069 &CurrentBlock->front());
3070 Map[Current] = PHI;
3071 NewPhiNodes.insert(PHI);
3072 // Add all predecessors in work list.
3073 for (auto B : predecessors(CurrentBlock))
3074 Worklist.push_back({ CurrentValue, B });
3075 continue;
3076 }
3077 // Value is defined in this basic block.
3078 if (SelectInst *OrigSelect = dyn_cast<SelectInst>(CurrentI)) {
3079 // Is it OK to get metadata from OrigSelect?!
3080 // Create a Select placeholder with dummy value.
3081 SelectInst *Select =
3082 SelectInst::Create(OrigSelect->getCondition(), Dummy, Dummy,
3083 OrigSelect->getName(), OrigSelect, OrigSelect);
3084 Map[Current] = Select;
3085 NewSelectNodes.insert(Select);
3086 // We are interested in True and False value in this basic block.
3087 Worklist.push_back({ OrigSelect->getTrueValue(), CurrentBlock });
3088 Worklist.push_back({ OrigSelect->getFalseValue(), CurrentBlock });
3089 } else {
3090 // It must be a Phi node then.
3091 auto *CurrentPhi = cast<PHINode>(CurrentI);
3092 // Create new Phi node for merge of bases.
3093 assert(PredCount && "Unreachable block?!");
3094 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3095 &CurrentBlock->front());
3096 Map[Current] = PHI;
3097 NewPhiNodes.insert(PHI);
3098
3099 // Add all predecessors in work list.
3100 for (auto B : predecessors(CurrentBlock))
3101 Worklist.push_back({ CurrentPhi->getIncomingValueForBlock(B), B });
3102 }
3103 }
John Brawn736bf002017-10-03 13:08:22 +00003104 }
John Brawn70cdb5b2017-11-24 14:10:45 +00003105
3106 bool addrModeCombiningAllowed() {
3107 if (DisableComplexAddrModes)
3108 return false;
3109 switch (DifferentField) {
3110 default:
3111 return false;
3112 case ExtAddrMode::BaseRegField:
3113 return AddrSinkCombineBaseReg;
3114 case ExtAddrMode::BaseGVField:
3115 return AddrSinkCombineBaseGV;
3116 case ExtAddrMode::BaseOffsField:
3117 return AddrSinkCombineBaseOffs;
3118 case ExtAddrMode::ScaledRegField:
3119 return AddrSinkCombineScaledReg;
3120 }
3121 }
John Brawn736bf002017-10-03 13:08:22 +00003122};
Eugene Zelenko900b6332017-08-29 22:32:07 +00003123} // end anonymous namespace
3124
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003125/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003126/// Return true and update AddrMode if this addr mode is legal for the target,
3127/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003128bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003129 unsigned Depth) {
3130 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3131 // mode. Just process that directly.
3132 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003133 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003134
Chandler Carruthc8925912013-01-05 02:09:22 +00003135 // If the scale is 0, it takes nothing to add this.
3136 if (Scale == 0)
3137 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003138
Chandler Carruthc8925912013-01-05 02:09:22 +00003139 // If we already have a scale of this value, we can add to it, otherwise, we
3140 // need an available scale field.
3141 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3142 return false;
3143
3144 ExtAddrMode TestAddrMode = AddrMode;
3145
3146 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3147 // [A+B + A*7] -> [B+A*8].
3148 TestAddrMode.Scale += Scale;
3149 TestAddrMode.ScaledReg = ScaleReg;
3150
3151 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003152 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003153 return false;
3154
3155 // It was legal, so commit it.
3156 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003157
Chandler Carruthc8925912013-01-05 02:09:22 +00003158 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3159 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3160 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003161 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003162 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3163 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3164 TestAddrMode.ScaledReg = AddLHS;
3165 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003166
Chandler Carruthc8925912013-01-05 02:09:22 +00003167 // If this addressing mode is legal, commit it and remember that we folded
3168 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003169 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003170 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3171 AddrMode = TestAddrMode;
3172 return true;
3173 }
3174 }
3175
3176 // Otherwise, not (x+c)*scale, just return what we have.
3177 return true;
3178}
3179
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003180/// This is a little filter, which returns true if an addressing computation
3181/// involving I might be folded into a load/store accessing it.
3182/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003183/// the set of instructions that MatchOperationAddr can.
3184static bool MightBeFoldableInst(Instruction *I) {
3185 switch (I->getOpcode()) {
3186 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003187 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003188 // Don't touch identity bitcasts.
3189 if (I->getType() == I->getOperand(0)->getType())
3190 return false;
3191 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3192 case Instruction::PtrToInt:
3193 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3194 return true;
3195 case Instruction::IntToPtr:
3196 // We know the input is intptr_t, so this is foldable.
3197 return true;
3198 case Instruction::Add:
3199 return true;
3200 case Instruction::Mul:
3201 case Instruction::Shl:
3202 // Can only handle X*C and X << C.
3203 return isa<ConstantInt>(I->getOperand(1));
3204 case Instruction::GetElementPtr:
3205 return true;
3206 default:
3207 return false;
3208 }
3209}
3210
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003211/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3212/// \note \p Val is assumed to be the product of some type promotion.
3213/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3214/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003215static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3216 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003217 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3218 if (!PromotedInst)
3219 return false;
3220 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3221 // If the ISDOpcode is undefined, it was undefined before the promotion.
3222 if (!ISDOpcode)
3223 return true;
3224 // Otherwise, check if the promoted instruction is legal or not.
3225 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003226 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003227}
3228
Eugene Zelenko900b6332017-08-29 22:32:07 +00003229namespace {
3230
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003231/// \brief Hepler class to perform type promotion.
3232class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003233 /// \brief Utility function to check whether or not a sign or zero extension
3234 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3235 /// either using the operands of \p Inst or promoting \p Inst.
3236 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003237 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003238 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003239 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003240 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003241 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003242 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003243 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003244 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3245 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003246
3247 /// \brief Utility function to determine if \p OpIdx should be promoted when
3248 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003249 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003250 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003251 }
3252
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003253 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003254 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003255 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003256 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003257 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003258 /// Newly added extensions are inserted in \p Exts.
3259 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003260 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003261 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003262 static Value *promoteOperandForTruncAndAnyExt(
3263 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003264 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003265 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003266 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003267
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003268 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003269 /// operand is promotable and is not a supported trunc or sext.
3270 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003271 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003272 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003273 /// Newly added extensions are inserted in \p Exts.
3274 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003275 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003276 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003277 static Value *promoteOperandForOther(Instruction *Ext,
3278 TypePromotionTransaction &TPT,
3279 InstrToOrigTy &PromotedInsts,
3280 unsigned &CreatedInstsCost,
3281 SmallVectorImpl<Instruction *> *Exts,
3282 SmallVectorImpl<Instruction *> *Truncs,
3283 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003284
3285 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003286 static Value *signExtendOperandForOther(
3287 Instruction *Ext, TypePromotionTransaction &TPT,
3288 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3289 SmallVectorImpl<Instruction *> *Exts,
3290 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3291 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3292 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003293 }
3294
3295 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003296 static Value *zeroExtendOperandForOther(
3297 Instruction *Ext, TypePromotionTransaction &TPT,
3298 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3299 SmallVectorImpl<Instruction *> *Exts,
3300 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3301 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3302 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003303 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003304
3305public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003306 /// Type for the utility function that promotes the operand of Ext.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003307 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3308 InstrToOrigTy &PromotedInsts,
3309 unsigned &CreatedInstsCost,
3310 SmallVectorImpl<Instruction *> *Exts,
3311 SmallVectorImpl<Instruction *> *Truncs,
3312 const TargetLowering &TLI);
3313
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003314 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3315 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003316 /// \return NULL if no promotable action is possible with the current
3317 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003318 /// \p InsertedInsts keeps track of all the instructions inserted by the
3319 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003320 /// because we do not want to promote these instructions as CodeGenPrepare
3321 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3322 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003323 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003324 const TargetLowering &TLI,
3325 const InstrToOrigTy &PromotedInsts);
3326};
3327
Eugene Zelenko900b6332017-08-29 22:32:07 +00003328} // end anonymous namespace
3329
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003330bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003331 Type *ConsideredExtType,
3332 const InstrToOrigTy &PromotedInsts,
3333 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003334 // The promotion helper does not know how to deal with vector types yet.
3335 // To be able to fix that, we would need to fix the places where we
3336 // statically extend, e.g., constants and such.
3337 if (Inst->getType()->isVectorTy())
3338 return false;
3339
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003340 // We can always get through zext.
3341 if (isa<ZExtInst>(Inst))
3342 return true;
3343
3344 // sext(sext) is ok too.
3345 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003346 return true;
3347
3348 // We can get through binary operator, if it is legal. In other words, the
3349 // binary operator must have a nuw or nsw flag.
3350 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3351 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003352 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3353 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003354 return true;
3355
3356 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003357 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003358 if (!isa<TruncInst>(Inst))
3359 return false;
3360
3361 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003362 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003363 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003364 if (!OpndVal->getType()->isIntegerTy() ||
3365 OpndVal->getType()->getIntegerBitWidth() >
3366 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003367 return false;
3368
3369 // If the operand of the truncate is not an instruction, we will not have
3370 // any information on the dropped bits.
3371 // (Actually we could for constant but it is not worth the extra logic).
3372 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3373 if (!Opnd)
3374 return false;
3375
3376 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003377 // I.e., check that trunc just drops extended bits of the same kind of
3378 // the extension.
3379 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003380 const Type *OpndType;
3381 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003382 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3383 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003384 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3385 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003386 else
3387 return false;
3388
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003389 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003390 return Inst->getType()->getIntegerBitWidth() >=
3391 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003392}
3393
3394TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003395 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003396 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003397 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3398 "Unexpected instruction type");
3399 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3400 Type *ExtTy = Ext->getType();
3401 bool IsSExt = isa<SExtInst>(Ext);
3402 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003403 // get through.
3404 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003405 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003406 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003407
3408 // Do not promote if the operand has been added by codegenprepare.
3409 // Otherwise, it means we are undoing an optimization that is likely to be
3410 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003411 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003412 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003413
3414 // SExt or Trunc instructions.
3415 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003416 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3417 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003418 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003419
3420 // Regular instruction.
3421 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003422 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003423 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003424 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003425}
3426
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003427Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003428 Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003429 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003430 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003431 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003432 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3433 // get through it and this method should not be called.
3434 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003435 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003436 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003437 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003438 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003439 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003440 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003441 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003442 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3443 TPT.replaceAllUsesWith(SExt, ZExt);
3444 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003445 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003446 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003447 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3448 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003449 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3450 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003451 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003452
3453 // Remove dead code.
3454 if (SExtOpnd->use_empty())
3455 TPT.eraseInstruction(SExtOpnd);
3456
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003457 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003458 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003459 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003460 if (ExtInst) {
3461 if (Exts)
3462 Exts->push_back(ExtInst);
3463 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3464 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003465 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003466 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003467
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003468 // At this point we have: ext ty opnd to ty.
3469 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3470 Value *NextVal = ExtInst->getOperand(0);
3471 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003472 return NextVal;
3473}
3474
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003475Value *TypePromotionHelper::promoteOperandForOther(
3476 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003477 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003478 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003479 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3480 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003481 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003482 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003483 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003484 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003485 if (!ExtOpnd->hasOneUse()) {
3486 // ExtOpnd will be promoted.
3487 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003488 // promoted version.
3489 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003490 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003491 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
Quentin Colombetac55b152014-09-16 22:36:07 +00003492 // Insert it just after the definition.
Sanjay Patel674d2c22017-08-29 14:07:48 +00003493 ITrunc->moveAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003494 if (Truncs)
3495 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003496 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003497
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003498 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003499 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003500 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003501 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003502 }
3503
3504 // Get through the Instruction:
3505 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003506 // 2. Replace the uses of Ext by Inst.
3507 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003508
3509 // Remember the original type of the instruction before promotion.
3510 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003511 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3512 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003513 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003514 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003515 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003516 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003517 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003518 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003519
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003520 DEBUG(dbgs() << "Propagate Ext to operands\n");
3521 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003522 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003523 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3524 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3525 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003526 DEBUG(dbgs() << "No need to propagate\n");
3527 continue;
3528 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003529 // Check if we can statically extend the operand.
3530 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003531 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003532 DEBUG(dbgs() << "Statically extend\n");
3533 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3534 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3535 : Cst->getValue().zext(BitWidth);
3536 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003537 continue;
3538 }
3539 // UndefValue are typed, so we have to statically sign extend them.
3540 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003541 DEBUG(dbgs() << "Statically extend\n");
3542 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003543 continue;
3544 }
3545
3546 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003547 // Check if Ext was reused to extend an operand.
3548 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003549 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003550 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003551 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3552 : TPT.createZExt(Ext, Opnd, Ext->getType());
3553 if (!isa<Instruction>(ValForExtOpnd)) {
3554 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3555 continue;
3556 }
3557 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003558 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003559 if (Exts)
3560 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003561 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003562
3563 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003564 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3565 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003566 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003567 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003568 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003569 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003570 if (ExtForOpnd == Ext) {
3571 DEBUG(dbgs() << "Extension is useless now\n");
3572 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003573 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003574 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003575}
3576
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003577/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003578/// \p NewCost gives the cost of extension instructions created by the
3579/// promotion.
3580/// \p OldCost gives the cost of extension instructions before the promotion
3581/// plus the number of instructions that have been
3582/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003583/// \p PromotedOperand is the value that has been promoted.
3584/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003585bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003586 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3587 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3588 // The cost of the new extensions is greater than the cost of the
3589 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003590 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003591 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003592 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003593 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003594 return true;
3595 // The promotion is neutral but it may help folding the sign extension in
3596 // loads for instance.
3597 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003598 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003599}
3600
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003601/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003602/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003603/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003604/// If \p MovedAway is not NULL, it contains the information of whether or
3605/// not AddrInst has to be folded into the addressing mode on success.
3606/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3607/// because it has been moved away.
3608/// Thus AddrInst must not be added in the matched instructions.
3609/// This state can happen when AddrInst is a sext, since it may be moved away.
3610/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3611/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003612bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003613 unsigned Depth,
3614 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003615 // Avoid exponential behavior on extremely deep expression trees.
3616 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003617
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003618 // By default, all matched instructions stay in place.
3619 if (MovedAway)
3620 *MovedAway = false;
3621
Chandler Carruthc8925912013-01-05 02:09:22 +00003622 switch (Opcode) {
3623 case Instruction::PtrToInt:
3624 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003625 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003626 case Instruction::IntToPtr: {
3627 auto AS = AddrInst->getType()->getPointerAddressSpace();
3628 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003629 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003630 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003631 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003632 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003633 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003634 case Instruction::BitCast:
3635 // BitCast is always a noop, and we can handle it as long as it is
3636 // int->int or pointer->pointer (we don't want int<->fp or something).
3637 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3638 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3639 // Don't touch identity bitcasts. These were probably put here by LSR,
3640 // and we don't want to mess around with them. Assume it knows what it
3641 // is doing.
3642 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003643 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003644 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003645 case Instruction::AddrSpaceCast: {
3646 unsigned SrcAS
3647 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3648 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3649 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003650 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003651 return false;
3652 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003653 case Instruction::Add: {
3654 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3655 ExtAddrMode BackupAddrMode = AddrMode;
3656 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003657 // Start a transaction at this point.
3658 // The LHS may match but not the RHS.
3659 // Therefore, we need a higher level restoration point to undo partially
3660 // matched operation.
3661 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3662 TPT.getRestorationPoint();
3663
Sanjay Patelfc580a62015-09-21 23:03:16 +00003664 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3665 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003666 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003667
Chandler Carruthc8925912013-01-05 02:09:22 +00003668 // Restore the old addr mode info.
3669 AddrMode = BackupAddrMode;
3670 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003671 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003672
Chandler Carruthc8925912013-01-05 02:09:22 +00003673 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003674 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3675 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003676 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003677
Chandler Carruthc8925912013-01-05 02:09:22 +00003678 // Otherwise we definitely can't merge the ADD in.
3679 AddrMode = BackupAddrMode;
3680 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003681 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003682 break;
3683 }
3684 //case Instruction::Or:
3685 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3686 //break;
3687 case Instruction::Mul:
3688 case Instruction::Shl: {
3689 // Can only handle X*C and X << C.
3690 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Philip Reames9c3cbee2017-10-30 23:59:51 +00003691 if (!RHS || RHS->getBitWidth() > 64)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003692 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003693 int64_t Scale = RHS->getSExtValue();
3694 if (Opcode == Instruction::Shl)
3695 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003696
Sanjay Patelfc580a62015-09-21 23:03:16 +00003697 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003698 }
3699 case Instruction::GetElementPtr: {
3700 // Scan the GEP. We check it if it contains constant offsets and at most
3701 // one variable offset.
3702 int VariableOperand = -1;
3703 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003704
Chandler Carruthc8925912013-01-05 02:09:22 +00003705 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003706 gep_type_iterator GTI = gep_type_begin(AddrInst);
3707 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003708 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003709 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003710 unsigned Idx =
3711 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3712 ConstantOffset += SL->getElementOffset(Idx);
3713 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003714 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003715 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
Haicheng Wu0be88252017-12-19 20:53:32 +00003716 ConstantOffset += CI->getSExtValue() * TypeSize;
Chandler Carruthc8925912013-01-05 02:09:22 +00003717 } else if (TypeSize) { // Scales of zero don't do anything.
3718 // We only allow one variable index at the moment.
3719 if (VariableOperand != -1)
3720 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003721
Chandler Carruthc8925912013-01-05 02:09:22 +00003722 // Remember the variable index.
3723 VariableOperand = i;
3724 VariableScale = TypeSize;
3725 }
3726 }
3727 }
Stephen Lin837bba12013-07-15 17:55:02 +00003728
Chandler Carruthc8925912013-01-05 02:09:22 +00003729 // A common case is for the GEP to only do a constant offset. In this case,
3730 // just add it to the disp field and check validity.
3731 if (VariableOperand == -1) {
3732 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003733 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003734 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003735 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003736 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003737 return true;
3738 }
3739 AddrMode.BaseOffs -= ConstantOffset;
3740 return false;
3741 }
3742
3743 // Save the valid addressing mode in case we can't match.
3744 ExtAddrMode BackupAddrMode = AddrMode;
3745 unsigned OldSize = AddrModeInsts.size();
3746
3747 // See if the scale and offset amount is valid for this target.
3748 AddrMode.BaseOffs += ConstantOffset;
3749
3750 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003751 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003752 // If it couldn't be matched, just stuff the value in a register.
3753 if (AddrMode.HasBaseReg) {
3754 AddrMode = BackupAddrMode;
3755 AddrModeInsts.resize(OldSize);
3756 return false;
3757 }
3758 AddrMode.HasBaseReg = true;
3759 AddrMode.BaseReg = AddrInst->getOperand(0);
3760 }
3761
3762 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003763 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003764 Depth)) {
3765 // If it couldn't be matched, try stuffing the base into a register
3766 // instead of matching it, and retrying the match of the scale.
3767 AddrMode = BackupAddrMode;
3768 AddrModeInsts.resize(OldSize);
3769 if (AddrMode.HasBaseReg)
3770 return false;
3771 AddrMode.HasBaseReg = true;
3772 AddrMode.BaseReg = AddrInst->getOperand(0);
3773 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003774 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003775 VariableScale, Depth)) {
3776 // If even that didn't work, bail.
3777 AddrMode = BackupAddrMode;
3778 AddrModeInsts.resize(OldSize);
3779 return false;
3780 }
3781 }
3782
3783 return true;
3784 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003785 case Instruction::SExt:
3786 case Instruction::ZExt: {
3787 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3788 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003789 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003790
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003791 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003792 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003793 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003794 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003795 if (!TPH)
3796 return false;
3797
3798 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3799 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003800 unsigned CreatedInstsCost = 0;
3801 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003802 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003803 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003804 // SExt has been moved away.
3805 // Thus either it will be rematched later in the recursive calls or it is
3806 // gone. Anyway, we must not fold it into the addressing mode at this point.
3807 // E.g.,
3808 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003809 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003810 // addr = gep base, idx
3811 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003812 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003813 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3814 // addr = gep base, op <- match
3815 if (MovedAway)
3816 *MovedAway = true;
3817
3818 assert(PromotedOperand &&
3819 "TypePromotionHelper should have filtered out those cases");
3820
3821 ExtAddrMode BackupAddrMode = AddrMode;
3822 unsigned OldSize = AddrModeInsts.size();
3823
Sanjay Patelfc580a62015-09-21 23:03:16 +00003824 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003825 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003826 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003827 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003828 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003829 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003830 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003831 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003832 AddrMode = BackupAddrMode;
3833 AddrModeInsts.resize(OldSize);
3834 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3835 TPT.rollback(LastKnownGood);
3836 return false;
3837 }
3838 return true;
3839 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003840 }
3841 return false;
3842}
3843
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003844/// If we can, try to add the value of 'Addr' into the current addressing mode.
3845/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3846/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3847/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003848///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003849bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003850 // Start a transaction at this point that we will rollback if the matching
3851 // fails.
3852 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3853 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003854 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3855 // Fold in immediates if legal for the target.
3856 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003857 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003858 return true;
3859 AddrMode.BaseOffs -= CI->getSExtValue();
3860 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3861 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003862 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003863 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003864 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003865 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003866 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003867 }
3868 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3869 ExtAddrMode BackupAddrMode = AddrMode;
3870 unsigned OldSize = AddrModeInsts.size();
3871
3872 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003873 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003874 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003875 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003876 // to check here.
3877 if (MovedAway)
3878 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003879 // Okay, it's possible to fold this. Check to see if it is actually
3880 // *profitable* to do so. We use a simple cost model to avoid increasing
3881 // register pressure too much.
3882 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003883 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003884 AddrModeInsts.push_back(I);
3885 return true;
3886 }
Stephen Lin837bba12013-07-15 17:55:02 +00003887
Chandler Carruthc8925912013-01-05 02:09:22 +00003888 // It isn't profitable to do this, roll back.
3889 //cerr << "NOT FOLDING: " << *I;
3890 AddrMode = BackupAddrMode;
3891 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003892 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003893 }
3894 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003895 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003896 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003897 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003898 } else if (isa<ConstantPointerNull>(Addr)) {
3899 // Null pointer gets folded without affecting the addressing mode.
3900 return true;
3901 }
3902
3903 // Worse case, the target should support [reg] addressing modes. :)
3904 if (!AddrMode.HasBaseReg) {
3905 AddrMode.HasBaseReg = true;
3906 AddrMode.BaseReg = Addr;
3907 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003908 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003909 return true;
3910 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003911 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003912 }
3913
3914 // If the base register is already taken, see if we can do [r+r].
3915 if (AddrMode.Scale == 0) {
3916 AddrMode.Scale = 1;
3917 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003918 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003919 return true;
3920 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003921 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003922 }
3923 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003924 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003925 return false;
3926}
3927
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003928/// Check to see if all uses of OpVal by the specified inline asm call are due
3929/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003930static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003931 const TargetLowering &TLI,
3932 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00003933 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003934 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003935 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003936 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003937
Chandler Carruthc8925912013-01-05 02:09:22 +00003938 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3939 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003940
Chandler Carruthc8925912013-01-05 02:09:22 +00003941 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003942 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003943
3944 // If this asm operand is our Value*, and if it isn't an indirect memory
3945 // operand, we can't fold it!
3946 if (OpInfo.CallOperandVal == OpVal &&
3947 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3948 !OpInfo.isIndirect))
3949 return false;
3950 }
3951
3952 return true;
3953}
3954
Benjamin Kramerfc638c12017-07-24 16:18:09 +00003955// Max number of memory uses to look at before aborting the search to conserve
3956// compile time.
3957static constexpr int MaxMemoryUsesToScan = 20;
3958
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003959/// Recursively walk all the uses of I until we find a memory use.
3960/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003961/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003962static bool FindAllMemoryUses(
3963 Instruction *I,
3964 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Benjamin Kramerfc638c12017-07-24 16:18:09 +00003965 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
3966 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003967 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003968 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003969 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003970
Chandler Carruthc8925912013-01-05 02:09:22 +00003971 // If this is an obviously unfoldable instruction, bail out.
3972 if (!MightBeFoldableInst(I))
3973 return true;
3974
Philip Reamesac115ed2016-03-09 23:13:12 +00003975 const bool OptSize = I->getFunction()->optForSize();
3976
Chandler Carruthc8925912013-01-05 02:09:22 +00003977 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003978 for (Use &U : I->uses()) {
Benjamin Kramerfc638c12017-07-24 16:18:09 +00003979 // Conservatively return true if we're seeing a large number or a deep chain
3980 // of users. This avoids excessive compilation times in pathological cases.
3981 if (SeenInsts++ >= MaxMemoryUsesToScan)
3982 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003983
Benjamin Kramerfc638c12017-07-24 16:18:09 +00003984 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthcdf47882014-03-09 03:16:01 +00003985 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3986 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003987 continue;
3988 }
Stephen Lin837bba12013-07-15 17:55:02 +00003989
Chandler Carruthcdf47882014-03-09 03:16:01 +00003990 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3991 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00003992 if (opNo != StoreInst::getPointerOperandIndex())
3993 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00003994 MemoryUses.push_back(std::make_pair(SI, opNo));
3995 continue;
3996 }
Stephen Lin837bba12013-07-15 17:55:02 +00003997
Matt Arsenault02d915b2017-03-15 22:35:20 +00003998 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
3999 unsigned opNo = U.getOperandNo();
4000 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4001 return true; // Storing addr, not into addr.
4002 MemoryUses.push_back(std::make_pair(RMW, opNo));
4003 continue;
4004 }
4005
4006 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4007 unsigned opNo = U.getOperandNo();
4008 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4009 return true; // Storing addr, not into addr.
4010 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4011 continue;
4012 }
4013
Chandler Carruthcdf47882014-03-09 03:16:01 +00004014 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004015 // If this is a cold call, we can sink the addressing calculation into
4016 // the cold path. See optimizeCallInst
4017 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4018 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004019
Chandler Carruthc8925912013-01-05 02:09:22 +00004020 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4021 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004022
Chandler Carruthc8925912013-01-05 02:09:22 +00004023 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004024 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004025 return true;
4026 continue;
4027 }
Stephen Lin837bba12013-07-15 17:55:02 +00004028
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004029 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4030 SeenInsts))
Chandler Carruthc8925912013-01-05 02:09:22 +00004031 return true;
4032 }
4033
4034 return false;
4035}
4036
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004037/// Return true if Val is already known to be live at the use site that we're
4038/// folding it into. If so, there is no cost to include it in the addressing
4039/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4040/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004041bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004042 Value *KnownLive2) {
4043 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004044 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004045 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004046
Chandler Carruthc8925912013-01-05 02:09:22 +00004047 // All values other than instructions and arguments (e.g. constants) are live.
4048 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004049
Chandler Carruthc8925912013-01-05 02:09:22 +00004050 // If Val is a constant sized alloca in the entry block, it is live, this is
4051 // true because it is just a reference to the stack/frame pointer, which is
4052 // live for the whole function.
4053 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4054 if (AI->isStaticAlloca())
4055 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004056
Chandler Carruthc8925912013-01-05 02:09:22 +00004057 // Check to see if this value is already used in the memory instruction's
4058 // block. If so, it's already live into the block at the very least, so we
4059 // can reasonably fold it.
4060 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4061}
4062
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004063/// It is possible for the addressing mode of the machine to fold the specified
4064/// instruction into a load or store that ultimately uses it.
4065/// However, the specified instruction has multiple uses.
4066/// Given this, it may actually increase register pressure to fold it
4067/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004068///
4069/// X = ...
4070/// Y = X+1
4071/// use(Y) -> nonload/store
4072/// Z = Y+1
4073/// load Z
4074///
4075/// In this case, Y has multiple uses, and can be folded into the load of Z
4076/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4077/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4078/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4079/// number of computations either.
4080///
4081/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4082/// X was live across 'load Z' for other reasons, we actually *would* want to
4083/// fold the addressing mode in the Z case. This would make Y die earlier.
4084bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004085isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004086 ExtAddrMode &AMAfter) {
4087 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004088
Chandler Carruthc8925912013-01-05 02:09:22 +00004089 // AMBefore is the addressing mode before this instruction was folded into it,
4090 // and AMAfter is the addressing mode after the instruction was folded. Get
4091 // the set of registers referenced by AMAfter and subtract out those
4092 // referenced by AMBefore: this is the set of values which folding in this
4093 // address extends the lifetime of.
4094 //
4095 // Note that there are only two potential values being referenced here,
4096 // BaseReg and ScaleReg (global addresses are always available, as are any
4097 // folded immediates).
4098 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004099
Chandler Carruthc8925912013-01-05 02:09:22 +00004100 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4101 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004102 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004103 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004104 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004105 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004106
4107 // If folding this instruction (and it's subexprs) didn't extend any live
4108 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004109 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004110 return true;
4111
Philip Reamesac115ed2016-03-09 23:13:12 +00004112 // If all uses of this instruction can have the address mode sunk into them,
4113 // we can remove the addressing mode and effectively trade one live register
4114 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004115 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004116 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4117 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004118 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004119 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004120
Chandler Carruthc8925912013-01-05 02:09:22 +00004121 // Now that we know that all uses of this instruction are part of a chain of
4122 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004123 // into a memory use, loop over each of these memory operation uses and see
4124 // if they could *actually* fold the instruction. The assumption is that
4125 // addressing modes are cheap and that duplicating the computation involved
4126 // many times is worthwhile, even on a fastpath. For sinking candidates
4127 // (i.e. cold call sites), this serves as a way to prevent excessive code
4128 // growth since most architectures have some reasonable small and fast way to
4129 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004130 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4131 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4132 Instruction *User = MemoryUses[i].first;
4133 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004134
Chandler Carruthc8925912013-01-05 02:09:22 +00004135 // Get the access type of this use. If the use isn't a pointer, we don't
4136 // know what it accesses.
4137 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004138 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4139 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004140 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004141 Type *AddressAccessTy = AddrTy->getElementType();
4142 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004143
Chandler Carruthc8925912013-01-05 02:09:22 +00004144 // Do a match against the root of this address, ignoring profitability. This
4145 // will tell us if the addressing mode for the memory operation will
4146 // *actually* cover the shared instruction.
4147 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004148 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4149 TPT.getRestorationPoint();
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004150 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
4151 AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004152 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004153 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00004154 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004155 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004156 (void)Success; assert(Success && "Couldn't select *anything*?");
4157
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004158 // The match was to check the profitability, the changes made are not
4159 // part of the original matcher. Therefore, they should be dropped
4160 // otherwise the original matcher will not present the right state.
4161 TPT.rollback(LastKnownGood);
4162
Chandler Carruthc8925912013-01-05 02:09:22 +00004163 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004164 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004165 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004166
Chandler Carruthc8925912013-01-05 02:09:22 +00004167 MatchedAddrModeInsts.clear();
4168 }
Stephen Lin837bba12013-07-15 17:55:02 +00004169
Chandler Carruthc8925912013-01-05 02:09:22 +00004170 return true;
4171}
4172
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004173/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004174/// different basic block than BB.
4175static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4176 if (Instruction *I = dyn_cast<Instruction>(V))
4177 return I->getParent() != BB;
4178 return false;
4179}
4180
Philip Reamesac115ed2016-03-09 23:13:12 +00004181/// Sink addressing mode computation immediate before MemoryInst if doing so
4182/// can be done without increasing register pressure. The need for the
4183/// register pressure constraint means this can end up being an all or nothing
4184/// decision for all uses of the same addressing computation.
4185///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004186/// Load and Store Instructions often have addressing modes that can do
4187/// significant amounts of computation. As such, instruction selection will try
4188/// to get the load or store to do as much computation as possible for the
4189/// program. The problem is that isel can only see within a single block. As
4190/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004191///
4192/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004193/// operands. It's also used to sink addressing computations feeding into cold
4194/// call sites into their (cold) basic block.
4195///
4196/// The motivation for handling sinking into cold blocks is that doing so can
4197/// both enable other address mode sinking (by satisfying the register pressure
4198/// constraint above), and reduce register pressure globally (by removing the
4199/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004200bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004201 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004202 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004203
4204 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004205 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004206 SmallVector<Value*, 8> worklist;
4207 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004208 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004209
John Brawneb83c752017-10-03 13:04:15 +00004210 // Use a worklist to iteratively look through PHI and select nodes, and
4211 // ensure that the addressing mode obtained from the non-PHI/select roots of
John Brawn736bf002017-10-03 13:08:22 +00004212 // the graph are compatible.
John Brawneb83c752017-10-03 13:04:15 +00004213 bool PhiOrSelectSeen = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004214 SmallVector<Instruction*, 16> AddrModeInsts;
Serguei Katkovaee63752017-11-05 07:59:02 +00004215 const SimplifyQuery SQ(*DL, TLInfo);
4216 AddressingModeCombiner AddrModes(SQ, { Addr, MemoryInst->getParent() });
Jun Bum Limdee55652017-04-03 19:20:07 +00004217 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004218 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4219 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004220 while (!worklist.empty()) {
4221 Value *V = worklist.back();
4222 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004223
Serguei Katkov4ea855e2017-07-19 04:49:17 +00004224 // We allow traversing cyclic Phi nodes.
4225 // In case of success after this loop we ensure that traversing through
4226 // Phi nodes ends up with all cases to compute address of the form
4227 // BaseGV + Base + Scale * Index + Offset
4228 // where Scale and Offset are constans and BaseGV, Base and Index
4229 // are exactly the same Values in all cases.
4230 // It means that BaseGV, Scale and Offset dominate our memory instruction
4231 // and have the same value as they had in address computation represented
4232 // as Phi. So we can safely sink address computation to memory instruction.
4233 if (!Visited.insert(V).second)
4234 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00004235
Owen Anderson8ba5f392010-11-27 08:15:55 +00004236 // For a PHI node, push all of its incoming values.
4237 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004238 for (Value *IncValue : P->incoming_values())
4239 worklist.push_back(IncValue);
John Brawneb83c752017-10-03 13:04:15 +00004240 PhiOrSelectSeen = true;
4241 continue;
4242 }
4243 // Similar for select.
4244 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4245 worklist.push_back(SI->getFalseValue());
4246 worklist.push_back(SI->getTrueValue());
4247 PhiOrSelectSeen = true;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004248 continue;
4249 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004250
Philip Reamesac115ed2016-03-09 23:13:12 +00004251 // For non-PHIs, determine the addressing mode being computed. Note that
4252 // the result may differ depending on what other uses our candidate
4253 // addressing instructions might have.
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004254 AddrModeInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004255 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004256 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
4257 InsertedInsts, PromotedInsts, TPT);
John Brawn736bf002017-10-03 13:08:22 +00004258 NewAddrMode.OriginalValue = V;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004259
John Brawn736bf002017-10-03 13:08:22 +00004260 if (!AddrModes.addNewAddrMode(NewAddrMode))
4261 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004262 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004263
John Brawn736bf002017-10-03 13:08:22 +00004264 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4265 // or we have multiple but either couldn't combine them or combining them
4266 // wouldn't do anything useful, bail out now.
4267 if (!AddrModes.combineAddrModes()) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004268 TPT.rollback(LastKnownGood);
4269 return false;
4270 }
4271 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004272
John Brawn736bf002017-10-03 13:08:22 +00004273 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4274 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4275
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004276 // If all the instructions matched are already in this BB, don't do anything.
John Brawneb83c752017-10-03 13:04:15 +00004277 // If we saw a Phi node then it is not local definitely, and if we saw a select
4278 // then we want to push the address calculation past it even if it's already
4279 // in this BB.
4280 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
Justin Lebar838c7f52016-11-21 22:49:11 +00004281 return IsNonLocalValue(V, MemoryInst->getParent());
Serguei Katkov0b7b59a2017-07-11 06:24:44 +00004282 })) {
David Greene74e2d492010-01-05 01:27:11 +00004283 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004284 return false;
4285 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004286
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004287 // Insert this computation right after this user. Since our caller is
4288 // scanning from the top of the BB to the bottom, reuse of the expr are
4289 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004290 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004291
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004292 // Now that we determined the addressing expression we want to use and know
4293 // that we have to sink it into this block. Check to see if we have already
Simon Dardis230f4532017-11-24 16:45:28 +00004294 // done this for some other load/store instr in this block. If so, reuse
4295 // the computation. Before attempting reuse, check if the address is valid
4296 // as it may have been erased.
4297
4298 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
4299
4300 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004301 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00004302 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004303 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004304 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004305 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004306 } else if (AddrSinkUsingGEPs ||
4307 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004308 SubtargetInfo->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004309 // By default, we use the GEP-based method when AA is used later. This
4310 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4311 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004312 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004313 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004314 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004315
4316 // First, find the pointer.
4317 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4318 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004319 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004320 }
4321
4322 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4323 // We can't add more than one pointer together, nor can we scale a
4324 // pointer (both of which seem meaningless).
4325 if (ResultPtr || AddrMode.Scale != 1)
4326 return false;
4327
4328 ResultPtr = AddrMode.ScaledReg;
4329 AddrMode.Scale = 0;
4330 }
4331
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004332 // It is only safe to sign extend the BaseReg if we know that the math
4333 // required to create it did not overflow before we extend it. Since
4334 // the original IR value was tossed in favor of a constant back when
4335 // the AddrMode was created we need to bail out gracefully if widths
4336 // do not match instead of extending it.
4337 //
4338 // (See below for code to add the scale.)
4339 if (AddrMode.Scale) {
4340 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4341 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4342 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4343 return false;
4344 }
4345
Hal Finkelc3998302014-04-12 00:59:48 +00004346 if (AddrMode.BaseGV) {
4347 if (ResultPtr)
4348 return false;
4349
4350 ResultPtr = AddrMode.BaseGV;
4351 }
4352
4353 // If the real base value actually came from an inttoptr, then the matcher
4354 // will look through it and provide only the integer value. In that case,
4355 // use it here.
Keno Fischer05e4ac22017-06-29 20:28:59 +00004356 if (!DL->isNonIntegralPointerType(Addr->getType())) {
4357 if (!ResultPtr && AddrMode.BaseReg) {
4358 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4359 "sunkaddr");
4360 AddrMode.BaseReg = nullptr;
4361 } else if (!ResultPtr && AddrMode.Scale == 1) {
4362 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4363 "sunkaddr");
4364 AddrMode.Scale = 0;
4365 }
Hal Finkelc3998302014-04-12 00:59:48 +00004366 }
4367
4368 if (!ResultPtr &&
4369 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4370 SunkAddr = Constant::getNullValue(Addr->getType());
4371 } else if (!ResultPtr) {
4372 return false;
4373 } else {
4374 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004375 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4376 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004377
4378 // Start with the base register. Do this first so that subsequent address
4379 // matching finds it last, which will prevent it from trying to match it
4380 // as the scaled value in case it happens to be a mul. That would be
4381 // problematic if we've sunk a different mul for the scale, because then
4382 // we'd end up sinking both muls.
4383 if (AddrMode.BaseReg) {
4384 Value *V = AddrMode.BaseReg;
4385 if (V->getType() != IntPtrTy)
4386 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4387
4388 ResultIndex = V;
4389 }
4390
4391 // Add the scale value.
4392 if (AddrMode.Scale) {
4393 Value *V = AddrMode.ScaledReg;
4394 if (V->getType() == IntPtrTy) {
4395 // done.
Hal Finkelc3998302014-04-12 00:59:48 +00004396 } else {
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004397 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4398 cast<IntegerType>(V->getType())->getBitWidth() &&
4399 "We can't transform if ScaledReg is too narrow");
4400 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004401 }
4402
4403 if (AddrMode.Scale != 1)
4404 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4405 "sunkaddr");
4406 if (ResultIndex)
4407 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4408 else
4409 ResultIndex = V;
4410 }
4411
4412 // Add in the Base Offset if present.
4413 if (AddrMode.BaseOffs) {
4414 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4415 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004416 // We need to add this separately from the scale above to help with
4417 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004418 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004419 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004420 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004421 }
4422
4423 ResultIndex = V;
4424 }
4425
4426 if (!ResultIndex) {
4427 SunkAddr = ResultPtr;
4428 } else {
4429 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004430 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004431 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004432 }
4433
4434 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004435 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004436 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004437 } else {
Keno Fischer05e4ac22017-06-29 20:28:59 +00004438 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4439 // non-integral pointers, so in that case bail out now.
4440 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4441 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4442 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4443 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4444 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4445 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4446 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4447 (AddrMode.BaseGV &&
4448 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4449 return false;
4450
David Greene74e2d492010-01-05 01:27:11 +00004451 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004452 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004453 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004454 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004455
4456 // Start with the base register. Do this first so that subsequent address
4457 // matching finds it last, which will prevent it from trying to match it
4458 // as the scaled value in case it happens to be a mul. That would be
4459 // problematic if we've sunk a different mul for the scale, because then
4460 // we'd end up sinking both muls.
4461 if (AddrMode.BaseReg) {
4462 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004463 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004464 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004465 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004466 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004467 Result = V;
4468 }
4469
4470 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004471 if (AddrMode.Scale) {
4472 Value *V = AddrMode.ScaledReg;
4473 if (V->getType() == IntPtrTy) {
4474 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004475 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004476 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004477 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4478 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004479 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004480 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004481 // It is only safe to sign extend the BaseReg if we know that the math
4482 // required to create it did not overflow before we extend it. Since
4483 // the original IR value was tossed in favor of a constant back when
4484 // the AddrMode was created we need to bail out gracefully if widths
4485 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004486 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004487 if (I && (Result != AddrMode.BaseReg))
4488 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004489 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004490 }
4491 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004492 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4493 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004494 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004495 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004496 else
4497 Result = V;
4498 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004499
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004500 // Add in the BaseGV if present.
4501 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004502 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004503 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004504 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004505 else
4506 Result = V;
4507 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004508
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004509 // Add in the Base Offset if present.
4510 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004511 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004512 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004513 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004514 else
4515 Result = V;
4516 }
4517
Craig Topperc0196b12014-04-14 00:51:57 +00004518 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004519 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004520 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004521 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004522 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004523
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004524 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Simon Dardis230f4532017-11-24 16:45:28 +00004525 // Store the newly computed address into the cache. In the case we reused a
4526 // value, this should be idempotent.
4527 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004528
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004529 // If we have no uses, recursively delete the value and all dead instructions
4530 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004531 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004532 // This can cause recursive deletion, which can invalidate our iterator.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004533 // Use a WeakTrackingVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004534 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004535 WeakTrackingVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004536 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004537
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004538 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004539
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004540 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004541 // If the iterator instruction was recursively deleted, start over at the
4542 // start of the block.
4543 CurInstIterator = BB->begin();
4544 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004545 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004546 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004547 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004548 return true;
4549}
4550
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004551/// If there are any memory operands, use OptimizeMemoryInst to sink their
4552/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004553bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004554 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004555
Eric Christopher11e4df72015-02-26 22:38:43 +00004556 const TargetRegisterInfo *TRI =
Sanjay Patel4137d512017-06-07 14:29:52 +00004557 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004558 TargetLowering::AsmOperandInfoVector TargetConstraints =
4559 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004560 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004561 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4562 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004563
Evan Cheng1da25002008-02-26 02:42:37 +00004564 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004565 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004566
Eli Friedman666bbe32008-02-26 18:37:49 +00004567 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4568 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004569 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004570 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004571 } else if (OpInfo.Type == InlineAsm::isInput)
4572 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004573 }
4574
4575 return MadeChange;
4576}
4577
Jun Bum Lim42301012017-03-17 19:05:21 +00004578/// \brief Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004579/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00004580static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4581 assert(!Val->use_empty() && "Input must have at least one use");
4582 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004583 bool IsSExt = isa<SExtInst>(FirstUser);
4584 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00004585 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004586 const Instruction *UI = cast<Instruction>(U);
4587 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4588 return false;
4589 Type *CurTy = UI->getType();
4590 // Same input and output types: Same instruction after CSE.
4591 if (CurTy == ExtTy)
4592 continue;
4593
4594 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00004595 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004596 // b = sext ty1 a to ty2
4597 // c = sext ty1 a to ty3
4598 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00004599 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004600 // b = sext ty1 a to ty2
4601 // c = sext ty2 b to ty3
4602 // However, the last sext is not free.
4603 if (IsSExt)
4604 return false;
4605
4606 // This is a ZExt, maybe this is free to extend from one type to another.
4607 // In that case, we would not account for a different use.
4608 Type *NarrowTy;
4609 Type *LargeTy;
4610 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4611 CurTy->getScalarType()->getIntegerBitWidth()) {
4612 NarrowTy = CurTy;
4613 LargeTy = ExtTy;
4614 } else {
4615 NarrowTy = ExtTy;
4616 LargeTy = CurTy;
4617 }
4618
4619 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4620 return false;
4621 }
4622 // All uses are the same or can be derived from one another for free.
4623 return true;
4624}
4625
Jun Bum Lim42301012017-03-17 19:05:21 +00004626/// \brief Try to speculatively promote extensions in \p Exts and continue
4627/// promoting through newly promoted operands recursively as far as doing so is
4628/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4629/// When some promotion happened, \p TPT contains the proper state to revert
4630/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004631///
Jun Bum Lim42301012017-03-17 19:05:21 +00004632/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00004633bool CodeGenPrepare::tryToPromoteExts(
4634 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4635 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4636 unsigned CreatedInstsCost) {
4637 bool Promoted = false;
4638
4639 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004640 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004641 // Early check if we directly have ext(load).
4642 if (isa<LoadInst>(I->getOperand(0))) {
4643 ProfitablyMovedExts.push_back(I);
4644 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004645 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004646
4647 // Check whether or not we want to do any promotion. The reason we have
4648 // this check inside the for loop is to catch the case where an extension
4649 // is directly fed by a load because in such case the extension can be moved
4650 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004651 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00004652 return false;
4653
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004654 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00004655 TypePromotionHelper::Action TPH =
4656 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004657 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00004658 if (!TPH) {
4659 // Save the current extension as we cannot move up through its operand.
4660 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004661 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00004662 }
4663
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004664 // Save the current state.
4665 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4666 TPT.getRestorationPoint();
4667 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004668 unsigned NewCreatedInstsCost = 0;
4669 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004670 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004671 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4672 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004673 assert(PromotedVal &&
4674 "TypePromotionHelper should have filtered out those cases");
4675
4676 // We would be able to merge only one extension in a load.
4677 // Therefore, if we have more than 1 new extension we heuristically
4678 // cut this search path, because it means we degrade the code quality.
4679 // With exactly 2, the transformation is neutral, because we will merge
4680 // one extension but leave one. However, we optimistically keep going,
4681 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004682 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004683 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00004684 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004685 TotalCreatedInstsCost =
4686 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004687 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004688 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004689 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004690 // This promotion is not profitable, rollback to the previous state, and
4691 // save the current extension in ProfitablyMovedExts as the latest
4692 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004693 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00004694 ProfitablyMovedExts.push_back(I);
4695 continue;
4696 }
4697 // Continue promoting NewExts as far as doing so is profitable.
4698 SmallVector<Instruction *, 2> NewlyMovedExts;
4699 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4700 bool NewPromoted = false;
4701 for (auto ExtInst : NewlyMovedExts) {
4702 Instruction *MovedExt = cast<Instruction>(ExtInst);
4703 Value *ExtOperand = MovedExt->getOperand(0);
4704 // If we have reached to a load, we need this extra profitability check
4705 // as it could potentially be merged into an ext(load).
4706 if (isa<LoadInst>(ExtOperand) &&
4707 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4708 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
4709 continue;
4710
4711 ProfitablyMovedExts.push_back(MovedExt);
4712 NewPromoted = true;
4713 }
4714
4715 // If none of speculative promotions for NewExts is profitable, rollback
4716 // and save the current extension (I) as the last profitable extension.
4717 if (!NewPromoted) {
4718 TPT.rollback(LastKnownGood);
4719 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004720 continue;
4721 }
4722 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00004723 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004724 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004725 return Promoted;
4726}
4727
Jun Bum Limdee55652017-04-03 19:20:07 +00004728/// Merging redundant sexts when one is dominating the other.
4729bool CodeGenPrepare::mergeSExts(Function &F) {
4730 DominatorTree DT(F);
4731 bool Changed = false;
4732 for (auto &Entry : ValToSExtendedUses) {
4733 SExts &Insts = Entry.second;
4734 SExts CurPts;
4735 for (Instruction *Inst : Insts) {
4736 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
4737 Inst->getOperand(0) != Entry.first)
4738 continue;
4739 bool inserted = false;
4740 for (auto &Pt : CurPts) {
4741 if (DT.dominates(Inst, Pt)) {
4742 Pt->replaceAllUsesWith(Inst);
4743 RemovedInsts.insert(Pt);
4744 Pt->removeFromParent();
4745 Pt = Inst;
4746 inserted = true;
4747 Changed = true;
4748 break;
4749 }
4750 if (!DT.dominates(Pt, Inst))
4751 // Give up if we need to merge in a common dominator as the
4752 // expermients show it is not profitable.
4753 continue;
4754 Inst->replaceAllUsesWith(Pt);
4755 RemovedInsts.insert(Inst);
4756 Inst->removeFromParent();
4757 inserted = true;
4758 Changed = true;
4759 break;
4760 }
4761 if (!inserted)
4762 CurPts.push_back(Inst);
4763 }
4764 }
4765 return Changed;
4766}
4767
Jun Bum Lim42301012017-03-17 19:05:21 +00004768/// Return true, if an ext(load) can be formed from an extension in
4769/// \p MovedExts.
4770bool CodeGenPrepare::canFormExtLd(
4771 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
4772 Instruction *&Inst, bool HasPromoted) {
4773 for (auto *MovedExtInst : MovedExts) {
4774 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
4775 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
4776 Inst = MovedExtInst;
4777 break;
4778 }
4779 }
4780 if (!LI)
4781 return false;
4782
4783 // If they're already in the same block, there's nothing to do.
4784 // Make the cheap checks first if we did not promote.
4785 // If we promoted, we need to check if it is indeed profitable.
4786 if (!HasPromoted && LI->getParent() == Inst->getParent())
4787 return false;
4788
Haicheng Wuabdef9e2017-07-15 02:12:16 +00004789 return TLI->isExtLoad(LI, Inst, *DL);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004790}
4791
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004792/// Move a zext or sext fed by a load into the same basic block as the load,
4793/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4794/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00004795///
Jun Bum Limdee55652017-04-03 19:20:07 +00004796/// E.g.,
4797/// \code
4798/// %ld = load i32* %addr
4799/// %add = add nuw i32 %ld, 4
4800/// %zext = zext i32 %add to i64
4801// \endcode
4802/// =>
4803/// \code
4804/// %ld = load i32* %addr
4805/// %zext = zext i32 %ld to i64
4806/// %add = add nuw i64 %zext, 4
4807/// \encode
4808/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
4809/// allow us to match zext(load i32*) to i64.
4810///
4811/// Also, try to promote the computations used to obtain a sign extended
4812/// value used into memory accesses.
4813/// E.g.,
4814/// \code
4815/// a = add nsw i32 b, 3
4816/// d = sext i32 a to i64
4817/// e = getelementptr ..., i64 d
4818/// \endcode
4819/// =>
4820/// \code
4821/// f = sext i32 b to i64
4822/// a = add nsw i64 f, 3
4823/// e = getelementptr ..., i64 a
4824/// \endcode
4825///
4826/// \p Inst[in/out] the extension may be modified during the process if some
4827/// promotions apply.
4828bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
4829 // ExtLoad formation and address type promotion infrastructure requires TLI to
4830 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00004831 if (!TLI)
4832 return false;
4833
Jun Bum Limdee55652017-04-03 19:20:07 +00004834 bool AllowPromotionWithoutCommonHeader = false;
4835 /// See if it is an interesting sext operations for the address type
4836 /// promotion before trying to promote it, e.g., the ones with the right
4837 /// type and used in memory accesses.
4838 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
4839 *Inst, AllowPromotionWithoutCommonHeader);
4840 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004841 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00004842 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004843 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00004844 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
4845 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00004846
Jun Bum Limdee55652017-04-03 19:20:07 +00004847 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00004848
Dan Gohman99429a02009-10-16 20:59:35 +00004849 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004850 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00004851 Instruction *ExtFedByLoad;
4852
4853 // Try to promote a chain of computation if it allows to form an extended
4854 // load.
4855 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
4856 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
4857 TPT.commit();
4858 // Move the extend into the same block as the load
Sanjay Patel674d2c22017-08-29 14:07:48 +00004859 ExtFedByLoad->moveAfter(LI);
Jun Bum Limdee55652017-04-03 19:20:07 +00004860 // CGP does not check if the zext would be speculatively executed when moved
4861 // to the same basic block as the load. Preserving its original location
4862 // would pessimize the debugging experience, as well as negatively impact
4863 // the quality of sample pgo. We don't want to use "line 0" as that has a
4864 // size cost in the line-table section and logically the zext can be seen as
4865 // part of the load. Therefore we conservatively reuse the same debug
4866 // location for the load and the zext.
4867 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
4868 ++NumExtsMoved;
4869 Inst = ExtFedByLoad;
4870 return true;
4871 }
4872
4873 // Continue promoting SExts if known as considerable depending on targets.
4874 if (ATPConsiderable &&
4875 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
4876 HasPromoted, TPT, SpeculativelyMovedExts))
4877 return true;
4878
4879 TPT.rollback(LastKnownGood);
4880 return false;
4881}
4882
4883// Perform address type promotion if doing so is profitable.
4884// If AllowPromotionWithoutCommonHeader == false, we should find other sext
4885// instructions that sign extended the same initial value. However, if
4886// AllowPromotionWithoutCommonHeader == true, we expect promoting the
4887// extension is just profitable.
4888bool CodeGenPrepare::performAddressTypePromotion(
4889 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
4890 bool HasPromoted, TypePromotionTransaction &TPT,
4891 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
4892 bool Promoted = false;
4893 SmallPtrSet<Instruction *, 1> UnhandledExts;
4894 bool AllSeenFirst = true;
4895 for (auto I : SpeculativelyMovedExts) {
4896 Value *HeadOfChain = I->getOperand(0);
4897 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
4898 SeenChainsForSExt.find(HeadOfChain);
4899 // If there is an unhandled SExt which has the same header, try to promote
4900 // it as well.
4901 if (AlreadySeen != SeenChainsForSExt.end()) {
4902 if (AlreadySeen->second != nullptr)
4903 UnhandledExts.insert(AlreadySeen->second);
4904 AllSeenFirst = false;
4905 }
4906 }
4907
4908 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
4909 SpeculativelyMovedExts.size() == 1)) {
4910 TPT.commit();
4911 if (HasPromoted)
4912 Promoted = true;
4913 for (auto I : SpeculativelyMovedExts) {
4914 Value *HeadOfChain = I->getOperand(0);
4915 SeenChainsForSExt[HeadOfChain] = nullptr;
4916 ValToSExtendedUses[HeadOfChain].push_back(I);
4917 }
4918 // Update Inst as promotion happen.
4919 Inst = SpeculativelyMovedExts.pop_back_val();
4920 } else {
4921 // This is the first chain visited from the header, keep the current chain
4922 // as unhandled. Defer to promote this until we encounter another SExt
4923 // chain derived from the same header.
4924 for (auto I : SpeculativelyMovedExts) {
4925 Value *HeadOfChain = I->getOperand(0);
4926 SeenChainsForSExt[HeadOfChain] = Inst;
4927 }
Dan Gohman99429a02009-10-16 20:59:35 +00004928 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004929 }
Dan Gohman99429a02009-10-16 20:59:35 +00004930
Jun Bum Limdee55652017-04-03 19:20:07 +00004931 if (!AllSeenFirst && !UnhandledExts.empty())
4932 for (auto VisitedSExt : UnhandledExts) {
4933 if (RemovedInsts.count(VisitedSExt))
4934 continue;
4935 TypePromotionTransaction TPT(RemovedInsts);
4936 SmallVector<Instruction *, 1> Exts;
4937 SmallVector<Instruction *, 2> Chains;
4938 Exts.push_back(VisitedSExt);
4939 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
4940 TPT.commit();
4941 if (HasPromoted)
4942 Promoted = true;
4943 for (auto I : Chains) {
4944 Value *HeadOfChain = I->getOperand(0);
4945 // Mark this as handled.
4946 SeenChainsForSExt[HeadOfChain] = nullptr;
4947 ValToSExtendedUses[HeadOfChain].push_back(I);
4948 }
4949 }
4950 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00004951}
4952
Sanjay Patelfc580a62015-09-21 23:03:16 +00004953bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004954 BasicBlock *DefBB = I->getParent();
4955
Bob Wilsonff714f92010-09-21 21:44:14 +00004956 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004957 // other uses of the source with result of extension.
4958 Value *Src = I->getOperand(0);
4959 if (Src->hasOneUse())
4960 return false;
4961
Evan Cheng2011df42007-12-13 07:50:36 +00004962 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004963 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004964 return false;
4965
Evan Cheng7bc89422007-12-12 00:51:06 +00004966 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004967 // this block.
4968 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004969 return false;
4970
Evan Chengd3d80172007-12-05 23:58:20 +00004971 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004972 for (User *U : I->users()) {
4973 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004974
4975 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004976 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004977 if (UserBB == DefBB) continue;
4978 DefIsLiveOut = true;
4979 break;
4980 }
4981 if (!DefIsLiveOut)
4982 return false;
4983
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004984 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004985 for (User *U : Src->users()) {
4986 Instruction *UI = cast<Instruction>(U);
4987 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004988 if (UserBB == DefBB) continue;
4989 // Be conservative. We don't want this xform to end up introducing
4990 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004991 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004992 return false;
4993 }
4994
Evan Chengd3d80172007-12-05 23:58:20 +00004995 // InsertedTruncs - Only insert one trunc in each block once.
4996 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4997
4998 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004999 for (Use &U : Src->uses()) {
5000 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00005001
5002 // Figure out which BB this ext is used in.
5003 BasicBlock *UserBB = User->getParent();
5004 if (UserBB == DefBB) continue;
5005
5006 // Both src and def are live in this block. Rewrite the use.
5007 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5008
5009 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00005010 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005011 assert(InsertPt != UserBB->end());
5012 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005013 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00005014 }
5015
5016 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005017 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00005018 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00005019 MadeChange = true;
5020 }
5021
5022 return MadeChange;
5023}
5024
Geoff Berry5256fca2015-11-20 22:34:39 +00005025// Find loads whose uses only use some of the loaded value's bits. Add an "and"
5026// just after the load if the target can fold this into one extload instruction,
5027// with the hope of eliminating some of the other later "and" instructions using
5028// the loaded value. "and"s that are made trivially redundant by the insertion
5029// of the new "and" are removed by this function, while others (e.g. those whose
5030// path from the load goes through a phi) are left for isel to potentially
5031// remove.
5032//
5033// For example:
5034//
5035// b0:
5036// x = load i32
5037// ...
5038// b1:
5039// y = and x, 0xff
5040// z = use y
5041//
5042// becomes:
5043//
5044// b0:
5045// x = load i32
5046// x' = and x, 0xff
5047// ...
5048// b1:
5049// z = use x'
5050//
5051// whereas:
5052//
5053// b0:
5054// x1 = load i32
5055// ...
5056// b1:
5057// x2 = load i32
5058// ...
5059// b2:
5060// x = phi x1, x2
5061// y = and x, 0xff
5062//
5063// becomes (after a call to optimizeLoadExt for each load):
5064//
5065// b0:
5066// x1 = load i32
5067// x1' = and x1, 0xff
5068// ...
5069// b1:
5070// x2 = load i32
5071// x2' = and x2, 0xff
5072// ...
5073// b2:
5074// x = phi x1', x2'
5075// y = and x, 0xff
Geoff Berry5256fca2015-11-20 22:34:39 +00005076bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005077 if (!Load->isSimple() ||
5078 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5079 return false;
5080
Geoff Berry5d534b62017-02-21 18:53:14 +00005081 // Skip loads we've already transformed.
5082 if (Load->hasOneUse() &&
5083 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5084 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005085
5086 // Look at all uses of Load, looking through phis, to determine how many bits
5087 // of the loaded value are needed.
5088 SmallVector<Instruction *, 8> WorkList;
5089 SmallPtrSet<Instruction *, 16> Visited;
5090 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5091 for (auto *U : Load->users())
5092 WorkList.push_back(cast<Instruction>(U));
5093
5094 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5095 unsigned BitWidth = LoadResultVT.getSizeInBits();
5096 APInt DemandBits(BitWidth, 0);
5097 APInt WidestAndBits(BitWidth, 0);
5098
5099 while (!WorkList.empty()) {
5100 Instruction *I = WorkList.back();
5101 WorkList.pop_back();
5102
5103 // Break use-def graph loops.
5104 if (!Visited.insert(I).second)
5105 continue;
5106
5107 // For a PHI node, push all of its users.
5108 if (auto *Phi = dyn_cast<PHINode>(I)) {
5109 for (auto *U : Phi->users())
5110 WorkList.push_back(cast<Instruction>(U));
5111 continue;
5112 }
5113
5114 switch (I->getOpcode()) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005115 case Instruction::And: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005116 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5117 if (!AndC)
5118 return false;
5119 APInt AndBits = AndC->getValue();
5120 DemandBits |= AndBits;
5121 // Keep track of the widest and mask we see.
5122 if (AndBits.ugt(WidestAndBits))
5123 WidestAndBits = AndBits;
5124 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5125 AndsToMaybeRemove.push_back(I);
5126 break;
5127 }
5128
Eugene Zelenko900b6332017-08-29 22:32:07 +00005129 case Instruction::Shl: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005130 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5131 if (!ShlC)
5132 return false;
5133 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00005134 DemandBits.setLowBits(BitWidth - ShiftAmt);
Geoff Berry5256fca2015-11-20 22:34:39 +00005135 break;
5136 }
5137
Eugene Zelenko900b6332017-08-29 22:32:07 +00005138 case Instruction::Trunc: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005139 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5140 unsigned TruncBitWidth = TruncVT.getSizeInBits();
Craig Topperfc947bc2017-04-18 17:14:21 +00005141 DemandBits.setLowBits(TruncBitWidth);
Geoff Berry5256fca2015-11-20 22:34:39 +00005142 break;
5143 }
5144
5145 default:
5146 return false;
5147 }
5148 }
5149
5150 uint32_t ActiveBits = DemandBits.getActiveBits();
5151 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5152 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5153 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5154 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5155 // followed by an AND.
5156 // TODO: Look into removing this restriction by fixing backends to either
5157 // return false for isLoadExtLegal for i1 or have them select this pattern to
5158 // a single instruction.
5159 //
5160 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5161 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005162 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005163 WidestAndBits != DemandBits)
5164 return false;
5165
5166 LLVMContext &Ctx = Load->getType()->getContext();
5167 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5168 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5169
5170 // Reject cases that won't be matched as extloads.
5171 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5172 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5173 return false;
5174
5175 IRBuilder<> Builder(Load->getNextNode());
5176 auto *NewAnd = dyn_cast<Instruction>(
5177 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005178 // Mark this instruction as "inserted by CGP", so that other
5179 // optimizations don't touch it.
5180 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005181
5182 // Replace all uses of load with new and (except for the use of load in the
5183 // new and itself).
5184 Load->replaceAllUsesWith(NewAnd);
5185 NewAnd->setOperand(0, Load);
5186
5187 // Remove any and instructions that are now redundant.
5188 for (auto *And : AndsToMaybeRemove)
5189 // Check that the and mask is the same as the one we decided to put on the
5190 // new and.
5191 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5192 And->replaceAllUsesWith(NewAnd);
5193 if (&*CurInstIterator == And)
5194 CurInstIterator = std::next(And->getIterator());
5195 And->eraseFromParent();
5196 ++NumAndUses;
5197 }
5198
5199 ++NumAndsAdded;
5200 return true;
5201}
5202
Sanjay Patel69a50a12015-10-19 21:59:12 +00005203/// Check if V (an operand of a select instruction) is an expensive instruction
5204/// that is only used once.
5205static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5206 auto *I = dyn_cast<Instruction>(V);
5207 // If it's safe to speculatively execute, then it should not have side
5208 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005209 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5210 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005211}
5212
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005213/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005214static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005215 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005216 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005217 // If even a predictable select is cheap, then a branch can't be cheaper.
5218 if (!TLI->isPredictableSelectExpensive())
5219 return false;
5220
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005221 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005222 // whether a select is better represented as a branch.
5223
5224 // If metadata tells us that the select condition is obviously predictable,
5225 // then we want to replace the select with a branch.
5226 uint64_t TrueWeight, FalseWeight;
5227 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5228 uint64_t Max = std::max(TrueWeight, FalseWeight);
5229 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005230 if (Sum != 0) {
5231 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5232 if (Probability > TLI->getPredictableBranchThreshold())
5233 return true;
5234 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005235 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005236
5237 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5238
Sanjay Patel4e652762015-09-28 22:14:51 +00005239 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5240 // comparison condition. If the compare has more than one use, there's
5241 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005242 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005243 return false;
5244
Sanjay Patel69a50a12015-10-19 21:59:12 +00005245 // If either operand of the select is expensive and only needed on one side
5246 // of the select, we should form a branch.
5247 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5248 sinkSelectOperand(TTI, SI->getFalseValue()))
5249 return true;
5250
5251 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005252}
5253
Dehao Chen9bbb9412016-09-12 20:23:28 +00005254/// If \p isTrue is true, return the true value of \p SI, otherwise return
5255/// false value of \p SI. If the true/false value of \p SI is defined by any
5256/// select instructions in \p Selects, look through the defining select
5257/// instruction until the true/false value is not defined in \p Selects.
5258static Value *getTrueOrFalseValue(
5259 SelectInst *SI, bool isTrue,
5260 const SmallPtrSet<const Instruction *, 2> &Selects) {
5261 Value *V;
5262
5263 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5264 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005265 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005266 "The condition of DefSI does not match with SI");
5267 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5268 }
5269 return V;
5270}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005271
Nadav Rotem9d832022012-09-02 12:10:19 +00005272/// If we have a SelectInst that will likely profit from branch prediction,
5273/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005274bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00005275 // Find all consecutive select instructions that share the same condition.
5276 SmallVector<SelectInst *, 2> ASI;
5277 ASI.push_back(SI);
5278 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5279 It != SI->getParent()->end(); ++It) {
5280 SelectInst *I = dyn_cast<SelectInst>(&*It);
5281 if (I && SI->getCondition() == I->getCondition()) {
5282 ASI.push_back(I);
5283 } else {
5284 break;
5285 }
5286 }
5287
5288 SelectInst *LastSI = ASI.back();
5289 // Increment the current iterator to skip all the rest of select instructions
5290 // because they will be either "not lowered" or "all lowered" to branch.
5291 CurInstIterator = std::next(LastSI->getIterator());
5292
Nadav Rotem9d832022012-09-02 12:10:19 +00005293 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5294
5295 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00005296 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
5297 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005298 return false;
5299
Nadav Rotem9d832022012-09-02 12:10:19 +00005300 TargetLowering::SelectSupportKind SelectKind;
5301 if (VectorCond)
5302 SelectKind = TargetLowering::VectorMaskSelect;
5303 else if (SI->getType()->isVectorTy())
5304 SelectKind = TargetLowering::ScalarCondVectorVal;
5305 else
5306 SelectKind = TargetLowering::ScalarValSelect;
5307
Sanjay Pateld66607b2016-04-26 17:11:17 +00005308 if (TLI->isSelectSupported(SelectKind) &&
5309 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5310 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005311
5312 ModifiedDT = true;
5313
Sanjay Patel69a50a12015-10-19 21:59:12 +00005314 // Transform a sequence like this:
5315 // start:
5316 // %cmp = cmp uge i32 %a, %b
5317 // %sel = select i1 %cmp, i32 %c, i32 %d
5318 //
5319 // Into:
5320 // start:
5321 // %cmp = cmp uge i32 %a, %b
5322 // br i1 %cmp, label %select.true, label %select.false
5323 // select.true:
5324 // br label %select.end
5325 // select.false:
5326 // br label %select.end
5327 // select.end:
5328 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5329 //
5330 // In addition, we may sink instructions that produce %c or %d from
5331 // the entry block into the destination(s) of the new branch.
5332 // If the true or false blocks do not contain a sunken instruction, that
5333 // block and its branch may be optimized away. In that case, one side of the
5334 // first branch will point directly to select.end, and the corresponding PHI
5335 // predecessor block will be the start block.
5336
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005337 // First, we split the block containing the select into 2 blocks.
5338 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005339 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005340 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005341
Sanjay Patel69a50a12015-10-19 21:59:12 +00005342 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005343 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005344
5345 // These are the new basic blocks for the conditional branch.
5346 // At least one will become an actual new basic block.
5347 BasicBlock *TrueBlock = nullptr;
5348 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005349 BranchInst *TrueBranch = nullptr;
5350 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005351
5352 // Sink expensive instructions into the conditional blocks to avoid executing
5353 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005354 for (SelectInst *SI : ASI) {
5355 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5356 if (TrueBlock == nullptr) {
5357 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5358 EndBlock->getParent(), EndBlock);
5359 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5360 }
5361 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5362 TrueInst->moveBefore(TrueBranch);
5363 }
5364 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5365 if (FalseBlock == nullptr) {
5366 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5367 EndBlock->getParent(), EndBlock);
5368 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5369 }
5370 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5371 FalseInst->moveBefore(FalseBranch);
5372 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005373 }
5374
5375 // If there was nothing to sink, then arbitrarily choose the 'false' side
5376 // for a new input value to the PHI.
5377 if (TrueBlock == FalseBlock) {
5378 assert(TrueBlock == nullptr &&
5379 "Unexpected basic block transform while optimizing select");
5380
5381 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5382 EndBlock->getParent(), EndBlock);
5383 BranchInst::Create(EndBlock, FalseBlock);
5384 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005385
5386 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005387 // If we did not create a new block for one of the 'true' or 'false' paths
5388 // of the condition, it means that side of the branch goes to the end block
5389 // directly and the path originates from the start block from the point of
5390 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005391 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005392 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005393 TT = EndBlock;
5394 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005395 TrueBlock = StartBlock;
5396 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005397 TT = TrueBlock;
5398 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005399 FalseBlock = StartBlock;
5400 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005401 TT = TrueBlock;
5402 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005403 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005404 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005405
Dehao Chen9bbb9412016-09-12 20:23:28 +00005406 SmallPtrSet<const Instruction *, 2> INS;
5407 INS.insert(ASI.begin(), ASI.end());
5408 // Use reverse iterator because later select may use the value of the
5409 // earlier select, and we need to propagate value through earlier select
5410 // to get the PHI operand.
5411 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5412 SelectInst *SI = *It;
5413 // The select itself is replaced with a PHI Node.
5414 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5415 PN->takeName(SI);
5416 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5417 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00005418
Dehao Chen9bbb9412016-09-12 20:23:28 +00005419 SI->replaceAllUsesWith(PN);
5420 SI->eraseFromParent();
5421 INS.erase(SI);
5422 ++NumSelectsExpanded;
5423 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005424
5425 // Instruct OptimizeBlock to skip to the next block.
5426 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005427 return true;
5428}
5429
Benjamin Kramer573ff362014-03-01 17:24:40 +00005430static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005431 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5432 int SplatElem = -1;
5433 for (unsigned i = 0; i < Mask.size(); ++i) {
5434 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5435 return false;
5436 SplatElem = Mask[i];
5437 }
5438
5439 return true;
5440}
5441
5442/// Some targets have expensive vector shifts if the lanes aren't all the same
5443/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5444/// it's often worth sinking a shufflevector splat down to its use so that
5445/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005446bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005447 BasicBlock *DefBB = SVI->getParent();
5448
5449 // Only do this xform if variable vector shifts are particularly expensive.
5450 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5451 return false;
5452
5453 // We only expect better codegen by sinking a shuffle if we can recognise a
5454 // constant splat.
5455 if (!isBroadcastShuffle(SVI))
5456 return false;
5457
5458 // InsertedShuffles - Only insert a shuffle in each block once.
5459 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5460
5461 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005462 for (User *U : SVI->users()) {
5463 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005464
5465 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005466 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005467 if (UserBB == DefBB) continue;
5468
5469 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005470 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005471
5472 // Everything checks out, sink the shuffle if the user's block doesn't
5473 // already have a copy.
5474 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5475
5476 if (!InsertedShuffle) {
5477 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005478 assert(InsertPt != UserBB->end());
5479 InsertedShuffle =
5480 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5481 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005482 }
5483
Chandler Carruthcdf47882014-03-09 03:16:01 +00005484 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005485 MadeChange = true;
5486 }
5487
5488 // If we removed all uses, nuke the shuffle.
5489 if (SVI->use_empty()) {
5490 SVI->eraseFromParent();
5491 MadeChange = true;
5492 }
5493
5494 return MadeChange;
5495}
5496
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005497bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5498 if (!TLI || !DL)
5499 return false;
5500
5501 Value *Cond = SI->getCondition();
5502 Type *OldType = Cond->getType();
5503 LLVMContext &Context = Cond->getContext();
5504 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5505 unsigned RegWidth = RegType.getSizeInBits();
5506
5507 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5508 return false;
5509
5510 // If the register width is greater than the type width, expand the condition
5511 // of the switch instruction and each case constant to the width of the
5512 // register. By widening the type of the switch condition, subsequent
5513 // comparisons (for case comparisons) will not need to be extended to the
5514 // preferred register width, so we will potentially eliminate N-1 extends,
5515 // where N is the number of cases in the switch.
5516 auto *NewType = Type::getIntNTy(Context, RegWidth);
5517
5518 // Zero-extend the switch condition and case constants unless the switch
5519 // condition is a function argument that is already being sign-extended.
5520 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5521 // everything instead.
5522 Instruction::CastOps ExtType = Instruction::ZExt;
5523 if (auto *Arg = dyn_cast<Argument>(Cond))
5524 if (Arg->hasSExtAttr())
5525 ExtType = Instruction::SExt;
5526
5527 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5528 ExtInst->insertBefore(SI);
5529 SI->setCondition(ExtInst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00005530 for (auto Case : SI->cases()) {
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005531 APInt NarrowConst = Case.getCaseValue()->getValue();
5532 APInt WideConst = (ExtType == Instruction::ZExt) ?
5533 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5534 Case.setValue(ConstantInt::get(Context, WideConst));
5535 }
5536
5537 return true;
5538}
5539
Zaara Syeda3a7578c2017-05-31 17:12:38 +00005540
Quentin Colombetc32615d2014-10-31 17:52:53 +00005541namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005542
Quentin Colombetc32615d2014-10-31 17:52:53 +00005543/// \brief Helper class to promote a scalar operation to a vector one.
5544/// This class is used to move downward extractelement transition.
5545/// E.g.,
5546/// a = vector_op <2 x i32>
5547/// b = extractelement <2 x i32> a, i32 0
5548/// c = scalar_op b
5549/// store c
5550///
5551/// =>
5552/// a = vector_op <2 x i32>
5553/// c = vector_op a (equivalent to scalar_op on the related lane)
5554/// * d = extractelement <2 x i32> c, i32 0
5555/// * store d
5556/// Assuming both extractelement and store can be combine, we get rid of the
5557/// transition.
5558class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005559 /// DataLayout associated with the current module.
5560 const DataLayout &DL;
5561
Quentin Colombetc32615d2014-10-31 17:52:53 +00005562 /// Used to perform some checks on the legality of vector operations.
5563 const TargetLowering &TLI;
5564
5565 /// Used to estimated the cost of the promoted chain.
5566 const TargetTransformInfo &TTI;
5567
5568 /// The transition being moved downwards.
5569 Instruction *Transition;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005570
Quentin Colombetc32615d2014-10-31 17:52:53 +00005571 /// The sequence of instructions to be promoted.
5572 SmallVector<Instruction *, 4> InstsToBePromoted;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005573
Quentin Colombetc32615d2014-10-31 17:52:53 +00005574 /// Cost of combining a store and an extract.
5575 unsigned StoreExtractCombineCost;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005576
Quentin Colombetc32615d2014-10-31 17:52:53 +00005577 /// Instruction that will be combined with the transition.
Eugene Zelenko900b6332017-08-29 22:32:07 +00005578 Instruction *CombineInst = nullptr;
Quentin Colombetc32615d2014-10-31 17:52:53 +00005579
5580 /// \brief The instruction that represents the current end of the transition.
5581 /// Since we are faking the promotion until we reach the end of the chain
5582 /// of computation, we need a way to get the current end of the transition.
5583 Instruction *getEndOfTransition() const {
5584 if (InstsToBePromoted.empty())
5585 return Transition;
5586 return InstsToBePromoted.back();
5587 }
5588
5589 /// \brief Return the index of the original value in the transition.
5590 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5591 /// c, is at index 0.
5592 unsigned getTransitionOriginalValueIdx() const {
5593 assert(isa<ExtractElementInst>(Transition) &&
5594 "Other kind of transitions are not supported yet");
5595 return 0;
5596 }
5597
5598 /// \brief Return the index of the index in the transition.
5599 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5600 /// is at index 1.
5601 unsigned getTransitionIdx() const {
5602 assert(isa<ExtractElementInst>(Transition) &&
5603 "Other kind of transitions are not supported yet");
5604 return 1;
5605 }
5606
5607 /// \brief Get the type of the transition.
5608 /// This is the type of the original value.
5609 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5610 /// transition is <2 x i32>.
5611 Type *getTransitionType() const {
5612 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5613 }
5614
5615 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5616 /// I.e., we have the following sequence:
5617 /// Def = Transition <ty1> a to <ty2>
5618 /// b = ToBePromoted <ty2> Def, ...
5619 /// =>
5620 /// b = ToBePromoted <ty1> a, ...
5621 /// Def = Transition <ty1> ToBePromoted to <ty2>
5622 void promoteImpl(Instruction *ToBePromoted);
5623
5624 /// \brief Check whether or not it is profitable to promote all the
5625 /// instructions enqueued to be promoted.
5626 bool isProfitableToPromote() {
5627 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5628 unsigned Index = isa<ConstantInt>(ValIdx)
5629 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5630 : -1;
5631 Type *PromotedType = getTransitionType();
5632
5633 StoreInst *ST = cast<StoreInst>(CombineInst);
5634 unsigned AS = ST->getPointerAddressSpace();
5635 unsigned Align = ST->getAlignment();
5636 // Check if this store is supported.
5637 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005638 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5639 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005640 // If this is not supported, there is no way we can combine
5641 // the extract with the store.
5642 return false;
5643 }
5644
5645 // The scalar chain of computation has to pay for the transition
5646 // scalar to vector.
5647 // The vector chain has to account for the combining cost.
5648 uint64_t ScalarCost =
5649 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5650 uint64_t VectorCost = StoreExtractCombineCost;
5651 for (const auto &Inst : InstsToBePromoted) {
5652 // Compute the cost.
5653 // By construction, all instructions being promoted are arithmetic ones.
5654 // Moreover, one argument is a constant that can be viewed as a splat
5655 // constant.
5656 Value *Arg0 = Inst->getOperand(0);
5657 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5658 isa<ConstantFP>(Arg0);
5659 TargetTransformInfo::OperandValueKind Arg0OVK =
5660 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5661 : TargetTransformInfo::OK_AnyValue;
5662 TargetTransformInfo::OperandValueKind Arg1OVK =
5663 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5664 : TargetTransformInfo::OK_AnyValue;
5665 ScalarCost += TTI.getArithmeticInstrCost(
5666 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5667 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5668 Arg0OVK, Arg1OVK);
5669 }
5670 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5671 << ScalarCost << "\nVector: " << VectorCost << '\n');
5672 return ScalarCost > VectorCost;
5673 }
5674
5675 /// \brief Generate a constant vector with \p Val with the same
5676 /// number of elements as the transition.
5677 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005678 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005679 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5680 /// otherwise we generate a vector with as many undef as possible:
5681 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5682 /// used at the index of the extract.
5683 Value *getConstantVector(Constant *Val, bool UseSplat) const {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005684 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00005685 if (!UseSplat) {
5686 // If we cannot determine where the constant must be, we have to
5687 // use a splat constant.
5688 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5689 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5690 ExtractIdx = CstVal->getSExtValue();
5691 else
5692 UseSplat = true;
5693 }
5694
5695 unsigned End = getTransitionType()->getVectorNumElements();
5696 if (UseSplat)
5697 return ConstantVector::getSplat(End, Val);
5698
5699 SmallVector<Constant *, 4> ConstVec;
5700 UndefValue *UndefVal = UndefValue::get(Val->getType());
5701 for (unsigned Idx = 0; Idx != End; ++Idx) {
5702 if (Idx == ExtractIdx)
5703 ConstVec.push_back(Val);
5704 else
5705 ConstVec.push_back(UndefVal);
5706 }
5707 return ConstantVector::get(ConstVec);
5708 }
5709
5710 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5711 /// in \p Use can trigger undefined behavior.
5712 static bool canCauseUndefinedBehavior(const Instruction *Use,
5713 unsigned OperandIdx) {
5714 // This is not safe to introduce undef when the operand is on
5715 // the right hand side of a division-like instruction.
5716 if (OperandIdx != 1)
5717 return false;
5718 switch (Use->getOpcode()) {
5719 default:
5720 return false;
5721 case Instruction::SDiv:
5722 case Instruction::UDiv:
5723 case Instruction::SRem:
5724 case Instruction::URem:
5725 return true;
5726 case Instruction::FDiv:
5727 case Instruction::FRem:
5728 return !Use->hasNoNaNs();
5729 }
5730 llvm_unreachable(nullptr);
5731 }
5732
5733public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005734 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5735 const TargetTransformInfo &TTI, Instruction *Transition,
5736 unsigned CombineCost)
5737 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Eugene Zelenko900b6332017-08-29 22:32:07 +00005738 StoreExtractCombineCost(CombineCost) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005739 assert(Transition && "Do not know how to promote null");
5740 }
5741
5742 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5743 bool canPromote(const Instruction *ToBePromoted) const {
5744 // We could support CastInst too.
5745 return isa<BinaryOperator>(ToBePromoted);
5746 }
5747
5748 /// \brief Check if it is profitable to promote \p ToBePromoted
5749 /// by moving downward the transition through.
5750 bool shouldPromote(const Instruction *ToBePromoted) const {
5751 // Promote only if all the operands can be statically expanded.
5752 // Indeed, we do not want to introduce any new kind of transitions.
5753 for (const Use &U : ToBePromoted->operands()) {
5754 const Value *Val = U.get();
5755 if (Val == getEndOfTransition()) {
5756 // If the use is a division and the transition is on the rhs,
5757 // we cannot promote the operation, otherwise we may create a
5758 // division by zero.
5759 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5760 return false;
5761 continue;
5762 }
5763 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5764 !isa<ConstantFP>(Val))
5765 return false;
5766 }
5767 // Check that the resulting operation is legal.
5768 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5769 if (!ISDOpcode)
5770 return false;
5771 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005772 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005773 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005774 }
5775
5776 /// \brief Check whether or not \p Use can be combined
5777 /// with the transition.
5778 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5779 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5780
5781 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5782 void enqueueForPromotion(Instruction *ToBePromoted) {
5783 InstsToBePromoted.push_back(ToBePromoted);
5784 }
5785
5786 /// \brief Set the instruction that will be combined with the transition.
5787 void recordCombineInstruction(Instruction *ToBeCombined) {
5788 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5789 CombineInst = ToBeCombined;
5790 }
5791
5792 /// \brief Promote all the instructions enqueued for promotion if it is
5793 /// is profitable.
5794 /// \return True if the promotion happened, false otherwise.
5795 bool promote() {
5796 // Check if there is something to promote.
5797 // Right now, if we do not have anything to combine with,
5798 // we assume the promotion is not profitable.
5799 if (InstsToBePromoted.empty() || !CombineInst)
5800 return false;
5801
5802 // Check cost.
5803 if (!StressStoreExtract && !isProfitableToPromote())
5804 return false;
5805
5806 // Promote.
5807 for (auto &ToBePromoted : InstsToBePromoted)
5808 promoteImpl(ToBePromoted);
5809 InstsToBePromoted.clear();
5810 return true;
5811 }
5812};
Eugene Zelenko900b6332017-08-29 22:32:07 +00005813
5814} // end anonymous namespace
Quentin Colombetc32615d2014-10-31 17:52:53 +00005815
5816void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5817 // At this point, we know that all the operands of ToBePromoted but Def
5818 // can be statically promoted.
5819 // For Def, we need to use its parameter in ToBePromoted:
5820 // b = ToBePromoted ty1 a
5821 // Def = Transition ty1 b to ty2
5822 // Move the transition down.
5823 // 1. Replace all uses of the promoted operation by the transition.
5824 // = ... b => = ... Def.
5825 assert(ToBePromoted->getType() == Transition->getType() &&
5826 "The type of the result of the transition does not match "
5827 "the final type");
5828 ToBePromoted->replaceAllUsesWith(Transition);
5829 // 2. Update the type of the uses.
5830 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5831 Type *TransitionTy = getTransitionType();
5832 ToBePromoted->mutateType(TransitionTy);
5833 // 3. Update all the operands of the promoted operation with promoted
5834 // operands.
5835 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5836 for (Use &U : ToBePromoted->operands()) {
5837 Value *Val = U.get();
5838 Value *NewVal = nullptr;
5839 if (Val == Transition)
5840 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5841 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5842 isa<ConstantFP>(Val)) {
5843 // Use a splat constant if it is not safe to use undef.
5844 NewVal = getConstantVector(
5845 cast<Constant>(Val),
5846 isa<UndefValue>(Val) ||
5847 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5848 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005849 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5850 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005851 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5852 }
Sanjay Patel674d2c22017-08-29 14:07:48 +00005853 Transition->moveAfter(ToBePromoted);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005854 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5855}
5856
5857/// Some targets can do store(extractelement) with one instruction.
5858/// Try to push the extractelement towards the stores when the target
5859/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005860bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005861 unsigned CombineCost = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00005862 if (DisableStoreExtract || !TLI ||
5863 (!StressStoreExtract &&
5864 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5865 Inst->getOperand(1), CombineCost)))
5866 return false;
5867
5868 // At this point we know that Inst is a vector to scalar transition.
5869 // Try to move it down the def-use chain, until:
5870 // - We can combine the transition with its single use
5871 // => we got rid of the transition.
5872 // - We escape the current basic block
5873 // => we would need to check that we are moving it at a cheaper place and
5874 // we do not do that for now.
5875 BasicBlock *Parent = Inst->getParent();
5876 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005877 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005878 // If the transition has more than one use, assume this is not going to be
5879 // beneficial.
5880 while (Inst->hasOneUse()) {
5881 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5882 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5883
5884 if (ToBePromoted->getParent() != Parent) {
5885 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5886 << ToBePromoted->getParent()->getName()
5887 << ") than the transition (" << Parent->getName() << ").\n");
5888 return false;
5889 }
5890
5891 if (VPH.canCombine(ToBePromoted)) {
5892 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5893 << "will be combined with: " << *ToBePromoted << '\n');
5894 VPH.recordCombineInstruction(ToBePromoted);
5895 bool Changed = VPH.promote();
5896 NumStoreExtractExposed += Changed;
5897 return Changed;
5898 }
5899
5900 DEBUG(dbgs() << "Try promoting.\n");
5901 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5902 return false;
5903
5904 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5905
5906 VPH.enqueueForPromotion(ToBePromoted);
5907 Inst = ToBePromoted;
5908 }
5909 return false;
5910}
5911
Wei Mia2f0b592016-12-22 19:44:45 +00005912/// For the instruction sequence of store below, F and I values
5913/// are bundled together as an i64 value before being stored into memory.
5914/// Sometimes it is more efficent to generate separate stores for F and I,
5915/// which can remove the bitwise instructions or sink them to colder places.
5916///
5917/// (store (or (zext (bitcast F to i32) to i64),
5918/// (shl (zext I to i64), 32)), addr) -->
5919/// (store F, addr) and (store I, addr+4)
5920///
5921/// Similarly, splitting for other merged store can also be beneficial, like:
5922/// For pair of {i32, i32}, i64 store --> two i32 stores.
5923/// For pair of {i32, i16}, i64 store --> two i32 stores.
5924/// For pair of {i16, i16}, i32 store --> two i16 stores.
5925/// For pair of {i16, i8}, i32 store --> two i16 stores.
5926/// For pair of {i8, i8}, i16 store --> two i8 stores.
5927///
5928/// We allow each target to determine specifically which kind of splitting is
5929/// supported.
5930///
5931/// The store patterns are commonly seen from the simple code snippet below
5932/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
5933/// void goo(const std::pair<int, float> &);
5934/// hoo() {
5935/// ...
5936/// goo(std::make_pair(tmp, ftmp));
5937/// ...
5938/// }
5939///
5940/// Although we already have similar splitting in DAG Combine, we duplicate
5941/// it in CodeGenPrepare to catch the case in which pattern is across
5942/// multiple BBs. The logic in DAG Combine is kept to catch case generated
5943/// during code expansion.
5944static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
5945 const TargetLowering &TLI) {
5946 // Handle simple but common cases only.
5947 Type *StoreType = SI.getValueOperand()->getType();
5948 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
5949 DL.getTypeSizeInBits(StoreType) == 0)
5950 return false;
5951
5952 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
5953 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
5954 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
5955 DL.getTypeSizeInBits(SplitStoreType))
5956 return false;
5957
5958 // Match the following patterns:
5959 // (store (or (zext LValue to i64),
5960 // (shl (zext HValue to i64), 32)), HalfValBitSize)
5961 // or
5962 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
5963 // (zext LValue to i64),
5964 // Expect both operands of OR and the first operand of SHL have only
5965 // one use.
5966 Value *LValue, *HValue;
5967 if (!match(SI.getValueOperand(),
5968 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
5969 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
5970 m_SpecificInt(HalfValBitSize))))))
5971 return false;
5972
5973 // Check LValue and HValue are int with size less or equal than 32.
5974 if (!LValue->getType()->isIntegerTy() ||
5975 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
5976 !HValue->getType()->isIntegerTy() ||
5977 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
5978 return false;
5979
5980 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
5981 // as the input of target query.
5982 auto *LBC = dyn_cast<BitCastInst>(LValue);
5983 auto *HBC = dyn_cast<BitCastInst>(HValue);
5984 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
5985 : EVT::getEVT(LValue->getType());
5986 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
5987 : EVT::getEVT(HValue->getType());
5988 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
5989 return false;
5990
5991 // Start to split store.
5992 IRBuilder<> Builder(SI.getContext());
5993 Builder.SetInsertPoint(&SI);
5994
5995 // If LValue/HValue is a bitcast in another BB, create a new one in current
5996 // BB so it may be merged with the splitted stores by dag combiner.
5997 if (LBC && LBC->getParent() != SI.getParent())
5998 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
5999 if (HBC && HBC->getParent() != SI.getParent())
6000 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6001
6002 auto CreateSplitStore = [&](Value *V, bool Upper) {
6003 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6004 Value *Addr = Builder.CreateBitCast(
6005 SI.getOperand(1),
6006 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
6007 if (Upper)
6008 Addr = Builder.CreateGEP(
6009 SplitStoreType, Addr,
6010 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6011 Builder.CreateAlignedStore(
6012 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6013 };
6014
6015 CreateSplitStore(LValue, false);
6016 CreateSplitStore(HValue, true);
6017
6018 // Delete the old store.
6019 SI.eraseFromParent();
6020 return true;
6021}
6022
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006023// Return true if the GEP has two operands, the first operand is of a sequential
6024// type, and the second operand is a constant.
6025static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6026 gep_type_iterator I = gep_type_begin(*GEP);
6027 return GEP->getNumOperands() == 2 &&
6028 I.isSequential() &&
6029 isa<ConstantInt>(GEP->getOperand(1));
6030}
6031
6032// Try unmerging GEPs to reduce liveness interference (register pressure) across
6033// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6034// reducing liveness interference across those edges benefits global register
6035// allocation. Currently handles only certain cases.
6036//
6037// For example, unmerge %GEPI and %UGEPI as below.
6038//
6039// ---------- BEFORE ----------
6040// SrcBlock:
6041// ...
6042// %GEPIOp = ...
6043// ...
6044// %GEPI = gep %GEPIOp, Idx
6045// ...
6046// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6047// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6048// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6049// %UGEPI)
6050//
6051// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6052// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6053// ...
6054//
6055// DstBi:
6056// ...
6057// %UGEPI = gep %GEPIOp, UIdx
6058// ...
6059// ---------------------------
6060//
6061// ---------- AFTER ----------
6062// SrcBlock:
6063// ... (same as above)
6064// (* %GEPI is still alive on the indirectbr edges)
6065// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6066// unmerging)
6067// ...
6068//
6069// DstBi:
6070// ...
6071// %UGEPI = gep %GEPI, (UIdx-Idx)
6072// ...
6073// ---------------------------
6074//
6075// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6076// no longer alive on them.
6077//
6078// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6079// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6080// not to disable further simplications and optimizations as a result of GEP
6081// merging.
6082//
6083// Note this unmerging may increase the length of the data flow critical path
6084// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6085// between the register pressure and the length of data-flow critical
6086// path. Restricting this to the uncommon IndirectBr case would minimize the
6087// impact of potentially longer critical path, if any, and the impact on compile
6088// time.
6089static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6090 const TargetTransformInfo *TTI) {
6091 BasicBlock *SrcBlock = GEPI->getParent();
6092 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6093 // (non-IndirectBr) cases exit early here.
6094 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6095 return false;
6096 // Check that GEPI is a simple gep with a single constant index.
6097 if (!GEPSequentialConstIndexed(GEPI))
6098 return false;
6099 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6100 // Check that GEPI is a cheap one.
6101 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6102 > TargetTransformInfo::TCC_Basic)
6103 return false;
6104 Value *GEPIOp = GEPI->getOperand(0);
6105 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6106 if (!isa<Instruction>(GEPIOp))
6107 return false;
6108 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6109 if (GEPIOpI->getParent() != SrcBlock)
6110 return false;
6111 // Check that GEP is used outside the block, meaning it's alive on the
6112 // IndirectBr edge(s).
6113 if (find_if(GEPI->users(), [&](User *Usr) {
6114 if (auto *I = dyn_cast<Instruction>(Usr)) {
6115 if (I->getParent() != SrcBlock) {
6116 return true;
6117 }
6118 }
6119 return false;
6120 }) == GEPI->users().end())
6121 return false;
6122 // The second elements of the GEP chains to be unmerged.
6123 std::vector<GetElementPtrInst *> UGEPIs;
6124 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6125 // on IndirectBr edges.
6126 for (User *Usr : GEPIOp->users()) {
6127 if (Usr == GEPI) continue;
6128 // Check if Usr is an Instruction. If not, give up.
6129 if (!isa<Instruction>(Usr))
6130 return false;
6131 auto *UI = cast<Instruction>(Usr);
6132 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6133 if (UI->getParent() == SrcBlock)
6134 continue;
6135 // Check if Usr is a GEP. If not, give up.
6136 if (!isa<GetElementPtrInst>(Usr))
6137 return false;
6138 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6139 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6140 // the pointer operand to it. If so, record it in the vector. If not, give
6141 // up.
6142 if (!GEPSequentialConstIndexed(UGEPI))
6143 return false;
6144 if (UGEPI->getOperand(0) != GEPIOp)
6145 return false;
6146 if (GEPIIdx->getType() !=
6147 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6148 return false;
6149 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6150 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6151 > TargetTransformInfo::TCC_Basic)
6152 return false;
6153 UGEPIs.push_back(UGEPI);
6154 }
6155 if (UGEPIs.size() == 0)
6156 return false;
6157 // Check the materializing cost of (Uidx-Idx).
6158 for (GetElementPtrInst *UGEPI : UGEPIs) {
6159 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6160 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6161 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6162 if (ImmCost > TargetTransformInfo::TCC_Basic)
6163 return false;
6164 }
6165 // Now unmerge between GEPI and UGEPIs.
6166 for (GetElementPtrInst *UGEPI : UGEPIs) {
6167 UGEPI->setOperand(0, GEPI);
6168 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6169 Constant *NewUGEPIIdx =
6170 ConstantInt::get(GEPIIdx->getType(),
6171 UGEPIIdx->getValue() - GEPIIdx->getValue());
6172 UGEPI->setOperand(1, NewUGEPIIdx);
6173 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6174 // inbounds to avoid UB.
6175 if (!GEPI->isInBounds()) {
6176 UGEPI->setIsInBounds(false);
6177 }
6178 }
6179 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6180 // alive on IndirectBr edges).
6181 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6182 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6183 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6184 return true;
6185}
6186
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006187bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00006188 // Bail out if we inserted the instruction to prevent optimizations from
6189 // stepping on each other's toes.
6190 if (InsertedInsts.count(I))
6191 return false;
6192
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006193 if (PHINode *P = dyn_cast<PHINode>(I)) {
6194 // It is possible for very late stage optimizations (such as SimplifyCFG)
6195 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6196 // trivial PHI, go ahead and zap it here.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00006197 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006198 P->replaceAllUsesWith(V);
6199 P->eraseFromParent();
6200 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00006201 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006202 }
Chris Lattneree588de2011-01-15 07:29:01 +00006203 return false;
6204 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006205
Chris Lattneree588de2011-01-15 07:29:01 +00006206 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006207 // If the source of the cast is a constant, then this should have
6208 // already been constant folded. The only reason NOT to constant fold
6209 // it is if something (e.g. LSR) was careful to place the constant
6210 // evaluation in a block other than then one that uses it (e.g. to hoist
6211 // the address of globals out of a loop). If this is the case, we don't
6212 // want to forward-subst the cast.
6213 if (isa<Constant>(CI->getOperand(0)))
6214 return false;
6215
Mehdi Amini44ede332015-07-09 02:09:04 +00006216 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00006217 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006218
Chris Lattneree588de2011-01-15 07:29:01 +00006219 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006220 /// Sink a zext or sext into its user blocks if the target type doesn't
6221 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00006222 if (TLI &&
6223 TLI->getTypeAction(CI->getContext(),
6224 TLI->getValueType(*DL, CI->getType())) ==
6225 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006226 return SinkCast(CI);
6227 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00006228 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00006229 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006230 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006231 }
Chris Lattneree588de2011-01-15 07:29:01 +00006232 return false;
6233 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006234
Chris Lattneree588de2011-01-15 07:29:01 +00006235 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00006236 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00006237 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00006238
Chris Lattneree588de2011-01-15 07:29:01 +00006239 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006240 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006241 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006242 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006243 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006244 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6245 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006246 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006247 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006248 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006249
Chris Lattneree588de2011-01-15 07:29:01 +00006250 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006251 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6252 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006253 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006254 if (TLI) {
6255 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006256 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006257 SI->getOperand(0)->getType(), AS);
6258 }
Chris Lattneree588de2011-01-15 07:29:01 +00006259 return false;
6260 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006261
Matt Arsenault02d915b2017-03-15 22:35:20 +00006262 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6263 unsigned AS = RMW->getPointerAddressSpace();
6264 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6265 RMW->getType(), AS);
6266 }
6267
6268 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6269 unsigned AS = CmpX->getPointerAddressSpace();
6270 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6271 CmpX->getCompareOperand()->getType(), AS);
6272 }
6273
Yi Jiangd069f632014-04-21 19:34:27 +00006274 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6275
Geoff Berry5d534b62017-02-21 18:53:14 +00006276 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6277 EnableAndCmpSinking && TLI)
6278 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6279
Yi Jiangd069f632014-04-21 19:34:27 +00006280 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6281 BinOp->getOpcode() == Instruction::LShr)) {
6282 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6283 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006284 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006285
6286 return false;
6287 }
6288
Chris Lattneree588de2011-01-15 07:29:01 +00006289 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006290 if (GEPI->hasAllZeroIndices()) {
6291 /// The GEP operand must be a pointer, so must its result -> BitCast
6292 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6293 GEPI->getName(), GEPI);
6294 GEPI->replaceAllUsesWith(NC);
6295 GEPI->eraseFromParent();
6296 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00006297 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00006298 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006299 }
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006300 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
6301 return true;
6302 }
Chris Lattneree588de2011-01-15 07:29:01 +00006303 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006304 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006305
Chris Lattneree588de2011-01-15 07:29:01 +00006306 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006307 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006308
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006309 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006310 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006311
Tim Northoveraeb8e062014-02-19 10:02:43 +00006312 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006313 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006314
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006315 if (auto *Switch = dyn_cast<SwitchInst>(I))
6316 return optimizeSwitchInst(Switch);
6317
Quentin Colombetc32615d2014-10-31 17:52:53 +00006318 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006319 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006320
Chris Lattneree588de2011-01-15 07:29:01 +00006321 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006322}
6323
James Molloyf01488e2016-01-15 09:20:19 +00006324/// Given an OR instruction, check to see if this is a bitreverse
6325/// idiom. If so, insert the new intrinsic and return true.
6326static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6327 const TargetLowering &TLI) {
6328 if (!I.getType()->isIntegerTy() ||
6329 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6330 TLI.getValueType(DL, I.getType(), true)))
6331 return false;
6332
6333 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00006334 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00006335 return false;
6336 Instruction *LastInst = Insts.back();
6337 I.replaceAllUsesWith(LastInst);
6338 RecursivelyDeleteTriviallyDeadInstructions(&I);
6339 return true;
6340}
6341
Chris Lattnerf2836d12007-03-31 04:06:36 +00006342// In this pass we look for GEP and cast instructions that are used
6343// across basic blocks and rewrite them to improve basic-block-at-a-time
6344// selection.
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006345bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00006346 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00006347 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00006348
Chris Lattner7a277142011-01-15 07:14:54 +00006349 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006350 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006351 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006352 if (ModifiedDT)
6353 return true;
6354 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00006355
James Molloyf01488e2016-01-15 09:20:19 +00006356 bool MadeBitReverse = true;
6357 while (TLI && MadeBitReverse) {
6358 MadeBitReverse = false;
6359 for (auto &I : reverse(BB)) {
6360 if (makeBitReverse(I, *DL, *TLI)) {
6361 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00006362 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00006363 break;
6364 }
6365 }
6366 }
James Molloy3ef84c42016-01-15 10:36:01 +00006367 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00006368
Chris Lattnerf2836d12007-03-31 04:06:36 +00006369 return MadeChange;
6370}
Devang Patel53771ba2011-08-18 00:50:51 +00006371
6372// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00006373// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00006374// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006375bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00006376 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006377 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00006378 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006379 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006380 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00006381 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00006382 // Leave dbg.values that refer to an alloca alone. These
Craig Topper87e715f2017-11-07 20:56:17 +00006383 // intrinsics describe the address of a variable (= the alloca)
Adrian Prantl32da8892014-04-25 20:49:25 +00006384 // being taken. They should not be moved next to the alloca
6385 // (and to the beginning of the scope), but rather stay close to
6386 // where said address is used.
6387 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00006388 PrevNonDbgInst = Insn;
6389 continue;
6390 }
6391
6392 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6393 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00006394 // If VI is a phi in a block with an EHPad terminator, we can't insert
6395 // after it.
6396 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6397 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00006398 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
6399 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00006400 if (isa<PHINode>(VI))
6401 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6402 else
6403 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006404 MadeChange = true;
6405 ++NumDbgValueMoved;
6406 }
6407 }
6408 }
6409 return MadeChange;
6410}
Tim Northovercea0abb2014-03-29 08:22:29 +00006411
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006412/// \brief Scale down both weights to fit into uint32_t.
6413static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6414 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006415 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006416 NewTrue = NewTrue / Scale;
6417 NewFalse = NewFalse / Scale;
6418}
6419
6420/// \brief Some targets prefer to split a conditional branch like:
6421/// \code
6422/// %0 = icmp ne i32 %a, 0
6423/// %1 = icmp ne i32 %b, 0
6424/// %or.cond = or i1 %0, %1
6425/// br i1 %or.cond, label %TrueBB, label %FalseBB
6426/// \endcode
6427/// into multiple branch instructions like:
6428/// \code
6429/// bb1:
6430/// %0 = icmp ne i32 %a, 0
6431/// br i1 %0, label %TrueBB, label %bb2
6432/// bb2:
6433/// %1 = icmp ne i32 %b, 0
6434/// br i1 %1, label %TrueBB, label %FalseBB
6435/// \endcode
6436/// This usually allows instruction selection to do even further optimizations
6437/// and combine the compare with the branch instruction. Currently this is
6438/// applied for targets which have "cheap" jump instructions.
6439///
6440/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6441///
6442bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006443 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006444 return false;
6445
6446 bool MadeChange = false;
6447 for (auto &BB : F) {
6448 // Does this BB end with the following?
6449 // %cond1 = icmp|fcmp|binary instruction ...
6450 // %cond2 = icmp|fcmp|binary instruction ...
6451 // %cond.or = or|and i1 %cond1, cond2
6452 // br i1 %cond.or label %dest1, label %dest2"
6453 BinaryOperator *LogicOp;
6454 BasicBlock *TBB, *FBB;
6455 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6456 continue;
6457
Sanjay Patel42574202015-09-02 19:23:23 +00006458 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6459 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6460 continue;
6461
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006462 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006463 Value *Cond1, *Cond2;
6464 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6465 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006466 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006467 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6468 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006469 Opc = Instruction::Or;
6470 else
6471 continue;
6472
6473 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6474 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6475 continue;
6476
6477 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6478
6479 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00006480 auto TmpBB =
6481 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6482 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006483
6484 // Update original basic block by using the first condition directly by the
6485 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006486 Br1->setCondition(Cond1);
6487 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006488
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006489 // Depending on the conditon we have to either replace the true or the false
6490 // successor of the original branch instruction.
6491 if (Opc == Instruction::And)
6492 Br1->setSuccessor(0, TmpBB);
6493 else
6494 Br1->setSuccessor(1, TmpBB);
6495
6496 // Fill in the new basic block.
6497 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006498 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6499 I->removeFromParent();
6500 I->insertBefore(Br2);
6501 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006502
6503 // Update PHI nodes in both successors. The original BB needs to be
Hiroshi Inoue6a391bb2017-06-27 10:35:37 +00006504 // replaced in one successor's PHI nodes, because the branch comes now from
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006505 // the newly generated BB (NewBB). In the other successor we need to add one
6506 // incoming edge to the PHI nodes, because both branch instructions target
6507 // now the same successor. Depending on the original branch condition
6508 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006509 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006510 // This doesn't change the successor order of the just created branch
6511 // instruction (or any other instruction).
6512 if (Opc == Instruction::Or)
6513 std::swap(TBB, FBB);
6514
6515 // Replace the old BB with the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006516 for (PHINode &PN : TBB->phis()) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006517 int i;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006518 while ((i = PN.getBasicBlockIndex(&BB)) >= 0)
6519 PN.setIncomingBlock(i, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006520 }
6521
6522 // Add another incoming edge form the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006523 for (PHINode &PN : FBB->phis()) {
6524 auto *Val = PN.getIncomingValueForBlock(&BB);
6525 PN.addIncoming(Val, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006526 }
6527
6528 // Update the branch weights (from SelectionDAGBuilder::
6529 // FindMergedConditions).
6530 if (Opc == Instruction::Or) {
6531 // Codegen X | Y as:
6532 // BB1:
6533 // jmp_if_X TBB
6534 // jmp TmpBB
6535 // TmpBB:
6536 // jmp_if_Y TBB
6537 // jmp FBB
6538 //
6539
6540 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6541 // The requirement is that
6542 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6543 // = TrueProb for orignal BB.
6544 // Assuming the orignal weights are A and B, one choice is to set BB1's
6545 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6546 // assumes that
6547 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6548 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6549 // TmpBB, but the math is more complicated.
6550 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006551 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006552 uint64_t NewTrueWeight = TrueWeight;
6553 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6554 scaleWeights(NewTrueWeight, NewFalseWeight);
6555 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6556 .createBranchWeights(TrueWeight, FalseWeight));
6557
6558 NewTrueWeight = TrueWeight;
6559 NewFalseWeight = 2 * FalseWeight;
6560 scaleWeights(NewTrueWeight, NewFalseWeight);
6561 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6562 .createBranchWeights(TrueWeight, FalseWeight));
6563 }
6564 } else {
6565 // Codegen X & Y as:
6566 // BB1:
6567 // jmp_if_X TmpBB
6568 // jmp FBB
6569 // TmpBB:
6570 // jmp_if_Y TBB
6571 // jmp FBB
6572 //
6573 // This requires creation of TmpBB after CurBB.
6574
6575 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6576 // The requirement is that
6577 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6578 // = FalseProb for orignal BB.
6579 // Assuming the orignal weights are A and B, one choice is to set BB1's
6580 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6581 // assumes that
6582 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6583 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006584 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006585 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6586 uint64_t NewFalseWeight = FalseWeight;
6587 scaleWeights(NewTrueWeight, NewFalseWeight);
6588 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6589 .createBranchWeights(TrueWeight, FalseWeight));
6590
6591 NewTrueWeight = 2 * TrueWeight;
6592 NewFalseWeight = FalseWeight;
6593 scaleWeights(NewTrueWeight, NewFalseWeight);
6594 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6595 .createBranchWeights(TrueWeight, FalseWeight));
6596 }
6597 }
6598
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006599 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00006600 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006601 ModifiedDT = true;
6602
6603 MadeChange = true;
6604
6605 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6606 TmpBB->dump());
6607 }
6608 return MadeChange;
6609}