blob: cacabba5f2676dc8c11698cf25b0b9c5e5285e0a [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"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000021#include "llvm/ADT/SetVector.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000022#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/ADT/Statistic.h"
Jun Bum Lim90b6b502016-12-16 20:38:39 +000025#include "llvm/Analysis/BlockFrequencyInfo.h"
26#include "llvm/Analysis/BranchProbabilityInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000027#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000029#include "llvm/Analysis/LoopInfo.h"
Zaara Syeda3a7578c2017-05-31 17:12:38 +000030#include "llvm/Analysis/MemoryBuiltins.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000031#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000032#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000033#include "llvm/Analysis/TargetTransformInfo.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000034#include "llvm/Analysis/ValueTracking.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000035#include "llvm/CodeGen/Analysis.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000036#include "llvm/CodeGen/ISDOpcodes.h"
37#include "llvm/CodeGen/MachineValueType.h"
38#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000039#include "llvm/CodeGen/TargetLowering.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000040#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000041#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000042#include "llvm/CodeGen/ValueTypes.h"
43#include "llvm/IR/Argument.h"
44#include "llvm/IR/Attributes.h"
45#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000046#include "llvm/IR/CallSite.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000047#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000051#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000053#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000054#include "llvm/IR/GlobalValue.h"
55#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/IRBuilder.h"
57#include "llvm/IR/InlineAsm.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000058#include "llvm/IR/InstrTypes.h"
59#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000060#include "llvm/IR/Instructions.h"
61#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000062#include "llvm/IR/Intrinsics.h"
63#include "llvm/IR/LLVMContext.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000064#include "llvm/IR/MDBuilder.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000065#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000067#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000068#include "llvm/IR/Statepoint.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000069#include "llvm/IR/Type.h"
70#include "llvm/IR/Use.h"
71#include "llvm/IR/User.h"
72#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000073#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000074#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000075#include "llvm/Pass.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000076#include "llvm/Support/BlockFrequency.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000077#include "llvm/Support/BranchProbability.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000078#include "llvm/Support/Casting.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000079#include "llvm/Support/CommandLine.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000080#include "llvm/Support/Compiler.h"
Evan Chengd3d80172007-12-05 23:58:20 +000081#include "llvm/Support/Debug.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000082#include "llvm/Support/ErrorHandling.h"
83#include "llvm/Support/MathExtras.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000084#include "llvm/Support/raw_ostream.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000085#include "llvm/Target/TargetMachine.h"
86#include "llvm/Target/TargetOptions.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000087#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000088#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000089#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000090#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000091#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000092#include "llvm/Transforms/Utils/ValueMapper.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000093#include <algorithm>
94#include <cassert>
95#include <cstdint>
96#include <iterator>
97#include <limits>
98#include <memory>
99#include <utility>
100#include <vector>
Zaara Syeda3a7578c2017-05-31 17:12:38 +0000101
Chris Lattnerf2836d12007-03-31 04:06:36 +0000102using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +0000103using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000104
Chandler Carruth1b9dde02014-04-22 02:02:50 +0000105#define DEBUG_TYPE "codegenprepare"
106
Cameron Zwarichced753f2011-01-05 17:27:27 +0000107STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +0000108STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
109STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +0000110STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
111 "sunken Cmps");
112STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
113 "of sunken Casts");
114STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
115 "computations were sunk");
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000116STATISTIC(NumMemoryInstsPhiCreated,
117 "Number of phis created when address "
118 "computations were sunk to memory instructions");
119STATISTIC(NumMemoryInstsSelectCreated,
120 "Number of select created when address "
121 "computations were sunk to memory instructions");
Evan Cheng0663f232011-03-21 01:19:09 +0000122STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
123STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +0000124STATISTIC(NumAndsAdded,
125 "Number of and mask instructions added to form ext loads");
126STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +0000127STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +0000128STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000129STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +0000130STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +0000131
Cameron Zwarich338d3622011-03-11 21:52:04 +0000132static cl::opt<bool> DisableBranchOpts(
133 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
134 cl::desc("Disable branch optimizations in CodeGenPrepare"));
135
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000136static cl::opt<bool>
137 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
138 cl::desc("Disable GC optimizations in CodeGenPrepare"));
139
Benjamin Kramer3d38c172012-05-06 14:25:16 +0000140static cl::opt<bool> DisableSelectToBranch(
141 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
142 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000143
Hal Finkelc3998302014-04-12 00:59:48 +0000144static cl::opt<bool> AddrSinkUsingGEPs(
Eli Friedman5fba1e52017-04-06 22:42:18 +0000145 "addr-sink-using-gep", cl::Hidden, cl::init(true),
Hal Finkelc3998302014-04-12 00:59:48 +0000146 cl::desc("Address sinking in CGP using GEPs."));
147
Tim Northovercea0abb2014-03-29 08:22:29 +0000148static cl::opt<bool> EnableAndCmpSinking(
149 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
150 cl::desc("Enable sinkinig and/cmp into branches."));
151
Quentin Colombetc32615d2014-10-31 17:52:53 +0000152static cl::opt<bool> DisableStoreExtract(
153 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
154 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
155
156static cl::opt<bool> StressStoreExtract(
157 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
158 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
159
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000160static cl::opt<bool> DisableExtLdPromotion(
161 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
162 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
163 "CodeGenPrepare"));
164
165static cl::opt<bool> StressExtLdPromotion(
166 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
167 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
168 "optimization in CodeGenPrepare"));
169
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000170static cl::opt<bool> DisablePreheaderProtect(
171 "disable-preheader-prot", cl::Hidden, cl::init(false),
172 cl::desc("Disable protection against removing loop preheaders"));
173
Dehao Chen302b69c2016-10-18 20:42:47 +0000174static cl::opt<bool> ProfileGuidedSectionPrefix(
David Callahan5960d9b12017-06-14 20:35:33 +0000175 "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
Dehao Chen302b69c2016-10-18 20:42:47 +0000176 cl::desc("Use profile info to add section prefix for hot/cold functions"));
177
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000178static cl::opt<unsigned> FreqRatioToSkipMerge(
179 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
180 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
181 "(frequency of destination block) is greater than this ratio"));
182
Wei Mia2f0b592016-12-22 19:44:45 +0000183static cl::opt<bool> ForceSplitStore(
184 "force-split-store", cl::Hidden, cl::init(false),
185 cl::desc("Force store splitting no matter what the target query says."));
186
Jun Bum Limdee55652017-04-03 19:20:07 +0000187static cl::opt<bool>
188EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
189 cl::desc("Enable merging of redundant sexts when one is dominating"
190 " the other."), cl::init(true));
191
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000192static cl::opt<bool> DisableComplexAddrModes(
Serguei Katkovac17aad2017-11-21 06:03:43 +0000193 "disable-complex-addr-modes", cl::Hidden, cl::init(true),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000194 cl::desc("Disables combining addressing modes with different parts "
195 "in optimizeMemoryInst."));
196
197static cl::opt<bool>
198AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
199 cl::desc("Allow creation of Phis in Address sinking."));
200
201static cl::opt<bool>
Serguei Katkov36520022017-11-07 09:43:08 +0000202AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(false),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000203 cl::desc("Allow creation of selects in Address sinking."));
204
John Brawn70cdb5b2017-11-24 14:10:45 +0000205static cl::opt<bool> AddrSinkCombineBaseReg(
206 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
207 cl::desc("Allow combining of BaseReg field in Address sinking."));
208
209static cl::opt<bool> AddrSinkCombineBaseGV(
210 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
211 cl::desc("Allow combining of BaseGV field in Address sinking."));
212
213static cl::opt<bool> AddrSinkCombineBaseOffs(
214 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
215 cl::desc("Allow combining of BaseOffs field in Address sinking."));
216
217static cl::opt<bool> AddrSinkCombineScaledReg(
218 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
219 cl::desc("Allow combining of ScaledReg field in Address sinking."));
220
Eric Christopherc1ea1492008-09-24 05:32:41 +0000221namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000222
223using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
224using TypeIsSExt = PointerIntPair<Type *, 1, bool>;
225using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
226using SExts = SmallVector<Instruction *, 16>;
227using ValueToSExts = DenseMap<Value *, SExts>;
228
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000229class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000230
Chris Lattner2dd09db2009-09-02 06:11:42 +0000231 class CodeGenPrepare : public FunctionPass {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000232 const TargetMachine *TM = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000233 const TargetSubtargetInfo *SubtargetInfo;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000234 const TargetLowering *TLI = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000235 const TargetRegisterInfo *TRI;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000236 const TargetTransformInfo *TTI = nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000237 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000238 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000239 std::unique_ptr<BlockFrequencyInfo> BFI;
240 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000241
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000242 /// As we scan instructions optimizing them, this is the next instruction
243 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000244 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000245
Evan Cheng0663f232011-03-21 01:19:09 +0000246 /// Keeps track of non-local addresses that have been sunk into a block.
247 /// This allows us to avoid inserting duplicate code for blocks with
248 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000249 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000250
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000251 /// Keeps track of all instructions inserted for the current function.
252 SetOfInstrs InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000253
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000254 /// Keeps track of the type of the related instruction before their
255 /// promotion for the current function.
256 InstrToOrigTy PromotedInsts;
257
Jun Bum Limdee55652017-04-03 19:20:07 +0000258 /// Keep track of instructions removed during promotion.
259 SetOfInstrs RemovedInsts;
260
261 /// Keep track of sext chains based on their initial value.
262 DenseMap<Value *, Instruction *> SeenChainsForSExt;
263
264 /// Keep track of SExt promoted.
265 ValueToSExts ValToSExtendedUses;
266
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000267 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000268 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000269
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000270 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000271 bool OptSize;
272
Mehdi Amini4fe37982015-07-07 18:45:17 +0000273 /// DataLayout for the Function being processed.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000274 const DataLayout *DL = nullptr;
Mehdi Amini4fe37982015-07-07 18:45:17 +0000275
Chris Lattnerf2836d12007-03-31 04:06:36 +0000276 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000277 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000278
279 CodeGenPrepare() : FunctionPass(ID) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000280 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
281 }
Eugene Zelenko900b6332017-08-29 22:32:07 +0000282
Craig Topper4584cd52014-03-07 09:26:03 +0000283 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000284
Mehdi Amini117296c2016-10-01 02:56:57 +0000285 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000286
Craig Topper4584cd52014-03-07 09:26:03 +0000287 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000288 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000289 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000290 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000291 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000292 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000293 }
294
Chris Lattnerf2836d12007-03-31 04:06:36 +0000295 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000296 bool eliminateFallThrough(Function &F);
297 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000298 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000299 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
300 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000301 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
302 bool isPreheader);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000303 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
304 bool optimizeInst(Instruction *I, bool &ModifiedDT);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000305 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000306 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000307 bool optimizeInlineAsmInst(CallInst *CS);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000308 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000309 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000310 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000311 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000312 bool optimizeSelectInst(SelectInst *SI);
313 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000314 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000315 bool optimizeExtractElementInst(Instruction *Inst);
316 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
317 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000318 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
319 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
320 bool tryToPromoteExts(TypePromotionTransaction &TPT,
321 const SmallVectorImpl<Instruction *> &Exts,
322 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
323 unsigned CreatedInstsCost = 0);
Jun Bum Limdee55652017-04-03 19:20:07 +0000324 bool mergeSExts(Function &F);
325 bool performAddressTypePromotion(
326 Instruction *&Inst,
327 bool AllowPromotionWithoutCommonHeader,
328 bool HasPromoted, TypePromotionTransaction &TPT,
329 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000330 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000331 bool simplifyOffsetableRelocate(Instruction &I);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000332 bool splitIndirectCriticalEdges(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000333 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000334
335} // end anonymous namespace
Devang Patel09f162c2007-05-01 21:15:47 +0000336
Devang Patel8c78a0b2007-05-03 01:11:54 +0000337char CodeGenPrepare::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000338
Matthias Braun1527baa2017-05-25 21:26:32 +0000339INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000340 "Optimize for code generation", false, false)
Dehao Chen302b69c2016-10-18 20:42:47 +0000341INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000342INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000343 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000344
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000345FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000346
Chris Lattnerf2836d12007-03-31 04:06:36 +0000347bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000348 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000349 return false;
350
Mehdi Amini4fe37982015-07-07 18:45:17 +0000351 DL = &F.getParent()->getDataLayout();
352
Chris Lattnerf2836d12007-03-31 04:06:36 +0000353 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000354 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000355 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000356 PromotedInsts.clear();
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000357 BFI.reset();
358 BPI.reset();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000359
Devang Patel8f606d72011-03-24 15:35:25 +0000360 ModifiedDT = false;
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000361 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
362 TM = &TPC->getTM<TargetMachine>();
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000363 SubtargetInfo = TM->getSubtargetImpl(F);
364 TLI = SubtargetInfo->getTargetLowering();
365 TRI = SubtargetInfo->getRegisterInfo();
366 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000367 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000368 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000369 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000370 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000371
Easwaran Raman0d55b552017-11-14 19:31:51 +0000372 ProfileSummaryInfo *PSI =
373 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen302b69c2016-10-18 20:42:47 +0000374 if (ProfileGuidedSectionPrefix) {
Dehao Chen775341a2017-03-23 23:14:11 +0000375 if (PSI->isFunctionHotInCallGraph(&F))
Dehao Chen302b69c2016-10-18 20:42:47 +0000376 F.setSectionPrefix(".hot");
Dehao Chen775341a2017-03-23 23:14:11 +0000377 else if (PSI->isFunctionColdInCallGraph(&F))
Teresa Johnson720d9b42017-05-09 01:43:24 +0000378 F.setSectionPrefix(".unlikely");
Dehao Chen302b69c2016-10-18 20:42:47 +0000379 }
380
Preston Gurdcdf540d2012-09-04 18:22:17 +0000381 /// This optimization identifies DIV instructions that can be
382 /// profitably bypassed and carried out with a shorter, faster divide.
Easwaran Raman0d55b552017-11-14 19:31:51 +0000383 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
384 TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000385 const DenseMap<unsigned int, unsigned int> &BypassWidths =
386 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000387 BasicBlock* BB = &*F.begin();
388 while (BB != nullptr) {
389 // bypassSlowDivision may create new BBs, but we don't want to reapply the
390 // optimization to those blocks.
391 BasicBlock* Next = BB->getNextNode();
392 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
393 BB = Next;
394 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000395 }
396
397 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000398 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000399 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000400
Devang Patel53771ba2011-08-18 00:50:51 +0000401 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000402 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000403 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000404 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000405
Geoff Berry5d534b62017-02-21 18:53:14 +0000406 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000407 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000408
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000409 // Split some critical edges where one of the sources is an indirect branch,
410 // to help generate sane code for PHIs involving such edges.
411 EverMadeChange |= splitIndirectCriticalEdges(F);
412
Chris Lattnerc3748562007-04-02 01:35:34 +0000413 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000414 while (MadeChange) {
415 MadeChange = false;
Jun Bum Limdee55652017-04-03 19:20:07 +0000416 SeenChainsForSExt.clear();
417 ValToSExtendedUses.clear();
418 RemovedInsts.clear();
Hans Wennborg02fbc712012-09-19 07:48:16 +0000419 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000420 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000421 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000422 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000423
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000424 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000425 if (ModifiedDTOnIteration)
426 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000427 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000428 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
429 MadeChange |= mergeSExts(F);
430
431 // Really free removed instructions during promotion.
432 for (Instruction *I : RemovedInsts)
Reid Kleckner96ab8722017-05-18 17:24:10 +0000433 I->deleteValue();
Jun Bum Limdee55652017-04-03 19:20:07 +0000434
Chris Lattnerf2836d12007-03-31 04:06:36 +0000435 EverMadeChange |= MadeChange;
436 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000437
438 SunkAddrs.clear();
439
Cameron Zwarich338d3622011-03-11 21:52:04 +0000440 if (!DisableBranchOpts) {
441 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000442 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000443 for (BasicBlock &BB : F) {
444 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
445 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000446 if (!MadeChange) continue;
447
448 for (SmallVectorImpl<BasicBlock*>::iterator
449 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
450 if (pred_begin(*II) == pred_end(*II))
451 WorkList.insert(*II);
452 }
453
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000454 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000455 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000456 while (!WorkList.empty()) {
457 BasicBlock *BB = *WorkList.begin();
458 WorkList.erase(BB);
459 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
460
461 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000462
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000463 for (SmallVectorImpl<BasicBlock*>::iterator
464 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
465 if (pred_begin(*II) == pred_end(*II))
466 WorkList.insert(*II);
467 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000468
Nadav Rotem70409992012-08-14 05:19:07 +0000469 // Merge pairs of basic blocks with unconditional branches, connected by
470 // a single edge.
471 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000472 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000473
Cameron Zwarich338d3622011-03-11 21:52:04 +0000474 EverMadeChange |= MadeChange;
475 }
476
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000477 if (!DisableGCOpts) {
478 SmallVector<Instruction *, 2> Statepoints;
479 for (BasicBlock &BB : F)
480 for (Instruction &I : BB)
481 if (isStatepoint(I))
482 Statepoints.push_back(&I);
483 for (auto &I : Statepoints)
484 EverMadeChange |= simplifyOffsetableRelocate(*I);
485 }
486
Chris Lattnerf2836d12007-03-31 04:06:36 +0000487 return EverMadeChange;
488}
489
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000490/// Merge basic blocks which are connected by a single edge, where one of the
491/// basic blocks has a single successor pointing to the other basic block,
492/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000493bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000494 bool Changed = false;
495 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000496 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000497 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000498 // If the destination block has a single pred, then this is a trivial
499 // edge, just collapse it.
500 BasicBlock *SinglePred = BB->getSinglePredecessor();
501
Evan Cheng64a223a2012-09-28 23:58:57 +0000502 // Don't merge if BB's address is taken.
503 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000504
505 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
506 if (Term && !Term->isConditional()) {
507 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000508 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000509 // Remember if SinglePred was the entry block of the function.
510 // If so, we will need to move BB back to the entry position.
511 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000512 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000513
514 if (isEntry && BB != &BB->getParent()->getEntryBlock())
515 BB->moveBefore(&BB->getParent()->getEntryBlock());
516
517 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000518 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000519 }
520 }
521 return Changed;
522}
523
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000524/// Find a destination block from BB if BB is mergeable empty block.
525BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
526 // If this block doesn't end with an uncond branch, ignore it.
527 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
528 if (!BI || !BI->isUnconditional())
529 return nullptr;
530
531 // If the instruction before the branch (skipping debug info) isn't a phi
532 // node, then other stuff is happening here.
533 BasicBlock::iterator BBI = BI->getIterator();
534 if (BBI != BB->begin()) {
535 --BBI;
536 while (isa<DbgInfoIntrinsic>(BBI)) {
537 if (BBI == BB->begin())
538 break;
539 --BBI;
540 }
541 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
542 return nullptr;
543 }
544
545 // Do not break infinite loops.
546 BasicBlock *DestBB = BI->getSuccessor(0);
547 if (DestBB == BB)
548 return nullptr;
549
550 if (!canMergeBlocks(BB, DestBB))
551 DestBB = nullptr;
552
553 return DestBB;
554}
555
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000556// Return the unique indirectbr predecessor of a block. This may return null
557// even if such a predecessor exists, if it's not useful for splitting.
558// If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
559// predecessors of BB.
560static BasicBlock *
561findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
562 // If the block doesn't have any PHIs, we don't care about it, since there's
563 // no point in splitting it.
564 PHINode *PN = dyn_cast<PHINode>(BB->begin());
565 if (!PN)
566 return nullptr;
567
568 // Verify we have exactly one IBR predecessor.
569 // Conservatively bail out if one of the other predecessors is not a "regular"
570 // terminator (that is, not a switch or a br).
571 BasicBlock *IBB = nullptr;
572 for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
573 BasicBlock *PredBB = PN->getIncomingBlock(Pred);
574 TerminatorInst *PredTerm = PredBB->getTerminator();
575 switch (PredTerm->getOpcode()) {
576 case Instruction::IndirectBr:
577 if (IBB)
578 return nullptr;
579 IBB = PredBB;
580 break;
581 case Instruction::Br:
582 case Instruction::Switch:
583 OtherPreds.push_back(PredBB);
584 continue;
585 default:
586 return nullptr;
587 }
588 }
589
590 return IBB;
591}
592
593// Split critical edges where the source of the edge is an indirectbr
594// instruction. This isn't always possible, but we can handle some easy cases.
595// This is useful because MI is unable to split such critical edges,
596// which means it will not be able to sink instructions along those edges.
597// This is especially painful for indirect branches with many successors, where
598// we end up having to prepare all outgoing values in the origin block.
599//
600// Our normal algorithm for splitting critical edges requires us to update
601// the outgoing edges of the edge origin block, but for an indirectbr this
602// is hard, since it would require finding and updating the block addresses
603// the indirect branch uses. But if a block only has a single indirectbr
604// predecessor, with the others being regular branches, we can do it in a
605// different way.
606// Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
607// We can split D into D0 and D1, where D0 contains only the PHIs from D,
608// and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
609// create the following structure:
610// A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
611bool CodeGenPrepare::splitIndirectCriticalEdges(Function &F) {
612 // Check whether the function has any indirectbrs, and collect which blocks
613 // they may jump to. Since most functions don't have indirect branches,
614 // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
615 SmallSetVector<BasicBlock *, 16> Targets;
616 for (auto &BB : F) {
617 auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
618 if (!IBI)
619 continue;
620
621 for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
622 Targets.insert(IBI->getSuccessor(Succ));
623 }
624
625 if (Targets.empty())
626 return false;
627
628 bool Changed = false;
629 for (BasicBlock *Target : Targets) {
630 SmallVector<BasicBlock *, 16> OtherPreds;
631 BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
632 // If we did not found an indirectbr, or the indirectbr is the only
633 // incoming edge, this isn't the kind of edge we're looking for.
634 if (!IBRPred || OtherPreds.empty())
635 continue;
636
637 // Don't even think about ehpads/landingpads.
638 Instruction *FirstNonPHI = Target->getFirstNonPHI();
639 if (FirstNonPHI->isEHPad() || Target->isLandingPad())
640 continue;
641
642 BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
643 // It's possible Target was its own successor through an indirectbr.
644 // In this case, the indirectbr now comes from BodyBlock.
645 if (IBRPred == Target)
646 IBRPred = BodyBlock;
647
648 // At this point Target only has PHIs, and BodyBlock has the rest of the
649 // block's body. Create a copy of Target that will be used by the "direct"
650 // preds.
651 ValueToValueMapTy VMap;
652 BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
653
Brendon Cahoon7769a082017-04-17 19:11:04 +0000654 for (BasicBlock *Pred : OtherPreds) {
655 // If the target is a loop to itself, then the terminator of the split
656 // block needs to be updated.
657 if (Pred == Target)
658 BodyBlock->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
659 else
660 Pred->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
661 }
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000662
663 // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
664 // they are clones, so the number of PHIs are the same.
665 // (a) Remove the edge coming from IBRPred from the "Direct" PHI
666 // (b) Leave that as the only edge in the "Indirect" PHI.
667 // (c) Merge the two in the body block.
668 BasicBlock::iterator Indirect = Target->begin(),
669 End = Target->getFirstNonPHI()->getIterator();
670 BasicBlock::iterator Direct = DirectSucc->begin();
671 BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
672
673 assert(&*End == Target->getTerminator() &&
674 "Block was expected to only contain PHIs");
675
676 while (Indirect != End) {
677 PHINode *DirPHI = cast<PHINode>(Direct);
678 PHINode *IndPHI = cast<PHINode>(Indirect);
679
680 // Now, clean up - the direct block shouldn't get the indirect value,
681 // and vice versa.
682 DirPHI->removeIncomingValue(IBRPred);
683 Direct++;
684
685 // Advance the pointer here, to avoid invalidation issues when the old
686 // PHI is erased.
687 Indirect++;
688
689 PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
690 NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
691 IBRPred);
692
693 // Create a PHI in the body block, to merge the direct and indirect
694 // predecessors.
695 PHINode *MergePHI =
696 PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
697 MergePHI->addIncoming(NewIndPHI, Target);
698 MergePHI->addIncoming(DirPHI, DirectSucc);
699
700 IndPHI->replaceAllUsesWith(MergePHI);
701 IndPHI->eraseFromParent();
702 }
703
704 Changed = true;
705 }
706
707 return Changed;
708}
709
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000710/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
711/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
712/// edges in ways that are non-optimal for isel. Start by eliminating these
713/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000714bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000715 SmallPtrSet<BasicBlock *, 16> Preheaders;
716 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
717 while (!LoopList.empty()) {
718 Loop *L = LoopList.pop_back_val();
719 LoopList.insert(LoopList.end(), L->begin(), L->end());
720 if (BasicBlock *Preheader = L->getLoopPreheader())
721 Preheaders.insert(Preheader);
722 }
723
Chris Lattnerc3748562007-04-02 01:35:34 +0000724 bool MadeChange = false;
725 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000726 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000727 BasicBlock *BB = &*I++;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000728 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
729 if (!DestBB ||
730 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000731 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000732
Sanjay Patelfc580a62015-09-21 23:03:16 +0000733 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000734 MadeChange = true;
735 }
736 return MadeChange;
737}
738
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000739bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
740 BasicBlock *DestBB,
741 bool isPreheader) {
742 // Do not delete loop preheaders if doing so would create a critical edge.
743 // Loop preheaders can be good locations to spill registers. If the
744 // preheader is deleted and we create a critical edge, registers may be
745 // spilled in the loop body instead.
746 if (!DisablePreheaderProtect && isPreheader &&
747 !(BB->getSinglePredecessor() &&
748 BB->getSinglePredecessor()->getSingleSuccessor()))
749 return false;
750
751 // Try to skip merging if the unique predecessor of BB is terminated by a
752 // switch or indirect branch instruction, and BB is used as an incoming block
753 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
754 // add COPY instructions in the predecessor of BB instead of BB (if it is not
755 // merged). Note that the critical edge created by merging such blocks wont be
756 // split in MachineSink because the jump table is not analyzable. By keeping
757 // such empty block (BB), ISel will place COPY instructions in BB, not in the
758 // predecessor of BB.
759 BasicBlock *Pred = BB->getUniquePredecessor();
760 if (!Pred ||
761 !(isa<SwitchInst>(Pred->getTerminator()) ||
762 isa<IndirectBrInst>(Pred->getTerminator())))
763 return true;
764
765 if (BB->getTerminator() != BB->getFirstNonPHI())
766 return true;
767
768 // We use a simple cost heuristic which determine skipping merging is
769 // profitable if the cost of skipping merging is less than the cost of
770 // merging : Cost(skipping merging) < Cost(merging BB), where the
771 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
772 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
773 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
774 // Freq(Pred) / Freq(BB) > 2.
775 // Note that if there are multiple empty blocks sharing the same incoming
776 // value for the PHIs in the DestBB, we consider them together. In such
777 // case, Cost(merging BB) will be the sum of their frequencies.
778
779 if (!isa<PHINode>(DestBB->begin()))
780 return true;
781
782 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
783
784 // Find all other incoming blocks from which incoming values of all PHIs in
785 // DestBB are the same as the ones from BB.
786 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
787 ++PI) {
788 BasicBlock *DestBBPred = *PI;
789 if (DestBBPred == BB)
790 continue;
791
Balaram Makam32bcb5d2017-10-27 00:35:18 +0000792 bool HasAllSameValue = true;
793 BasicBlock::const_iterator DestBBI = DestBB->begin();
794 while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) {
795 if (DestPN->getIncomingValueForBlock(BB) !=
796 DestPN->getIncomingValueForBlock(DestBBPred)) {
797 HasAllSameValue = false;
798 break;
799 }
800 }
801 if (HasAllSameValue)
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000802 SameIncomingValueBBs.insert(DestBBPred);
803 }
804
805 // See if all BB's incoming values are same as the value from Pred. In this
806 // case, no reason to skip merging because COPYs are expected to be place in
807 // Pred already.
808 if (SameIncomingValueBBs.count(Pred))
809 return true;
810
811 if (!BFI) {
812 Function &F = *BB->getParent();
813 LoopInfo LI{DominatorTree(F)};
814 BPI.reset(new BranchProbabilityInfo(F, LI));
815 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
816 }
817
818 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
819 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
820
821 for (auto SameValueBB : SameIncomingValueBBs)
822 if (SameValueBB->getUniquePredecessor() == Pred &&
823 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
824 BBFreq += BFI->getBlockFreq(SameValueBB);
825
826 return PredFreq.getFrequency() <=
827 BBFreq.getFrequency() * FreqRatioToSkipMerge;
828}
829
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000830/// Return true if we can merge BB into DestBB if there is a single
831/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000832/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000833bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000834 const BasicBlock *DestBB) const {
835 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
836 // the successor. If there are more complex condition (e.g. preheaders),
837 // don't mess around with them.
838 BasicBlock::const_iterator BBI = BB->begin();
839 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000840 for (const User *U : PN->users()) {
841 const Instruction *UI = cast<Instruction>(U);
842 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000843 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000844 // If User is inside DestBB block and it is a PHINode then check
845 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000846 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000847 if (UI->getParent() == DestBB) {
848 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000849 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
850 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
851 if (Insn && Insn->getParent() == BB &&
852 Insn->getParent() != UPN->getIncomingBlock(I))
853 return false;
854 }
855 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000856 }
857 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000858
Chris Lattnerc3748562007-04-02 01:35:34 +0000859 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
860 // and DestBB may have conflicting incoming values for the block. If so, we
861 // can't merge the block.
862 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
863 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000864
Chris Lattnerc3748562007-04-02 01:35:34 +0000865 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000866 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000867 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
868 // It is faster to get preds from a PHI than with pred_iterator.
869 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
870 BBPreds.insert(BBPN->getIncomingBlock(i));
871 } else {
872 BBPreds.insert(pred_begin(BB), pred_end(BB));
873 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000874
Chris Lattnerc3748562007-04-02 01:35:34 +0000875 // Walk the preds of DestBB.
876 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
877 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
878 if (BBPreds.count(Pred)) { // Common predecessor?
879 BBI = DestBB->begin();
880 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
881 const Value *V1 = PN->getIncomingValueForBlock(Pred);
882 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000883
Chris Lattnerc3748562007-04-02 01:35:34 +0000884 // If V2 is a phi node in BB, look up what the mapped value will be.
885 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
886 if (V2PN->getParent() == BB)
887 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000888
Chris Lattnerc3748562007-04-02 01:35:34 +0000889 // If there is a conflict, bail out.
890 if (V1 != V2) return false;
891 }
892 }
893 }
894
895 return true;
896}
897
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000898/// Eliminate a basic block that has only phi's and an unconditional branch in
899/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000900void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000901 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
902 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000903
David Greene74e2d492010-01-05 01:27:11 +0000904 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000905
Chris Lattnerc3748562007-04-02 01:35:34 +0000906 // If the destination block has a single pred, then this is a trivial edge,
907 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000908 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000909 if (SinglePred != DestBB) {
910 // Remember if SinglePred was the entry block of the function. If so, we
911 // will need to move BB back to the entry position.
912 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Balaram Makam32bcb5d2017-10-27 00:35:18 +0000913 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000914
Chris Lattner8a172da2008-11-28 19:54:49 +0000915 if (isEntry && BB != &BB->getParent()->getEntryBlock())
916 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000917
David Greene74e2d492010-01-05 01:27:11 +0000918 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000919 return;
920 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000921 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000922
Chris Lattnerc3748562007-04-02 01:35:34 +0000923 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
924 // to handle the new incoming edges it is about to have.
925 PHINode *PN;
926 for (BasicBlock::iterator BBI = DestBB->begin();
927 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
928 // Remove the incoming value for BB, and remember it.
929 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000930
Chris Lattnerc3748562007-04-02 01:35:34 +0000931 // Two options: either the InVal is a phi node defined in BB or it is some
932 // value that dominates BB.
933 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
934 if (InValPhi && InValPhi->getParent() == BB) {
935 // Add all of the input values of the input PHI as inputs of this phi.
936 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
937 PN->addIncoming(InValPhi->getIncomingValue(i),
938 InValPhi->getIncomingBlock(i));
939 } else {
940 // Otherwise, add one instance of the dominating value for each edge that
941 // we will be adding.
942 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
943 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
944 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
945 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000946 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
947 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000948 }
949 }
950 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000951
Chris Lattnerc3748562007-04-02 01:35:34 +0000952 // The PHIs are now updated, change everything that refers to BB to use
953 // DestBB and remove BB.
954 BB->replaceAllUsesWith(DestBB);
955 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000956 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000957
David Greene74e2d492010-01-05 01:27:11 +0000958 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000959}
960
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000961// Computes a map of base pointer relocation instructions to corresponding
962// derived pointer relocation instructions given a vector of all relocate calls
963static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000964 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
965 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
966 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000967 // Collect information in two maps: one primarily for locating the base object
968 // while filling the second map; the second map is the final structure holding
969 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000970 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
971 for (auto *ThisRelocate : AllRelocateCalls) {
972 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
973 ThisRelocate->getDerivedPtrIndex());
974 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000975 }
976 for (auto &Item : RelocateIdxMap) {
977 std::pair<unsigned, unsigned> Key = Item.first;
978 if (Key.first == Key.second)
979 // Base relocation: nothing to insert
980 continue;
981
Manuel Jacob83eefa62016-01-05 04:03:00 +0000982 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000983 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000984
985 // We're iterating over RelocateIdxMap so we cannot modify it.
986 auto MaybeBase = RelocateIdxMap.find(BaseKey);
987 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000988 // TODO: We might want to insert a new base object relocate and gep off
989 // that, if there are enough derived object relocates.
990 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000991
992 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000993 }
994}
995
996// Accepts a GEP and extracts the operands into a vector provided they're all
997// small integer constants
998static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
999 SmallVectorImpl<Value *> &OffsetV) {
1000 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1001 // Only accept small constant integer operands
1002 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1003 if (!Op || Op->getZExtValue() > 20)
1004 return false;
1005 }
1006
1007 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1008 OffsetV.push_back(GEP->getOperand(i));
1009 return true;
1010}
1011
1012// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1013// replace, computes a replacement, and affects it.
1014static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +00001015simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
1016 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001017 bool MadeChange = false;
Serguei Katkov9e5604d2017-08-17 05:48:30 +00001018 // We must ensure the relocation of derived pointer is defined after
1019 // relocation of base pointer. If we find a relocation corresponding to base
1020 // defined earlier than relocation of base then we move relocation of base
1021 // right before found relocation. We consider only relocation in the same
1022 // basic block as relocation of base. Relocations from other basic block will
1023 // be skipped by optimization and we do not care about them.
1024 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
1025 &*R != RelocatedBase; ++R)
1026 if (auto RI = dyn_cast<GCRelocateInst>(R))
1027 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1028 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1029 RelocatedBase->moveBefore(RI);
1030 break;
1031 }
1032
Manuel Jacob83eefa62016-01-05 04:03:00 +00001033 for (GCRelocateInst *ToReplace : Targets) {
1034 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001035 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +00001036 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001037 // A duplicate relocate call. TODO: coalesce duplicates.
1038 continue;
1039 }
1040
Igor Laevskyf637b4a2015-11-03 18:37:40 +00001041 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1042 // Base and derived relocates are in different basic blocks.
1043 // In this case transform is only valid when base dominates derived
1044 // relocate. However it would be too expensive to check dominance
1045 // for each such relocate, so we skip the whole transformation.
1046 continue;
1047 }
1048
Manuel Jacob83eefa62016-01-05 04:03:00 +00001049 Value *Base = ToReplace->getBasePtr();
1050 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001051 if (!Derived || Derived->getPointerOperand() != Base)
1052 continue;
1053
1054 SmallVector<Value *, 2> OffsetV;
1055 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1056 continue;
1057
1058 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +00001059 assert(RelocatedBase->getNextNode() &&
1060 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +00001061
1062 // Insert after RelocatedBase
1063 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001064 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +00001065
1066 // If gc_relocate does not match the actual type, cast it to the right type.
1067 // In theory, there must be a bitcast after gc_relocate if the type does not
1068 // match, and we should reuse it to get the derived pointer. But it could be
1069 // cases like this:
1070 // bb1:
1071 // ...
1072 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1073 // br label %merge
1074 //
1075 // bb2:
1076 // ...
1077 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1078 // br label %merge
1079 //
1080 // merge:
1081 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1082 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1083 //
1084 // In this case, we can not find the bitcast any more. So we insert a new bitcast
1085 // no matter there is already one or not. In this way, we can handle all cases, and
1086 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +00001087 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +00001088 if (RelocatedBase->getType() != Base->getType()) {
1089 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +00001090 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +00001091 }
David Blaikie68d535c2015-03-24 22:38:16 +00001092 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +00001093 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001094 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +00001095 // If the newly generated derived pointer's type does not match the original derived
1096 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +00001097 Value *ActualReplacement = Replacement;
1098 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +00001099 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +00001100 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +00001101 }
1102 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001103 ToReplace->eraseFromParent();
1104
1105 MadeChange = true;
1106 }
1107 return MadeChange;
1108}
1109
1110// Turns this:
1111//
1112// %base = ...
1113// %ptr = gep %base + 15
1114// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1115// %base' = relocate(%tok, i32 4, i32 4)
1116// %ptr' = relocate(%tok, i32 4, i32 5)
1117// %val = load %ptr'
1118//
1119// into this:
1120//
1121// %base = ...
1122// %ptr = gep %base + 15
1123// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1124// %base' = gc.relocate(%tok, i32 4, i32 4)
1125// %ptr' = gep %base' + 15
1126// %val = load %ptr'
1127bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1128 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +00001129 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001130
1131 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +00001132 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001133 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +00001134 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001135
1136 // We need atleast one base pointer relocation + one derived pointer
1137 // relocation to mangle
1138 if (AllRelocateCalls.size() < 2)
1139 return false;
1140
1141 // RelocateInstMap is a mapping from the base relocate instruction to the
1142 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +00001143 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001144 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1145 if (RelocateInstMap.empty())
1146 return false;
1147
1148 for (auto &Item : RelocateInstMap)
1149 // Item.first is the RelocatedBase to offset against
1150 // Item.second is the vector of Targets to replace
1151 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1152 return MadeChange;
1153}
1154
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001155/// SinkCast - Sink the specified cast instruction into its user blocks
1156static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001157 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001158
Chris Lattnerf2836d12007-03-31 04:06:36 +00001159 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001160 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001161
Chris Lattnerf2836d12007-03-31 04:06:36 +00001162 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001163 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001164 UI != E; ) {
1165 Use &TheUse = UI.getUse();
1166 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001167
Chris Lattnerf2836d12007-03-31 04:06:36 +00001168 // Figure out which BB this cast is used in. For PHI's this is the
1169 // appropriate predecessor block.
1170 BasicBlock *UserBB = User->getParent();
1171 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001172 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001173 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001174
Chris Lattnerf2836d12007-03-31 04:06:36 +00001175 // Preincrement use iterator so we don't invalidate it.
1176 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001177
David Majnemer0c80e2e2016-04-27 19:36:38 +00001178 // The first insertion point of a block containing an EH pad is after the
1179 // pad. If the pad is the user, we cannot sink the cast past the pad.
1180 if (User->isEHPad())
1181 continue;
1182
Andrew Kaylord0430e82015-11-23 19:16:15 +00001183 // If the block selected to receive the cast is an EH pad that does not
1184 // allow non-PHI instructions before the terminator, we can't sink the
1185 // cast.
1186 if (UserBB->getTerminator()->isEHPad())
1187 continue;
1188
Chris Lattnerf2836d12007-03-31 04:06:36 +00001189 // If this user is in the same block as the cast, don't change the cast.
1190 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001191
Chris Lattnerf2836d12007-03-31 04:06:36 +00001192 // If we have already inserted a cast into this block, use it.
1193 CastInst *&InsertedCast = InsertedCasts[UserBB];
1194
1195 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001196 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001197 assert(InsertPt != UserBB->end());
1198 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1199 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001200 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001201
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001202 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001203 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001204 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001205 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001206 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001207
Chris Lattnerf2836d12007-03-31 04:06:36 +00001208 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001209 if (CI->use_empty()) {
Adrian Prantl261ac8b2017-11-03 21:55:03 +00001210 salvageDebugInfo(*CI);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001211 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001212 MadeChange = true;
1213 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001214
Chris Lattnerf2836d12007-03-31 04:06:36 +00001215 return MadeChange;
1216}
1217
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001218/// If the specified cast instruction is a noop copy (e.g. it's casting from
1219/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1220/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001221///
1222/// Return true if any changes are made.
Mehdi Amini44ede332015-07-09 02:09:04 +00001223static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1224 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001225 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1226 // than sinking only nop casts, but is helpful on some platforms.
1227 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1228 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1229 ASC->getDestAddressSpace()))
1230 return false;
1231 }
1232
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001233 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001234 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1235 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001236
1237 // This is an fp<->int conversion?
1238 if (SrcVT.isInteger() != DstVT.isInteger())
1239 return false;
1240
1241 // If this is an extension, it will be a zero or sign extension, which
1242 // isn't a noop.
1243 if (SrcVT.bitsLT(DstVT)) return false;
1244
1245 // If these values will be promoted, find out what they will be promoted
1246 // to. This helps us consider truncates on PPC as noop copies when they
1247 // are.
1248 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1249 TargetLowering::TypePromoteInteger)
1250 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1251 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1252 TargetLowering::TypePromoteInteger)
1253 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1254
1255 // If, after promotion, these are the same types, this is a noop copy.
1256 if (SrcVT != DstVT)
1257 return false;
1258
1259 return SinkCast(CI);
1260}
1261
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001262/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1263/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001264///
1265/// Return true if any changes were made.
1266static bool CombineUAddWithOverflow(CmpInst *CI) {
1267 Value *A, *B;
1268 Instruction *AddI;
1269 if (!match(CI,
1270 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1271 return false;
1272
1273 Type *Ty = AddI->getType();
1274 if (!isa<IntegerType>(Ty))
1275 return false;
1276
1277 // We don't want to move around uses of condition values this late, so we we
1278 // check if it is legal to create the call to the intrinsic in the basic
1279 // block containing the icmp:
1280
1281 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1282 return false;
1283
1284#ifndef NDEBUG
1285 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1286 // for now:
1287 if (AddI->hasOneUse())
1288 assert(*AddI->user_begin() == CI && "expected!");
1289#endif
1290
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001291 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001292 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1293
1294 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1295
1296 auto *UAddWithOverflow =
1297 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1298 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1299 auto *Overflow =
1300 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1301
1302 CI->replaceAllUsesWith(Overflow);
1303 AddI->replaceAllUsesWith(UAdd);
1304 CI->eraseFromParent();
1305 AddI->eraseFromParent();
1306 return true;
1307}
1308
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001309/// Sink the given CmpInst into user blocks to reduce the number of virtual
1310/// registers that must be created and coalesced. This is a clear win except on
1311/// targets with multiple condition code registers (PowerPC), where it might
1312/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001313///
1314/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001315static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001316 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001317
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001318 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001319 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001320 return false;
1321
1322 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001323 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001324
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001325 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001326 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001327 UI != E; ) {
1328 Use &TheUse = UI.getUse();
1329 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001330
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001331 // Preincrement use iterator so we don't invalidate it.
1332 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001333
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001334 // Don't bother for PHI nodes.
1335 if (isa<PHINode>(User))
1336 continue;
1337
1338 // Figure out which BB this cmp is used in.
1339 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001340
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001341 // If this user is in the same block as the cmp, don't change the cmp.
1342 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001343
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001344 // If we have already inserted a cmp into this block, use it.
1345 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1346
1347 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001348 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001349 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001350 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001351 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1352 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001353 // Propagate the debug info.
1354 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001355 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001356
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001357 // Replace a use of the cmp with a use of the new cmp.
1358 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001359 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001360 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001361 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001362
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001363 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001364 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001365 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001366 MadeChange = true;
1367 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001368
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001369 return MadeChange;
1370}
1371
Peter Zotovf87e5502016-04-03 17:11:53 +00001372static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001373 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001374 return true;
1375
1376 if (CombineUAddWithOverflow(CI))
1377 return true;
1378
1379 return false;
1380}
1381
Geoff Berry5d534b62017-02-21 18:53:14 +00001382/// Duplicate and sink the given 'and' instruction into user blocks where it is
1383/// used in a compare to allow isel to generate better code for targets where
1384/// this operation can be combined.
1385///
1386/// Return true if any changes are made.
1387static bool sinkAndCmp0Expression(Instruction *AndI,
1388 const TargetLowering &TLI,
1389 SetOfInstrs &InsertedInsts) {
1390 // Double-check that we're not trying to optimize an instruction that was
1391 // already optimized by some other part of this pass.
1392 assert(!InsertedInsts.count(AndI) &&
1393 "Attempting to optimize already optimized and instruction");
1394 (void) InsertedInsts;
1395
1396 // Nothing to do for single use in same basic block.
1397 if (AndI->hasOneUse() &&
1398 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1399 return false;
1400
1401 // Try to avoid cases where sinking/duplicating is likely to increase register
1402 // pressure.
1403 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1404 !isa<ConstantInt>(AndI->getOperand(1)) &&
1405 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1406 return false;
1407
1408 for (auto *U : AndI->users()) {
1409 Instruction *User = cast<Instruction>(U);
1410
1411 // Only sink for and mask feeding icmp with 0.
1412 if (!isa<ICmpInst>(User))
1413 return false;
1414
1415 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1416 if (!CmpC || !CmpC->isZero())
1417 return false;
1418 }
1419
1420 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1421 return false;
1422
1423 DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1424 DEBUG(AndI->getParent()->dump());
1425
1426 // Push the 'and' into the same block as the icmp 0. There should only be
1427 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1428 // others, so we don't need to keep track of which BBs we insert into.
1429 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1430 UI != E; ) {
1431 Use &TheUse = UI.getUse();
1432 Instruction *User = cast<Instruction>(*UI);
1433
1434 // Preincrement use iterator so we don't invalidate it.
1435 ++UI;
1436
1437 DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1438
1439 // Keep the 'and' in the same place if the use is already in the same block.
1440 Instruction *InsertPt =
1441 User->getParent() == AndI->getParent() ? AndI : User;
1442 Instruction *InsertedAnd =
1443 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1444 AndI->getOperand(1), "", InsertPt);
1445 // Propagate the debug info.
1446 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1447
1448 // Replace a use of the 'and' with a use of the new 'and'.
1449 TheUse = InsertedAnd;
1450 ++NumAndUses;
1451 DEBUG(User->getParent()->dump());
1452 }
1453
1454 // We removed all uses, nuke the and.
1455 AndI->eraseFromParent();
1456 return true;
1457}
1458
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001459/// Check if the candidates could be combined with a shift instruction, which
1460/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001461/// 1. Truncate instruction
1462/// 2. And instruction and the imm is a mask of the low bits:
1463/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001464static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001465 if (!isa<TruncInst>(User)) {
1466 if (User->getOpcode() != Instruction::And ||
1467 !isa<ConstantInt>(User->getOperand(1)))
1468 return false;
1469
Quentin Colombetd4f44692014-04-22 01:20:34 +00001470 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001471
Quentin Colombetd4f44692014-04-22 01:20:34 +00001472 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001473 return false;
1474 }
1475 return true;
1476}
1477
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001478/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001479static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001480SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1481 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001482 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001483 BasicBlock *UserBB = User->getParent();
1484 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1485 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1486 bool MadeChange = false;
1487
1488 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1489 TruncE = TruncI->user_end();
1490 TruncUI != TruncE;) {
1491
1492 Use &TruncTheUse = TruncUI.getUse();
1493 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1494 // Preincrement use iterator so we don't invalidate it.
1495
1496 ++TruncUI;
1497
1498 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1499 if (!ISDOpcode)
1500 continue;
1501
Tim Northovere2239ff2014-07-29 10:20:22 +00001502 // If the use is actually a legal node, there will not be an
1503 // implicit truncate.
1504 // FIXME: always querying the result type is just an
1505 // approximation; some nodes' legality is determined by the
1506 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001507 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001508 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001509 continue;
1510
1511 // Don't bother for PHI nodes.
1512 if (isa<PHINode>(TruncUser))
1513 continue;
1514
1515 BasicBlock *TruncUserBB = TruncUser->getParent();
1516
1517 if (UserBB == TruncUserBB)
1518 continue;
1519
1520 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1521 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1522
1523 if (!InsertedShift && !InsertedTrunc) {
1524 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001525 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001526 // Sink the shift
1527 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001528 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1529 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001530 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001531 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1532 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001533
1534 // Sink the trunc
1535 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1536 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001537 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001538
1539 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001540 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001541
1542 MadeChange = true;
1543
1544 TruncTheUse = InsertedTrunc;
1545 }
1546 }
1547 return MadeChange;
1548}
1549
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001550/// Sink the shift *right* instruction into user blocks if the uses could
1551/// potentially be combined with this shift instruction and generate BitExtract
1552/// instruction. It will only be applied if the architecture supports BitExtract
1553/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001554/// BB1:
1555/// %x.extract.shift = lshr i64 %arg1, 32
1556/// BB2:
1557/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1558/// ==>
1559///
1560/// BB2:
1561/// %x.extract.shift.1 = lshr i64 %arg1, 32
1562/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1563///
1564/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1565/// instruction.
1566/// Return true if any changes are made.
1567static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001568 const TargetLowering &TLI,
1569 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001570 BasicBlock *DefBB = ShiftI->getParent();
1571
1572 /// Only insert instructions in each block once.
1573 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1574
Mehdi Amini44ede332015-07-09 02:09:04 +00001575 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001576
1577 bool MadeChange = false;
1578 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1579 UI != E;) {
1580 Use &TheUse = UI.getUse();
1581 Instruction *User = cast<Instruction>(*UI);
1582 // Preincrement use iterator so we don't invalidate it.
1583 ++UI;
1584
1585 // Don't bother for PHI nodes.
1586 if (isa<PHINode>(User))
1587 continue;
1588
1589 if (!isExtractBitsCandidateUse(User))
1590 continue;
1591
1592 BasicBlock *UserBB = User->getParent();
1593
1594 if (UserBB == DefBB) {
1595 // If the shift and truncate instruction are in the same BB. The use of
1596 // the truncate(TruncUse) may still introduce another truncate if not
1597 // legal. In this case, we would like to sink both shift and truncate
1598 // instruction to the BB of TruncUse.
1599 // for example:
1600 // BB1:
1601 // i64 shift.result = lshr i64 opnd, imm
1602 // trunc.result = trunc shift.result to i16
1603 //
1604 // BB2:
1605 // ----> We will have an implicit truncate here if the architecture does
1606 // not have i16 compare.
1607 // cmp i16 trunc.result, opnd2
1608 //
1609 if (isa<TruncInst>(User) && shiftIsLegal
1610 // If the type of the truncate is legal, no trucate will be
1611 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001612 &&
1613 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001614 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001615 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001616
1617 continue;
1618 }
1619 // If we have already inserted a shift into this block, use it.
1620 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1621
1622 if (!InsertedShift) {
1623 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001624 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001625
1626 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001627 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1628 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001629 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001630 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1631 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001632
1633 MadeChange = true;
1634 }
1635
1636 // Replace a use of the shift with a use of the new shift.
1637 TheUse = InsertedShift;
1638 }
1639
1640 // If we removed all uses, nuke the shift.
1641 if (ShiftI->use_empty())
1642 ShiftI->eraseFromParent();
1643
1644 return MadeChange;
1645}
1646
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001647/// If counting leading or trailing zeros is an expensive operation and a zero
1648/// input is defined, add a check for zero to avoid calling the intrinsic.
1649///
1650/// We want to transform:
1651/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1652///
1653/// into:
1654/// entry:
1655/// %cmpz = icmp eq i64 %A, 0
1656/// br i1 %cmpz, label %cond.end, label %cond.false
1657/// cond.false:
1658/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1659/// br label %cond.end
1660/// cond.end:
1661/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1662///
1663/// If the transform is performed, return true and set ModifiedDT to true.
1664static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1665 const TargetLowering *TLI,
1666 const DataLayout *DL,
1667 bool &ModifiedDT) {
1668 if (!TLI || !DL)
1669 return false;
1670
1671 // If a zero input is undefined, it doesn't make sense to despeculate that.
1672 if (match(CountZeros->getOperand(1), m_One()))
1673 return false;
1674
1675 // If it's cheap to speculate, there's nothing to do.
1676 auto IntrinsicID = CountZeros->getIntrinsicID();
1677 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1678 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1679 return false;
1680
1681 // Only handle legal scalar cases. Anything else requires too much work.
1682 Type *Ty = CountZeros->getType();
1683 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001684 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001685 return false;
1686
1687 // The intrinsic will be sunk behind a compare against zero and branch.
1688 BasicBlock *StartBlock = CountZeros->getParent();
1689 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1690
1691 // Create another block after the count zero intrinsic. A PHI will be added
1692 // in this block to select the result of the intrinsic or the bit-width
1693 // constant if the input to the intrinsic is zero.
1694 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1695 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1696
1697 // Set up a builder to create a compare, conditional branch, and PHI.
1698 IRBuilder<> Builder(CountZeros->getContext());
1699 Builder.SetInsertPoint(StartBlock->getTerminator());
1700 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1701
1702 // Replace the unconditional branch that was created by the first split with
1703 // a compare against zero and a conditional branch.
1704 Value *Zero = Constant::getNullValue(Ty);
1705 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1706 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1707 StartBlock->getTerminator()->eraseFromParent();
1708
1709 // Create a PHI in the end block to select either the output of the intrinsic
1710 // or the bit width of the operand.
1711 Builder.SetInsertPoint(&EndBlock->front());
1712 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1713 CountZeros->replaceAllUsesWith(PN);
1714 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1715 PN->addIncoming(BitWidth, StartBlock);
1716 PN->addIncoming(CountZeros, CallBlock);
1717
1718 // We are explicitly handling the zero case, so we can set the intrinsic's
1719 // undefined zero argument to 'true'. This will also prevent reprocessing the
1720 // intrinsic; we only despeculate when a zero input is defined.
1721 CountZeros->setArgOperand(1, Builder.getTrue());
1722 ModifiedDT = true;
1723 return true;
1724}
1725
Sanjay Patel3b8974b2017-06-08 20:00:09 +00001726bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001727 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001728
Chris Lattner7a277142011-01-15 07:14:54 +00001729 // Lower inline assembly if we can.
1730 // If we found an inline asm expession, and if the target knows how to
1731 // lower it to normal LLVM code, do so now.
1732 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1733 if (TLI->ExpandInlineAsm(CI)) {
1734 // Avoid invalidating the iterator.
1735 CurInstIterator = BB->begin();
1736 // Avoid processing instructions out of order, which could cause
1737 // reuse before a value is defined.
1738 SunkAddrs.clear();
1739 return true;
1740 }
1741 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001742 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001743 return true;
1744 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001745
John Brawn0dbcd652015-03-18 12:01:59 +00001746 // Align the pointer arguments to this call if the target thinks it's a good
1747 // idea
1748 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001749 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001750 for (auto &Arg : CI->arg_operands()) {
1751 // We want to align both objects whose address is used directly and
1752 // objects whose address is used in casts and GEPs, though it only makes
1753 // sense for GEPs if the offset is a multiple of the desired alignment and
1754 // if size - offset meets the size threshold.
1755 if (!Arg->getType()->isPointerTy())
1756 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001757 APInt Offset(DL->getPointerSizeInBits(
1758 cast<PointerType>(Arg->getType())->getAddressSpace()),
1759 0);
1760 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001761 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001762 if ((Offset2 & (PrefAlign-1)) != 0)
1763 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001764 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001765 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1766 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001767 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001768 // Global variables can only be aligned if they are defined in this
1769 // object (i.e. they are uniquely initialized in this object), and
1770 // over-aligning global variables that have an explicit section is
1771 // forbidden.
1772 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001773 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001774 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001775 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001776 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001777 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001778 }
1779 // If this is a memcpy (or similar) then we may be able to improve the
1780 // alignment
1781 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001782 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001783 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001784 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001785 if (Align > MI->getAlignment())
1786 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001787 }
1788 }
1789
Philip Reamesac115ed2016-03-09 23:13:12 +00001790 // If we have a cold call site, try to sink addressing computation into the
1791 // cold block. This interacts with our handling for loads and stores to
1792 // ensure that we can fold all uses of a potential addressing computation
1793 // into their uses. TODO: generalize this to work over profiling data
1794 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1795 for (auto &Arg : CI->arg_operands()) {
1796 if (!Arg->getType()->isPointerTy())
1797 continue;
1798 unsigned AS = Arg->getType()->getPointerAddressSpace();
1799 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1800 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001801
Eric Christopher4b7948e2010-03-11 02:41:03 +00001802 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001803 if (II) {
1804 switch (II->getIntrinsicID()) {
1805 default: break;
1806 case Intrinsic::objectsize: {
1807 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00001808 ConstantInt *RetVal =
1809 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001810 // Substituting this can cause recursive simplifications, which can
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001811 // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case
1812 // this
Sanjoy Das2cbeb002017-04-26 16:37:05 +00001813 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001814 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001815 WeakTrackingVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001816
Sanjay Patel545a4562016-01-20 18:59:16 +00001817 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001818
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001819 // If the iterator instruction was recursively deleted, start over at the
1820 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001821 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001822 CurInstIterator = BB->begin();
1823 SunkAddrs.clear();
1824 }
1825 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001826 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001827 case Intrinsic::aarch64_stlxr:
1828 case Intrinsic::aarch64_stxr: {
1829 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1830 if (!ExtVal || !ExtVal->hasOneUse() ||
1831 ExtVal->getParent() == CI->getParent())
1832 return false;
1833 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1834 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001835 // Mark this instruction as "inserted by CGP", so that other
1836 // optimizations don't touch it.
1837 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001838 return true;
1839 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001840 case Intrinsic::invariant_group_barrier:
1841 II->replaceAllUsesWith(II->getArgOperand(0));
1842 II->eraseFromParent();
1843 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001844
1845 case Intrinsic::cttz:
1846 case Intrinsic::ctlz:
1847 // If counting zeros is expensive, try to avoid it.
1848 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001849 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001850
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001851 if (TLI) {
1852 SmallVector<Value*, 2> PtrOps;
1853 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001854 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1855 while (!PtrOps.empty()) {
1856 Value *PtrVal = PtrOps.pop_back_val();
1857 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1858 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001859 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001860 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001861 }
Pete Cooper615fd892012-03-13 20:59:56 +00001862 }
1863
Eric Christopher4b7948e2010-03-11 02:41:03 +00001864 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001865 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001866
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001867 // Lower all default uses of _chk calls. This is very similar
1868 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001869 // to fortified library functions (e.g. __memcpy_chk) that have the default
1870 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001871 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001872 if (Value *V = Simplifier.optimizeCall(CI)) {
1873 CI->replaceAllUsesWith(V);
1874 CI->eraseFromParent();
1875 return true;
1876 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001877
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001878 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001879}
Chris Lattner1b93be52011-01-15 07:25:29 +00001880
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001881/// Look for opportunities to duplicate return instructions to the predecessor
1882/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001883/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001884/// bb0:
1885/// %tmp0 = tail call i32 @f0()
1886/// br label %return
1887/// bb1:
1888/// %tmp1 = tail call i32 @f1()
1889/// br label %return
1890/// bb2:
1891/// %tmp2 = tail call i32 @f2()
1892/// br label %return
1893/// return:
1894/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1895/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001896/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001897///
1898/// =>
1899///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001900/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001901/// bb0:
1902/// %tmp0 = tail call i32 @f0()
1903/// ret i32 %tmp0
1904/// bb1:
1905/// %tmp1 = tail call i32 @f1()
1906/// ret i32 %tmp1
1907/// bb2:
1908/// %tmp2 = tail call i32 @f2()
1909/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001910/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001911bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001912 if (!TLI)
1913 return false;
1914
Michael Kuperstein71321562016-09-07 20:29:49 +00001915 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1916 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001917 return false;
1918
Craig Topperc0196b12014-04-14 00:51:57 +00001919 PHINode *PN = nullptr;
1920 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001921 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001922 if (V) {
1923 BCI = dyn_cast<BitCastInst>(V);
1924 if (BCI)
1925 V = BCI->getOperand(0);
1926
1927 PN = dyn_cast<PHINode>(V);
1928 if (!PN)
1929 return false;
1930 }
Evan Cheng0663f232011-03-21 01:19:09 +00001931
Cameron Zwarich4649f172011-03-24 04:52:10 +00001932 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001933 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001934
Cameron Zwarich4649f172011-03-24 04:52:10 +00001935 // Make sure there are no instructions between the PHI and return, or that the
1936 // return is the first instruction in the block.
1937 if (PN) {
1938 BasicBlock::iterator BI = BB->begin();
1939 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001940 if (&*BI == BCI)
1941 // Also skip over the bitcast.
1942 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001943 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001944 return false;
1945 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001946 BasicBlock::iterator BI = BB->begin();
1947 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001948 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001949 return false;
1950 }
Evan Cheng0663f232011-03-21 01:19:09 +00001951
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001952 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1953 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001954 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001955 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001956 if (PN) {
1957 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1958 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1959 // Make sure the phi value is indeed produced by the tail call.
1960 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001961 TLI->mayBeEmittedAsTailCall(CI) &&
1962 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001963 TailCalls.push_back(CI);
1964 }
1965 } else {
1966 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001967 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001968 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001969 continue;
1970
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001971 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001972 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1973 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001974 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1975 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001976 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001977
Cameron Zwarich4649f172011-03-24 04:52:10 +00001978 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001979 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1980 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001981 TailCalls.push_back(CI);
1982 }
Evan Cheng0663f232011-03-21 01:19:09 +00001983 }
1984
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001985 bool Changed = false;
1986 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1987 CallInst *CI = TailCalls[i];
1988 CallSite CS(CI);
1989
1990 // Conservatively require the attributes of the call to match those of the
1991 // return. Ignore noalias because it doesn't affect the call sequence.
Reid Klecknerb5180542017-03-21 16:57:19 +00001992 AttributeList CalleeAttrs = CS.getAttributes();
1993 if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1994 .removeAttribute(Attribute::NoAlias) !=
1995 AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1996 .removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001997 continue;
1998
1999 // Make sure the call instruction is followed by an unconditional branch to
2000 // the return block.
2001 BasicBlock *CallBB = CI->getParent();
2002 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2003 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2004 continue;
2005
2006 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002007 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002008 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002009 ++NumRetsDup;
2010 }
2011
2012 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002013 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002014 BB->eraseFromParent();
2015
2016 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002017}
2018
Chris Lattner728f9022008-11-25 07:09:13 +00002019//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002020// Memory Optimization
2021//===----------------------------------------------------------------------===//
2022
Chandler Carruthc8925912013-01-05 02:09:22 +00002023namespace {
2024
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002025/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002026/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002027struct ExtAddrMode : public TargetLowering::AddrMode {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002028 Value *BaseReg = nullptr;
2029 Value *ScaledReg = nullptr;
John Brawn736bf002017-10-03 13:08:22 +00002030 Value *OriginalValue = nullptr;
2031
2032 enum FieldName {
2033 NoField = 0x00,
2034 BaseRegField = 0x01,
2035 BaseGVField = 0x02,
2036 BaseOffsField = 0x04,
2037 ScaledRegField = 0x08,
2038 ScaleField = 0x10,
2039 MultipleFields = 0xff
2040 };
Eugene Zelenko900b6332017-08-29 22:32:07 +00002041
2042 ExtAddrMode() = default;
2043
Chandler Carruthc8925912013-01-05 02:09:22 +00002044 void print(raw_ostream &OS) const;
2045 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002046
John Brawn736bf002017-10-03 13:08:22 +00002047 FieldName compare(const ExtAddrMode &other) {
2048 // First check that the types are the same on each field, as differing types
2049 // is something we can't cope with later on.
2050 if (BaseReg && other.BaseReg &&
2051 BaseReg->getType() != other.BaseReg->getType())
2052 return MultipleFields;
2053 if (BaseGV && other.BaseGV &&
2054 BaseGV->getType() != other.BaseGV->getType())
2055 return MultipleFields;
2056 if (ScaledReg && other.ScaledReg &&
2057 ScaledReg->getType() != other.ScaledReg->getType())
2058 return MultipleFields;
2059
2060 // Check each field to see if it differs.
2061 unsigned Result = NoField;
2062 if (BaseReg != other.BaseReg)
2063 Result |= BaseRegField;
2064 if (BaseGV != other.BaseGV)
2065 Result |= BaseGVField;
2066 if (BaseOffs != other.BaseOffs)
2067 Result |= BaseOffsField;
2068 if (ScaledReg != other.ScaledReg)
2069 Result |= ScaledRegField;
2070 // Don't count 0 as being a different scale, because that actually means
2071 // unscaled (which will already be counted by having no ScaledReg).
2072 if (Scale && other.Scale && Scale != other.Scale)
2073 Result |= ScaleField;
2074
2075 if (countPopulation(Result) > 1)
2076 return MultipleFields;
2077 else
2078 return static_cast<FieldName>(Result);
2079 }
2080
Serguei Katkovf66a59e2017-10-31 07:01:35 +00002081 // AddrModes with a baseReg or gv where the reg/gv is
2082 // the only populated field are trivial.
John Brawn736bf002017-10-03 13:08:22 +00002083 bool isTrivial() {
Serguei Katkovf66a59e2017-10-31 07:01:35 +00002084 if (BaseGV && !BaseOffs && !Scale && !BaseReg)
2085 return true;
2086
2087 if (!BaseGV && !BaseOffs && !Scale && BaseReg)
2088 return true;
2089
2090 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00002091 }
John Brawn70cdb5b2017-11-24 14:10:45 +00002092
2093 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
2094 switch (Field) {
2095 default:
2096 return nullptr;
2097 case BaseRegField:
2098 return BaseReg;
2099 case BaseGVField:
2100 return BaseGV;
2101 case ScaledRegField:
2102 return ScaledReg;
2103 case BaseOffsField:
2104 return ConstantInt::get(IntPtrTy, BaseOffs);
2105 }
2106 }
2107
2108 void SetCombinedField(FieldName Field, Value *V,
2109 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
2110 switch (Field) {
2111 default:
2112 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
2113 break;
2114 case ExtAddrMode::BaseRegField:
2115 BaseReg = V;
2116 break;
2117 case ExtAddrMode::BaseGVField:
2118 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
2119 // in the BaseReg field.
2120 assert(BaseReg == nullptr);
2121 BaseReg = V;
2122 BaseGV = nullptr;
2123 break;
2124 case ExtAddrMode::ScaledRegField:
2125 ScaledReg = V;
2126 // If we have a mix of scaled and unscaled addrmodes then we want scale
2127 // to be the scale and not zero.
2128 if (!Scale)
2129 for (const ExtAddrMode &AM : AddrModes)
2130 if (AM.Scale) {
2131 Scale = AM.Scale;
2132 break;
2133 }
2134 break;
2135 case ExtAddrMode::BaseOffsField:
2136 // The offset is no longer a constant, so it goes in ScaledReg with a
2137 // scale of 1.
2138 assert(ScaledReg == nullptr);
2139 ScaledReg = V;
2140 Scale = 1;
2141 BaseOffs = 0;
2142 break;
2143 }
2144 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002145};
2146
Eugene Zelenko900b6332017-08-29 22:32:07 +00002147} // end anonymous namespace
2148
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002149#ifndef NDEBUG
2150static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2151 AM.print(OS);
2152 return OS;
2153}
2154#endif
2155
Aaron Ballman615eb472017-10-15 14:32:27 +00002156#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthc8925912013-01-05 02:09:22 +00002157void ExtAddrMode::print(raw_ostream &OS) const {
2158 bool NeedPlus = false;
2159 OS << "[";
2160 if (BaseGV) {
2161 OS << (NeedPlus ? " + " : "")
2162 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002163 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002164 NeedPlus = true;
2165 }
2166
Richard Trieuc0f91212014-05-30 03:15:17 +00002167 if (BaseOffs) {
2168 OS << (NeedPlus ? " + " : "")
2169 << BaseOffs;
2170 NeedPlus = true;
2171 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002172
2173 if (BaseReg) {
2174 OS << (NeedPlus ? " + " : "")
2175 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002176 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002177 NeedPlus = true;
2178 }
2179 if (Scale) {
2180 OS << (NeedPlus ? " + " : "")
2181 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002182 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002183 }
2184
2185 OS << ']';
2186}
2187
Yaron Kereneb2a2542016-01-29 20:50:44 +00002188LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002189 print(dbgs());
2190 dbgs() << '\n';
2191}
2192#endif
2193
Eugene Zelenko900b6332017-08-29 22:32:07 +00002194namespace {
2195
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002196/// \brief This class provides transaction based operation on the IR.
2197/// Every change made through this class is recorded in the internal state and
2198/// can be undone (rollback) until commit is called.
2199class TypePromotionTransaction {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002200 /// \brief This represents the common interface of the individual transaction.
2201 /// Each class implements the logic for doing one specific modification on
2202 /// the IR via the TypePromotionTransaction.
2203 class TypePromotionAction {
2204 protected:
2205 /// The Instruction modified.
2206 Instruction *Inst;
2207
2208 public:
2209 /// \brief Constructor of the action.
2210 /// The constructor performs the related action on the IR.
2211 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2212
Eugene Zelenko900b6332017-08-29 22:32:07 +00002213 virtual ~TypePromotionAction() = default;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002214
2215 /// \brief Undo the modification done by this action.
2216 /// When this method is called, the IR must be in the same state as it was
2217 /// before this action was applied.
2218 /// \pre Undoing the action works if and only if the IR is in the exact same
2219 /// state as it was directly after this action was applied.
2220 virtual void undo() = 0;
2221
2222 /// \brief Advocate every change made by this action.
2223 /// When the results on the IR of the action are to be kept, it is important
2224 /// to call this function, otherwise hidden information may be kept forever.
2225 virtual void commit() {
2226 // Nothing to be done, this action is not doing anything.
2227 }
2228 };
2229
2230 /// \brief Utility to remember the position of an instruction.
2231 class InsertionHandler {
2232 /// Position of an instruction.
2233 /// Either an instruction:
2234 /// - Is the first in a basic block: BB is used.
2235 /// - Has a previous instructon: PrevInst is used.
2236 union {
2237 Instruction *PrevInst;
2238 BasicBlock *BB;
2239 } Point;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002240
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002241 /// Remember whether or not the instruction had a previous instruction.
2242 bool HasPrevInstruction;
2243
2244 public:
2245 /// \brief Record the position of \p Inst.
2246 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002247 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002248 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2249 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002250 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002251 else
2252 Point.BB = Inst->getParent();
2253 }
2254
2255 /// \brief Insert \p Inst at the recorded position.
2256 void insert(Instruction *Inst) {
2257 if (HasPrevInstruction) {
2258 if (Inst->getParent())
2259 Inst->removeFromParent();
2260 Inst->insertAfter(Point.PrevInst);
2261 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002262 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002263 if (Inst->getParent())
2264 Inst->moveBefore(Position);
2265 else
2266 Inst->insertBefore(Position);
2267 }
2268 }
2269 };
2270
2271 /// \brief Move an instruction before another.
2272 class InstructionMoveBefore : public TypePromotionAction {
2273 /// Original position of the instruction.
2274 InsertionHandler Position;
2275
2276 public:
2277 /// \brief Move \p Inst before \p Before.
2278 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2279 : TypePromotionAction(Inst), Position(Inst) {
2280 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2281 Inst->moveBefore(Before);
2282 }
2283
2284 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002285 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002286 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2287 Position.insert(Inst);
2288 }
2289 };
2290
2291 /// \brief Set the operand of an instruction with a new value.
2292 class OperandSetter : public TypePromotionAction {
2293 /// Original operand of the instruction.
2294 Value *Origin;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002295
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002296 /// Index of the modified instruction.
2297 unsigned Idx;
2298
2299 public:
2300 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2301 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2302 : TypePromotionAction(Inst), Idx(Idx) {
2303 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2304 << "for:" << *Inst << "\n"
2305 << "with:" << *NewVal << "\n");
2306 Origin = Inst->getOperand(Idx);
2307 Inst->setOperand(Idx, NewVal);
2308 }
2309
2310 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002311 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002312 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2313 << "for: " << *Inst << "\n"
2314 << "with: " << *Origin << "\n");
2315 Inst->setOperand(Idx, Origin);
2316 }
2317 };
2318
2319 /// \brief Hide the operands of an instruction.
2320 /// Do as if this instruction was not using any of its operands.
2321 class OperandsHider : public TypePromotionAction {
2322 /// The list of original operands.
2323 SmallVector<Value *, 4> OriginalValues;
2324
2325 public:
2326 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2327 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2328 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2329 unsigned NumOpnds = Inst->getNumOperands();
2330 OriginalValues.reserve(NumOpnds);
2331 for (unsigned It = 0; It < NumOpnds; ++It) {
2332 // Save the current operand.
2333 Value *Val = Inst->getOperand(It);
2334 OriginalValues.push_back(Val);
2335 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002336 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002337 // that we are not willing to pay.
2338 Inst->setOperand(It, UndefValue::get(Val->getType()));
2339 }
2340 }
2341
2342 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002343 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002344 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2345 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2346 Inst->setOperand(It, OriginalValues[It]);
2347 }
2348 };
2349
2350 /// \brief Build a truncate instruction.
2351 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002352 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002353
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002354 public:
2355 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2356 /// result.
2357 /// trunc Opnd to Ty.
2358 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2359 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002360 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2361 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002362 }
2363
Quentin Colombetac55b152014-09-16 22:36:07 +00002364 /// \brief Get the built value.
2365 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002366
2367 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002368 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002369 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2370 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2371 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002372 }
2373 };
2374
2375 /// \brief Build a sign extension instruction.
2376 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002377 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002378
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002379 public:
2380 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2381 /// result.
2382 /// sext Opnd to Ty.
2383 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002384 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002385 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002386 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2387 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002388 }
2389
Quentin Colombetac55b152014-09-16 22:36:07 +00002390 /// \brief Get the built value.
2391 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002392
2393 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002394 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002395 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2396 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2397 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002398 }
2399 };
2400
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002401 /// \brief Build a zero extension instruction.
2402 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002403 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002404
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002405 public:
2406 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2407 /// result.
2408 /// zext Opnd to Ty.
2409 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002410 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002411 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002412 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2413 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002414 }
2415
Quentin Colombetac55b152014-09-16 22:36:07 +00002416 /// \brief Get the built value.
2417 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002418
2419 /// \brief Remove the built instruction.
2420 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002421 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2422 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2423 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002424 }
2425 };
2426
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002427 /// \brief Mutate an instruction to another type.
2428 class TypeMutator : public TypePromotionAction {
2429 /// Record the original type.
2430 Type *OrigTy;
2431
2432 public:
2433 /// \brief Mutate the type of \p Inst into \p NewTy.
2434 TypeMutator(Instruction *Inst, Type *NewTy)
2435 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2436 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2437 << "\n");
2438 Inst->mutateType(NewTy);
2439 }
2440
2441 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002442 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002443 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2444 << "\n");
2445 Inst->mutateType(OrigTy);
2446 }
2447 };
2448
2449 /// \brief Replace the uses of an instruction by another instruction.
2450 class UsesReplacer : public TypePromotionAction {
2451 /// Helper structure to keep track of the replaced uses.
2452 struct InstructionAndIdx {
2453 /// The instruction using the instruction.
2454 Instruction *Inst;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002455
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002456 /// The index where this instruction is used for Inst.
2457 unsigned Idx;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002458
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002459 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2460 : Inst(Inst), Idx(Idx) {}
2461 };
2462
2463 /// Keep track of the original uses (pair Instruction, Index).
2464 SmallVector<InstructionAndIdx, 4> OriginalUses;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002465
2466 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002467
2468 public:
2469 /// \brief Replace all the use of \p Inst by \p New.
2470 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2471 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2472 << "\n");
2473 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002474 for (Use &U : Inst->uses()) {
2475 Instruction *UserI = cast<Instruction>(U.getUser());
2476 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002477 }
2478 // Now, we can replace the uses.
2479 Inst->replaceAllUsesWith(New);
2480 }
2481
2482 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002483 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002484 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2485 for (use_iterator UseIt = OriginalUses.begin(),
2486 EndIt = OriginalUses.end();
2487 UseIt != EndIt; ++UseIt) {
2488 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2489 }
2490 }
2491 };
2492
2493 /// \brief Remove an instruction from the IR.
2494 class InstructionRemover : public TypePromotionAction {
2495 /// Original position of the instruction.
2496 InsertionHandler Inserter;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002497
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002498 /// Helper structure to hide all the link to the instruction. In other
2499 /// words, this helps to do as if the instruction was removed.
2500 OperandsHider Hider;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002501
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002502 /// Keep track of the uses replaced, if any.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002503 UsesReplacer *Replacer = nullptr;
2504
Jun Bum Limdee55652017-04-03 19:20:07 +00002505 /// Keep track of instructions removed.
2506 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002507
2508 public:
2509 /// \brief Remove all reference of \p Inst and optinally replace all its
2510 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002511 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002512 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002513 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2514 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002515 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Eugene Zelenko900b6332017-08-29 22:32:07 +00002516 RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002517 if (New)
2518 Replacer = new UsesReplacer(Inst, New);
2519 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002520 RemovedInsts.insert(Inst);
2521 /// The instructions removed here will be freed after completing
2522 /// optimizeBlock() for all blocks as we need to keep track of the
2523 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002524 Inst->removeFromParent();
2525 }
2526
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002527 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002528
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002529 /// \brief Resurrect the instruction and reassign it to the proper uses if
2530 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002531 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002532 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2533 Inserter.insert(Inst);
2534 if (Replacer)
2535 Replacer->undo();
2536 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002537 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002538 }
2539 };
2540
2541public:
2542 /// Restoration point.
2543 /// The restoration point is a pointer to an action instead of an iterator
2544 /// because the iterator may be invalidated but not the pointer.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002545 using ConstRestorationPt = const TypePromotionAction *;
Jun Bum Limdee55652017-04-03 19:20:07 +00002546
2547 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2548 : RemovedInsts(RemovedInsts) {}
2549
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002550 /// Advocate every changes made in that transaction.
2551 void commit();
Eugene Zelenko900b6332017-08-29 22:32:07 +00002552
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002553 /// Undo all the changes made after the given point.
2554 void rollback(ConstRestorationPt Point);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002555
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002556 /// Get the current restoration point.
2557 ConstRestorationPt getRestorationPoint() const;
2558
2559 /// \name API for IR modification with state keeping to support rollback.
2560 /// @{
2561 /// Same as Instruction::setOperand.
2562 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002563
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002564 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002565 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002566
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002567 /// Same as Value::replaceAllUsesWith.
2568 void replaceAllUsesWith(Instruction *Inst, Value *New);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002569
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002570 /// Same as Value::mutateType.
2571 void mutateType(Instruction *Inst, Type *NewTy);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002572
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002573 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002574 Value *createTrunc(Instruction *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002575
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002576 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002577 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002578
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002579 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002580 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002581
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002582 /// Same as Instruction::moveBefore.
2583 void moveBefore(Instruction *Inst, Instruction *Before);
2584 /// @}
2585
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002586private:
2587 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002588 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002589
2590 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2591
Jun Bum Limdee55652017-04-03 19:20:07 +00002592 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002593};
2594
Eugene Zelenko900b6332017-08-29 22:32:07 +00002595} // end anonymous namespace
2596
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002597void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2598 Value *NewVal) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002599 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2600 Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002601}
2602
2603void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2604 Value *NewVal) {
2605 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002606 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2607 Inst, RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002608}
2609
2610void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2611 Value *New) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002612 Actions.push_back(
2613 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002614}
2615
2616void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002617 Actions.push_back(
2618 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002619}
2620
Quentin Colombetac55b152014-09-16 22:36:07 +00002621Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2622 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002623 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002624 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002625 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002626 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002627}
2628
Quentin Colombetac55b152014-09-16 22:36:07 +00002629Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2630 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002631 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002632 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002633 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002634 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002635}
2636
Quentin Colombetac55b152014-09-16 22:36:07 +00002637Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2638 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002639 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002640 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002641 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002642 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002643}
2644
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002645void TypePromotionTransaction::moveBefore(Instruction *Inst,
2646 Instruction *Before) {
2647 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002648 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2649 Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002650}
2651
2652TypePromotionTransaction::ConstRestorationPt
2653TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002654 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002655}
2656
2657void TypePromotionTransaction::commit() {
2658 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002659 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002660 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002661 Actions.clear();
2662}
2663
2664void TypePromotionTransaction::rollback(
2665 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002666 while (!Actions.empty() && Point != Actions.back().get()) {
2667 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002668 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002669 }
2670}
2671
Eugene Zelenko900b6332017-08-29 22:32:07 +00002672namespace {
2673
Chandler Carruthc8925912013-01-05 02:09:22 +00002674/// \brief A helper class for matching addressing modes.
2675///
2676/// This encapsulates the logic for matching the target-legal addressing modes.
2677class AddressingModeMatcher {
2678 SmallVectorImpl<Instruction*> &AddrModeInsts;
2679 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002680 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002681 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002682
2683 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2684 /// the memory instruction that we're computing this address for.
2685 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002686 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002687 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002688
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002689 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002690 /// part of the return value of this addressing mode matching stuff.
2691 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002692
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002693 /// The instructions inserted by other CodeGenPrepare optimizations.
2694 const SetOfInstrs &InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002695
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002696 /// A map from the instructions to their type before promotion.
2697 InstrToOrigTy &PromotedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002698
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002699 /// The ongoing transaction where every action should be registered.
2700 TypePromotionTransaction &TPT;
2701
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002702 /// This is set to true when we should not do profitability checks.
2703 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002704 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002705
Eric Christopherd75c00c2015-02-26 22:38:34 +00002706 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002707 const TargetLowering &TLI,
2708 const TargetRegisterInfo &TRI,
2709 Type *AT, unsigned AS,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002710 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002711 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002712 InstrToOrigTy &PromotedInsts,
2713 TypePromotionTransaction &TPT)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002714 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002715 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2716 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2717 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002718 IgnoreProfitability = false;
2719 }
Stephen Lin837bba12013-07-15 17:55:02 +00002720
Eugene Zelenko900b6332017-08-29 22:32:07 +00002721public:
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002722 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002723 /// give an access type of AccessTy. This returns a list of involved
2724 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002725 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002726 /// optimizations.
2727 /// \p PromotedInsts maps the instructions to their type before promotion.
2728 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002729 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002730 Instruction *MemoryInst,
2731 SmallVectorImpl<Instruction*> &AddrModeInsts,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002732 const TargetLowering &TLI,
2733 const TargetRegisterInfo &TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002734 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002735 InstrToOrigTy &PromotedInsts,
2736 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002737 ExtAddrMode Result;
2738
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002739 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
2740 AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002741 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002742 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002743 (void)Success; assert(Success && "Couldn't select *anything*?");
2744 return Result;
2745 }
Eugene Zelenko900b6332017-08-29 22:32:07 +00002746
Chandler Carruthc8925912013-01-05 02:09:22 +00002747private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002748 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2749 bool matchAddr(Value *V, unsigned Depth);
2750 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002751 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002752 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002753 ExtAddrMode &AMBefore,
2754 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002755 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2756 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002757 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002758};
2759
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002760/// \brief Keep track of simplification of Phi nodes.
2761/// Accept the set of all phi nodes and erase phi node from this set
2762/// if it is simplified.
2763class SimplificationTracker {
2764 DenseMap<Value *, Value *> Storage;
2765 const SimplifyQuery &SQ;
2766 SmallPtrSetImpl<PHINode *> &AllPhiNodes;
2767 SmallPtrSetImpl<SelectInst *> &AllSelectNodes;
2768
2769public:
2770 SimplificationTracker(const SimplifyQuery &sq,
2771 SmallPtrSetImpl<PHINode *> &APN,
2772 SmallPtrSetImpl<SelectInst *> &ASN)
2773 : SQ(sq), AllPhiNodes(APN), AllSelectNodes(ASN) {}
2774
2775 Value *Get(Value *V) {
2776 do {
2777 auto SV = Storage.find(V);
2778 if (SV == Storage.end())
2779 return V;
2780 V = SV->second;
2781 } while (true);
2782 }
2783
2784 Value *Simplify(Value *Val) {
2785 SmallVector<Value *, 32> WorkList;
2786 SmallPtrSet<Value *, 32> Visited;
2787 WorkList.push_back(Val);
2788 while (!WorkList.empty()) {
2789 auto P = WorkList.pop_back_val();
2790 if (!Visited.insert(P).second)
2791 continue;
2792 if (auto *PI = dyn_cast<Instruction>(P))
2793 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
2794 for (auto *U : PI->users())
2795 WorkList.push_back(cast<Value>(U));
2796 Put(PI, V);
2797 PI->replaceAllUsesWith(V);
2798 if (auto *PHI = dyn_cast<PHINode>(PI))
2799 AllPhiNodes.erase(PHI);
2800 if (auto *Select = dyn_cast<SelectInst>(PI))
2801 AllSelectNodes.erase(Select);
2802 PI->eraseFromParent();
2803 }
2804 }
2805 return Get(Val);
2806 }
2807
2808 void Put(Value *From, Value *To) {
2809 Storage.insert({ From, To });
2810 }
2811};
2812
John Brawn736bf002017-10-03 13:08:22 +00002813/// \brief A helper class for combining addressing modes.
2814class AddressingModeCombiner {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002815 typedef std::pair<Value *, BasicBlock *> ValueInBB;
2816 typedef DenseMap<ValueInBB, Value *> FoldAddrToValueMapping;
2817 typedef std::pair<PHINode *, PHINode *> PHIPair;
2818
John Brawn736bf002017-10-03 13:08:22 +00002819private:
2820 /// The addressing modes we've collected.
2821 SmallVector<ExtAddrMode, 16> AddrModes;
2822
2823 /// The field in which the AddrModes differ, when we have more than one.
2824 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
2825
2826 /// Are the AddrModes that we have all just equal to their original values?
2827 bool AllAddrModesTrivial = true;
2828
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002829 /// Common Type for all different fields in addressing modes.
2830 Type *CommonType;
2831
2832 /// SimplifyQuery for simplifyInstruction utility.
2833 const SimplifyQuery &SQ;
2834
2835 /// Original Address.
2836 ValueInBB Original;
2837
John Brawn736bf002017-10-03 13:08:22 +00002838public:
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002839 AddressingModeCombiner(const SimplifyQuery &_SQ, ValueInBB OriginalValue)
2840 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
2841
John Brawn736bf002017-10-03 13:08:22 +00002842 /// \brief Get the combined AddrMode
2843 const ExtAddrMode &getAddrMode() const {
2844 return AddrModes[0];
2845 }
2846
2847 /// \brief Add a new AddrMode if it's compatible with the AddrModes we already
2848 /// have.
2849 /// \return True iff we succeeded in doing so.
2850 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
2851 // Take note of if we have any non-trivial AddrModes, as we need to detect
2852 // when all AddrModes are trivial as then we would introduce a phi or select
2853 // which just duplicates what's already there.
2854 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
2855
2856 // If this is the first addrmode then everything is fine.
2857 if (AddrModes.empty()) {
2858 AddrModes.emplace_back(NewAddrMode);
2859 return true;
2860 }
2861
2862 // Figure out how different this is from the other address modes, which we
2863 // can do just by comparing against the first one given that we only care
2864 // about the cumulative difference.
2865 ExtAddrMode::FieldName ThisDifferentField =
2866 AddrModes[0].compare(NewAddrMode);
2867 if (DifferentField == ExtAddrMode::NoField)
2868 DifferentField = ThisDifferentField;
2869 else if (DifferentField != ThisDifferentField)
2870 DifferentField = ExtAddrMode::MultipleFields;
2871
John Brawn70cdb5b2017-11-24 14:10:45 +00002872 // If NewAddrMode differs in only one dimension, and that dimension isn't
2873 // the amount that ScaledReg is scaled by, then we can handle it by
Serguei Katkov505359f2017-11-20 05:42:36 +00002874 // inserting a phi/select later on. Even if NewAddMode is the same
2875 // we still need to collect it due to original value is different.
2876 // And later we will need all original values as anchors during
2877 // finding the common Phi node.
John Brawn70cdb5b2017-11-24 14:10:45 +00002878 if (DifferentField != ExtAddrMode::MultipleFields &&
2879 DifferentField != ExtAddrMode::ScaleField) {
John Brawn736bf002017-10-03 13:08:22 +00002880 AddrModes.emplace_back(NewAddrMode);
2881 return true;
2882 }
2883
2884 // We couldn't combine NewAddrMode with the rest, so return failure.
2885 AddrModes.clear();
2886 return false;
2887 }
2888
2889 /// \brief Combine the addressing modes we've collected into a single
2890 /// addressing mode.
2891 /// \return True iff we successfully combined them or we only had one so
2892 /// didn't need to combine them anyway.
2893 bool combineAddrModes() {
2894 // If we have no AddrModes then they can't be combined.
2895 if (AddrModes.size() == 0)
2896 return false;
2897
2898 // A single AddrMode can trivially be combined.
Serguei Katkov505359f2017-11-20 05:42:36 +00002899 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
John Brawn736bf002017-10-03 13:08:22 +00002900 return true;
2901
2902 // If the AddrModes we collected are all just equal to the value they are
2903 // derived from then combining them wouldn't do anything useful.
2904 if (AllAddrModesTrivial)
2905 return false;
2906
John Brawn70cdb5b2017-11-24 14:10:45 +00002907 if (!addrModeCombiningAllowed())
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002908 return false;
2909
2910 // Build a map between <original value, basic block where we saw it> to
2911 // value of base register.
2912 FoldAddrToValueMapping Map;
2913 initializeMap(Map);
2914
2915 Value *CommonValue = findCommon(Map);
2916 if (CommonValue)
John Brawn70cdb5b2017-11-24 14:10:45 +00002917 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002918 return CommonValue != nullptr;
2919 }
2920
2921private:
2922 /// \brief Initialize Map with anchor values. For address seen in some BB
2923 /// we set the value of different field saw in this address.
2924 /// If address is not an instruction than basic block is set to null.
2925 /// At the same time we find a common type for different field we will
2926 /// use to create new Phi/Select nodes. Keep it in CommonType field.
2927 void initializeMap(FoldAddrToValueMapping &Map) {
2928 // Keep track of keys where the value is null. We will need to replace it
2929 // with constant null when we know the common type.
2930 SmallVector<ValueInBB, 2> NullValue;
John Brawn70cdb5b2017-11-24 14:10:45 +00002931 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002932 for (auto &AM : AddrModes) {
2933 BasicBlock *BB = nullptr;
2934 if (Instruction *I = dyn_cast<Instruction>(AM.OriginalValue))
2935 BB = I->getParent();
2936
John Brawn70cdb5b2017-11-24 14:10:45 +00002937 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002938 if (DV) {
2939 if (CommonType)
2940 assert(CommonType == DV->getType() && "Different types detected!");
2941 else
2942 CommonType = DV->getType();
2943 Map[{ AM.OriginalValue, BB }] = DV;
2944 } else {
2945 NullValue.push_back({ AM.OriginalValue, BB });
2946 }
2947 }
2948 assert(CommonType && "At least one non-null value must be!");
2949 for (auto VIBB : NullValue)
2950 Map[VIBB] = Constant::getNullValue(CommonType);
2951 }
2952
2953 /// \brief We have mapping between value A and basic block where value A
2954 /// seen to other value B where B was a field in addressing mode represented
2955 /// by A. Also we have an original value C representin an address in some
2956 /// basic block. Traversing from C through phi and selects we ended up with
2957 /// A's in a map. This utility function tries to find a value V which is a
2958 /// field in addressing mode C and traversing through phi nodes and selects
2959 /// we will end up in corresponded values B in a map.
2960 /// The utility will create a new Phi/Selects if needed.
2961 // The simple example looks as follows:
2962 // BB1:
2963 // p1 = b1 + 40
2964 // br cond BB2, BB3
2965 // BB2:
2966 // p2 = b2 + 40
2967 // br BB3
2968 // BB3:
2969 // p = phi [p1, BB1], [p2, BB2]
2970 // v = load p
2971 // Map is
2972 // <p1, BB1> -> b1
2973 // <p2, BB2> -> b2
2974 // Request is
2975 // <p, BB3> -> ?
2976 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3
2977 Value *findCommon(FoldAddrToValueMapping &Map) {
2978 // Tracks of new created Phi nodes.
2979 SmallPtrSet<PHINode *, 32> NewPhiNodes;
2980 // Tracks of new created Select nodes.
2981 SmallPtrSet<SelectInst *, 32> NewSelectNodes;
2982 // Tracks the simplification of new created phi nodes. The reason we use
2983 // this mapping is because we will add new created Phi nodes in AddrToBase.
2984 // Simplification of Phi nodes is recursive, so some Phi node may
2985 // be simplified after we added it to AddrToBase.
2986 // Using this mapping we can find the current value in AddrToBase.
2987 SimplificationTracker ST(SQ, NewPhiNodes, NewSelectNodes);
2988
2989 // First step, DFS to create PHI nodes for all intermediate blocks.
2990 // Also fill traverse order for the second step.
2991 SmallVector<ValueInBB, 32> TraverseOrder;
2992 InsertPlaceholders(Map, TraverseOrder, NewPhiNodes, NewSelectNodes);
2993
2994 // Second Step, fill new nodes by merged values and simplify if possible.
2995 FillPlaceholders(Map, TraverseOrder, ST);
2996
2997 if (!AddrSinkNewSelects && NewSelectNodes.size() > 0) {
2998 DestroyNodes(NewPhiNodes);
2999 DestroyNodes(NewSelectNodes);
3000 return nullptr;
3001 }
3002
3003 // Now we'd like to match New Phi nodes to existed ones.
3004 unsigned PhiNotMatchedCount = 0;
3005 if (!MatchPhiSet(NewPhiNodes, ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
3006 DestroyNodes(NewPhiNodes);
3007 DestroyNodes(NewSelectNodes);
3008 return nullptr;
3009 }
3010
3011 auto *Result = ST.Get(Map.find(Original)->second);
3012 if (Result) {
3013 NumMemoryInstsPhiCreated += NewPhiNodes.size() + PhiNotMatchedCount;
3014 NumMemoryInstsSelectCreated += NewSelectNodes.size();
3015 }
3016 return Result;
3017 }
3018
3019 /// \brief Destroy nodes from a set.
3020 template <typename T> void DestroyNodes(SmallPtrSetImpl<T *> &Instructions) {
3021 // For safe erasing, replace the Phi with dummy value first.
3022 auto Dummy = UndefValue::get(CommonType);
3023 for (auto I : Instructions) {
3024 I->replaceAllUsesWith(Dummy);
3025 I->eraseFromParent();
3026 }
3027 }
3028
3029 /// \brief Try to match PHI node to Candidate.
3030 /// Matcher tracks the matched Phi nodes.
3031 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
3032 DenseSet<PHIPair> &Matcher,
3033 SmallPtrSetImpl<PHINode *> &PhiNodesToMatch) {
3034 SmallVector<PHIPair, 8> WorkList;
3035 Matcher.insert({ PHI, Candidate });
3036 WorkList.push_back({ PHI, Candidate });
3037 SmallSet<PHIPair, 8> Visited;
3038 while (!WorkList.empty()) {
3039 auto Item = WorkList.pop_back_val();
3040 if (!Visited.insert(Item).second)
3041 continue;
3042 // We iterate over all incoming values to Phi to compare them.
3043 // If values are different and both of them Phi and the first one is a
3044 // Phi we added (subject to match) and both of them is in the same basic
3045 // block then we can match our pair if values match. So we state that
3046 // these values match and add it to work list to verify that.
3047 for (auto B : Item.first->blocks()) {
3048 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
3049 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
3050 if (FirstValue == SecondValue)
3051 continue;
3052
3053 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
3054 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
3055
3056 // One of them is not Phi or
3057 // The first one is not Phi node from the set we'd like to match or
3058 // Phi nodes from different basic blocks then
3059 // we will not be able to match.
3060 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
3061 FirstPhi->getParent() != SecondPhi->getParent())
3062 return false;
3063
3064 // If we already matched them then continue.
3065 if (Matcher.count({ FirstPhi, SecondPhi }))
3066 continue;
3067 // So the values are different and does not match. So we need them to
3068 // match.
3069 Matcher.insert({ FirstPhi, SecondPhi });
3070 // But me must check it.
3071 WorkList.push_back({ FirstPhi, SecondPhi });
3072 }
3073 }
3074 return true;
3075 }
3076
3077 /// \brief For the given set of PHI nodes try to find their equivalents.
3078 /// Returns false if this matching fails and creation of new Phi is disabled.
3079 bool MatchPhiSet(SmallPtrSetImpl<PHINode *> &PhiNodesToMatch,
3080 SimplificationTracker &ST, bool AllowNewPhiNodes,
3081 unsigned &PhiNotMatchedCount) {
3082 DenseSet<PHIPair> Matched;
3083 SmallPtrSet<PHINode *, 8> WillNotMatch;
3084 while (PhiNodesToMatch.size()) {
3085 PHINode *PHI = *PhiNodesToMatch.begin();
3086
3087 // Add us, if no Phi nodes in the basic block we do not match.
3088 WillNotMatch.clear();
3089 WillNotMatch.insert(PHI);
3090
3091 // Traverse all Phis until we found equivalent or fail to do that.
3092 bool IsMatched = false;
3093 for (auto &P : PHI->getParent()->phis()) {
3094 if (&P == PHI)
3095 continue;
3096 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3097 break;
3098 // If it does not match, collect all Phi nodes from matcher.
3099 // if we end up with no match, them all these Phi nodes will not match
3100 // later.
3101 for (auto M : Matched)
3102 WillNotMatch.insert(M.first);
3103 Matched.clear();
3104 }
3105 if (IsMatched) {
3106 // Replace all matched values and erase them.
3107 for (auto MV : Matched) {
3108 MV.first->replaceAllUsesWith(MV.second);
3109 PhiNodesToMatch.erase(MV.first);
3110 ST.Put(MV.first, MV.second);
3111 MV.first->eraseFromParent();
3112 }
3113 Matched.clear();
3114 continue;
3115 }
3116 // If we are not allowed to create new nodes then bail out.
3117 if (!AllowNewPhiNodes)
3118 return false;
3119 // Just remove all seen values in matcher. They will not match anything.
3120 PhiNotMatchedCount += WillNotMatch.size();
3121 for (auto *P : WillNotMatch)
3122 PhiNodesToMatch.erase(P);
3123 }
3124 return true;
3125 }
3126 /// \brief Fill the placeholder with values from predecessors and simplify it.
3127 void FillPlaceholders(FoldAddrToValueMapping &Map,
3128 SmallVectorImpl<ValueInBB> &TraverseOrder,
3129 SimplificationTracker &ST) {
3130 while (!TraverseOrder.empty()) {
3131 auto Current = TraverseOrder.pop_back_val();
3132 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
3133 Value *CurrentValue = Current.first;
3134 BasicBlock *CurrentBlock = Current.second;
3135 Value *V = Map[Current];
3136
3137 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3138 // CurrentValue also must be Select.
3139 auto *CurrentSelect = cast<SelectInst>(CurrentValue);
3140 auto *TrueValue = CurrentSelect->getTrueValue();
3141 ValueInBB TrueItem = { TrueValue, isa<Instruction>(TrueValue)
3142 ? CurrentBlock
3143 : nullptr };
3144 assert(Map.find(TrueItem) != Map.end() && "No True Value!");
3145 Select->setTrueValue(Map[TrueItem]);
3146 auto *FalseValue = CurrentSelect->getFalseValue();
3147 ValueInBB FalseItem = { FalseValue, isa<Instruction>(FalseValue)
3148 ? CurrentBlock
3149 : nullptr };
3150 assert(Map.find(FalseItem) != Map.end() && "No False Value!");
3151 Select->setFalseValue(Map[FalseItem]);
3152 } else {
3153 // Must be a Phi node then.
3154 PHINode *PHI = cast<PHINode>(V);
3155 // Fill the Phi node with values from predecessors.
3156 bool IsDefinedInThisBB =
3157 cast<Instruction>(CurrentValue)->getParent() == CurrentBlock;
3158 auto *CurrentPhi = dyn_cast<PHINode>(CurrentValue);
3159 for (auto B : predecessors(CurrentBlock)) {
3160 Value *PV = IsDefinedInThisBB
3161 ? CurrentPhi->getIncomingValueForBlock(B)
3162 : CurrentValue;
3163 ValueInBB item = { PV, isa<Instruction>(PV) ? B : nullptr };
3164 assert(Map.find(item) != Map.end() && "No predecessor Value!");
3165 PHI->addIncoming(ST.Get(Map[item]), B);
3166 }
3167 }
3168 // Simplify if possible.
3169 Map[Current] = ST.Simplify(V);
3170 }
3171 }
3172
3173 /// Starting from value recursively iterates over predecessors up to known
3174 /// ending values represented in a map. For each traversed block inserts
3175 /// a placeholder Phi or Select.
3176 /// Reports all new created Phi/Select nodes by adding them to set.
3177 /// Also reports and order in what basic blocks have been traversed.
3178 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3179 SmallVectorImpl<ValueInBB> &TraverseOrder,
3180 SmallPtrSetImpl<PHINode *> &NewPhiNodes,
3181 SmallPtrSetImpl<SelectInst *> &NewSelectNodes) {
3182 SmallVector<ValueInBB, 32> Worklist;
3183 assert((isa<PHINode>(Original.first) || isa<SelectInst>(Original.first)) &&
3184 "Address must be a Phi or Select node");
3185 auto *Dummy = UndefValue::get(CommonType);
3186 Worklist.push_back(Original);
3187 while (!Worklist.empty()) {
3188 auto Current = Worklist.pop_back_val();
3189 // If value is not an instruction it is something global, constant,
3190 // parameter and we can say that this value is observable in any block.
3191 // Set block to null to denote it.
3192 // Also please take into account that it is how we build anchors.
3193 if (!isa<Instruction>(Current.first))
3194 Current.second = nullptr;
3195 // if it is already visited or it is an ending value then skip it.
3196 if (Map.find(Current) != Map.end())
3197 continue;
3198 TraverseOrder.push_back(Current);
3199
3200 Value *CurrentValue = Current.first;
3201 BasicBlock *CurrentBlock = Current.second;
3202 // CurrentValue must be a Phi node or select. All others must be covered
3203 // by anchors.
3204 Instruction *CurrentI = cast<Instruction>(CurrentValue);
3205 bool IsDefinedInThisBB = CurrentI->getParent() == CurrentBlock;
3206
3207 unsigned PredCount =
3208 std::distance(pred_begin(CurrentBlock), pred_end(CurrentBlock));
3209 // if Current Value is not defined in this basic block we are interested
3210 // in values in predecessors.
3211 if (!IsDefinedInThisBB) {
3212 assert(PredCount && "Unreachable block?!");
3213 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3214 &CurrentBlock->front());
3215 Map[Current] = PHI;
3216 NewPhiNodes.insert(PHI);
3217 // Add all predecessors in work list.
3218 for (auto B : predecessors(CurrentBlock))
3219 Worklist.push_back({ CurrentValue, B });
3220 continue;
3221 }
3222 // Value is defined in this basic block.
3223 if (SelectInst *OrigSelect = dyn_cast<SelectInst>(CurrentI)) {
3224 // Is it OK to get metadata from OrigSelect?!
3225 // Create a Select placeholder with dummy value.
3226 SelectInst *Select =
3227 SelectInst::Create(OrigSelect->getCondition(), Dummy, Dummy,
3228 OrigSelect->getName(), OrigSelect, OrigSelect);
3229 Map[Current] = Select;
3230 NewSelectNodes.insert(Select);
3231 // We are interested in True and False value in this basic block.
3232 Worklist.push_back({ OrigSelect->getTrueValue(), CurrentBlock });
3233 Worklist.push_back({ OrigSelect->getFalseValue(), CurrentBlock });
3234 } else {
3235 // It must be a Phi node then.
3236 auto *CurrentPhi = cast<PHINode>(CurrentI);
3237 // Create new Phi node for merge of bases.
3238 assert(PredCount && "Unreachable block?!");
3239 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3240 &CurrentBlock->front());
3241 Map[Current] = PHI;
3242 NewPhiNodes.insert(PHI);
3243
3244 // Add all predecessors in work list.
3245 for (auto B : predecessors(CurrentBlock))
3246 Worklist.push_back({ CurrentPhi->getIncomingValueForBlock(B), B });
3247 }
3248 }
John Brawn736bf002017-10-03 13:08:22 +00003249 }
John Brawn70cdb5b2017-11-24 14:10:45 +00003250
3251 bool addrModeCombiningAllowed() {
3252 if (DisableComplexAddrModes)
3253 return false;
3254 switch (DifferentField) {
3255 default:
3256 return false;
3257 case ExtAddrMode::BaseRegField:
3258 return AddrSinkCombineBaseReg;
3259 case ExtAddrMode::BaseGVField:
3260 return AddrSinkCombineBaseGV;
3261 case ExtAddrMode::BaseOffsField:
3262 return AddrSinkCombineBaseOffs;
3263 case ExtAddrMode::ScaledRegField:
3264 return AddrSinkCombineScaledReg;
3265 }
3266 }
John Brawn736bf002017-10-03 13:08:22 +00003267};
Eugene Zelenko900b6332017-08-29 22:32:07 +00003268} // end anonymous namespace
3269
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003270/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003271/// Return true and update AddrMode if this addr mode is legal for the target,
3272/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003273bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003274 unsigned Depth) {
3275 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3276 // mode. Just process that directly.
3277 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003278 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003279
Chandler Carruthc8925912013-01-05 02:09:22 +00003280 // If the scale is 0, it takes nothing to add this.
3281 if (Scale == 0)
3282 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003283
Chandler Carruthc8925912013-01-05 02:09:22 +00003284 // If we already have a scale of this value, we can add to it, otherwise, we
3285 // need an available scale field.
3286 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3287 return false;
3288
3289 ExtAddrMode TestAddrMode = AddrMode;
3290
3291 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3292 // [A+B + A*7] -> [B+A*8].
3293 TestAddrMode.Scale += Scale;
3294 TestAddrMode.ScaledReg = ScaleReg;
3295
3296 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003297 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003298 return false;
3299
3300 // It was legal, so commit it.
3301 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003302
Chandler Carruthc8925912013-01-05 02:09:22 +00003303 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3304 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3305 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003306 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003307 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3308 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3309 TestAddrMode.ScaledReg = AddLHS;
3310 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003311
Chandler Carruthc8925912013-01-05 02:09:22 +00003312 // If this addressing mode is legal, commit it and remember that we folded
3313 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003314 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003315 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3316 AddrMode = TestAddrMode;
3317 return true;
3318 }
3319 }
3320
3321 // Otherwise, not (x+c)*scale, just return what we have.
3322 return true;
3323}
3324
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003325/// This is a little filter, which returns true if an addressing computation
3326/// involving I might be folded into a load/store accessing it.
3327/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003328/// the set of instructions that MatchOperationAddr can.
3329static bool MightBeFoldableInst(Instruction *I) {
3330 switch (I->getOpcode()) {
3331 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003332 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003333 // Don't touch identity bitcasts.
3334 if (I->getType() == I->getOperand(0)->getType())
3335 return false;
3336 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3337 case Instruction::PtrToInt:
3338 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3339 return true;
3340 case Instruction::IntToPtr:
3341 // We know the input is intptr_t, so this is foldable.
3342 return true;
3343 case Instruction::Add:
3344 return true;
3345 case Instruction::Mul:
3346 case Instruction::Shl:
3347 // Can only handle X*C and X << C.
3348 return isa<ConstantInt>(I->getOperand(1));
3349 case Instruction::GetElementPtr:
3350 return true;
3351 default:
3352 return false;
3353 }
3354}
3355
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003356/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3357/// \note \p Val is assumed to be the product of some type promotion.
3358/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3359/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003360static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3361 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003362 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3363 if (!PromotedInst)
3364 return false;
3365 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3366 // If the ISDOpcode is undefined, it was undefined before the promotion.
3367 if (!ISDOpcode)
3368 return true;
3369 // Otherwise, check if the promoted instruction is legal or not.
3370 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003371 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003372}
3373
Eugene Zelenko900b6332017-08-29 22:32:07 +00003374namespace {
3375
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003376/// \brief Hepler class to perform type promotion.
3377class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003378 /// \brief Utility function to check whether or not a sign or zero extension
3379 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3380 /// either using the operands of \p Inst or promoting \p Inst.
3381 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003382 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003383 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003384 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003385 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003386 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003387 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003388 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003389 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3390 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003391
3392 /// \brief Utility function to determine if \p OpIdx should be promoted when
3393 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003394 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003395 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003396 }
3397
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003398 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003399 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003400 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003401 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003402 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003403 /// Newly added extensions are inserted in \p Exts.
3404 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003405 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003406 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003407 static Value *promoteOperandForTruncAndAnyExt(
3408 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003409 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003410 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003411 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003412
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003413 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003414 /// operand is promotable and is not a supported trunc or sext.
3415 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003416 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003417 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003418 /// Newly added extensions are inserted in \p Exts.
3419 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003420 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003421 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003422 static Value *promoteOperandForOther(Instruction *Ext,
3423 TypePromotionTransaction &TPT,
3424 InstrToOrigTy &PromotedInsts,
3425 unsigned &CreatedInstsCost,
3426 SmallVectorImpl<Instruction *> *Exts,
3427 SmallVectorImpl<Instruction *> *Truncs,
3428 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003429
3430 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003431 static Value *signExtendOperandForOther(
3432 Instruction *Ext, TypePromotionTransaction &TPT,
3433 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3434 SmallVectorImpl<Instruction *> *Exts,
3435 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3436 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3437 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003438 }
3439
3440 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003441 static Value *zeroExtendOperandForOther(
3442 Instruction *Ext, TypePromotionTransaction &TPT,
3443 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3444 SmallVectorImpl<Instruction *> *Exts,
3445 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3446 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3447 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003448 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003449
3450public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003451 /// Type for the utility function that promotes the operand of Ext.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003452 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3453 InstrToOrigTy &PromotedInsts,
3454 unsigned &CreatedInstsCost,
3455 SmallVectorImpl<Instruction *> *Exts,
3456 SmallVectorImpl<Instruction *> *Truncs,
3457 const TargetLowering &TLI);
3458
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003459 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3460 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003461 /// \return NULL if no promotable action is possible with the current
3462 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003463 /// \p InsertedInsts keeps track of all the instructions inserted by the
3464 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003465 /// because we do not want to promote these instructions as CodeGenPrepare
3466 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3467 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003468 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003469 const TargetLowering &TLI,
3470 const InstrToOrigTy &PromotedInsts);
3471};
3472
Eugene Zelenko900b6332017-08-29 22:32:07 +00003473} // end anonymous namespace
3474
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003475bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003476 Type *ConsideredExtType,
3477 const InstrToOrigTy &PromotedInsts,
3478 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003479 // The promotion helper does not know how to deal with vector types yet.
3480 // To be able to fix that, we would need to fix the places where we
3481 // statically extend, e.g., constants and such.
3482 if (Inst->getType()->isVectorTy())
3483 return false;
3484
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003485 // We can always get through zext.
3486 if (isa<ZExtInst>(Inst))
3487 return true;
3488
3489 // sext(sext) is ok too.
3490 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003491 return true;
3492
3493 // We can get through binary operator, if it is legal. In other words, the
3494 // binary operator must have a nuw or nsw flag.
3495 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3496 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003497 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3498 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003499 return true;
3500
3501 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003502 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003503 if (!isa<TruncInst>(Inst))
3504 return false;
3505
3506 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003507 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003508 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003509 if (!OpndVal->getType()->isIntegerTy() ||
3510 OpndVal->getType()->getIntegerBitWidth() >
3511 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003512 return false;
3513
3514 // If the operand of the truncate is not an instruction, we will not have
3515 // any information on the dropped bits.
3516 // (Actually we could for constant but it is not worth the extra logic).
3517 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3518 if (!Opnd)
3519 return false;
3520
3521 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003522 // I.e., check that trunc just drops extended bits of the same kind of
3523 // the extension.
3524 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003525 const Type *OpndType;
3526 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003527 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3528 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003529 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3530 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003531 else
3532 return false;
3533
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003534 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003535 return Inst->getType()->getIntegerBitWidth() >=
3536 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003537}
3538
3539TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003540 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003541 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003542 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3543 "Unexpected instruction type");
3544 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3545 Type *ExtTy = Ext->getType();
3546 bool IsSExt = isa<SExtInst>(Ext);
3547 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003548 // get through.
3549 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003550 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003551 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003552
3553 // Do not promote if the operand has been added by codegenprepare.
3554 // Otherwise, it means we are undoing an optimization that is likely to be
3555 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003556 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003557 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003558
3559 // SExt or Trunc instructions.
3560 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003561 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3562 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003563 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003564
3565 // Regular instruction.
3566 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003567 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003568 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003569 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003570}
3571
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003572Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003573 Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003574 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003575 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003576 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003577 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3578 // get through it and this method should not be called.
3579 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003580 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003581 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003582 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003583 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003584 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003585 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003586 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003587 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3588 TPT.replaceAllUsesWith(SExt, ZExt);
3589 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003590 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003591 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003592 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3593 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003594 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3595 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003596 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003597
3598 // Remove dead code.
3599 if (SExtOpnd->use_empty())
3600 TPT.eraseInstruction(SExtOpnd);
3601
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003602 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003603 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003604 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003605 if (ExtInst) {
3606 if (Exts)
3607 Exts->push_back(ExtInst);
3608 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3609 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003610 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003611 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003612
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003613 // At this point we have: ext ty opnd to ty.
3614 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3615 Value *NextVal = ExtInst->getOperand(0);
3616 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003617 return NextVal;
3618}
3619
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003620Value *TypePromotionHelper::promoteOperandForOther(
3621 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003622 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003623 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003624 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3625 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003626 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003627 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003628 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003629 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003630 if (!ExtOpnd->hasOneUse()) {
3631 // ExtOpnd will be promoted.
3632 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003633 // promoted version.
3634 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003635 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003636 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
Quentin Colombetac55b152014-09-16 22:36:07 +00003637 // Insert it just after the definition.
Sanjay Patel674d2c22017-08-29 14:07:48 +00003638 ITrunc->moveAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003639 if (Truncs)
3640 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003641 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003642
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003643 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003644 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003645 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003646 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003647 }
3648
3649 // Get through the Instruction:
3650 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003651 // 2. Replace the uses of Ext by Inst.
3652 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003653
3654 // Remember the original type of the instruction before promotion.
3655 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003656 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3657 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003658 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003659 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003660 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003661 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003662 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003663 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003664
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003665 DEBUG(dbgs() << "Propagate Ext to operands\n");
3666 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003667 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003668 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3669 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3670 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003671 DEBUG(dbgs() << "No need to propagate\n");
3672 continue;
3673 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003674 // Check if we can statically extend the operand.
3675 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003676 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003677 DEBUG(dbgs() << "Statically extend\n");
3678 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3679 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3680 : Cst->getValue().zext(BitWidth);
3681 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003682 continue;
3683 }
3684 // UndefValue are typed, so we have to statically sign extend them.
3685 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003686 DEBUG(dbgs() << "Statically extend\n");
3687 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003688 continue;
3689 }
3690
3691 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003692 // Check if Ext was reused to extend an operand.
3693 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003694 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003695 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003696 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3697 : TPT.createZExt(Ext, Opnd, Ext->getType());
3698 if (!isa<Instruction>(ValForExtOpnd)) {
3699 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3700 continue;
3701 }
3702 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003703 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003704 if (Exts)
3705 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003706 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003707
3708 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003709 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3710 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003711 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003712 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003713 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003714 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003715 if (ExtForOpnd == Ext) {
3716 DEBUG(dbgs() << "Extension is useless now\n");
3717 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003718 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003719 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003720}
3721
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003722/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003723/// \p NewCost gives the cost of extension instructions created by the
3724/// promotion.
3725/// \p OldCost gives the cost of extension instructions before the promotion
3726/// plus the number of instructions that have been
3727/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003728/// \p PromotedOperand is the value that has been promoted.
3729/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003730bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003731 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3732 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3733 // The cost of the new extensions is greater than the cost of the
3734 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003735 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003736 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003737 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003738 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003739 return true;
3740 // The promotion is neutral but it may help folding the sign extension in
3741 // loads for instance.
3742 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003743 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003744}
3745
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003746/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003747/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003748/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003749/// If \p MovedAway is not NULL, it contains the information of whether or
3750/// not AddrInst has to be folded into the addressing mode on success.
3751/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3752/// because it has been moved away.
3753/// Thus AddrInst must not be added in the matched instructions.
3754/// This state can happen when AddrInst is a sext, since it may be moved away.
3755/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3756/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003757bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003758 unsigned Depth,
3759 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003760 // Avoid exponential behavior on extremely deep expression trees.
3761 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003762
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003763 // By default, all matched instructions stay in place.
3764 if (MovedAway)
3765 *MovedAway = false;
3766
Chandler Carruthc8925912013-01-05 02:09:22 +00003767 switch (Opcode) {
3768 case Instruction::PtrToInt:
3769 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003770 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003771 case Instruction::IntToPtr: {
3772 auto AS = AddrInst->getType()->getPointerAddressSpace();
3773 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003774 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003775 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003776 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003777 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003778 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003779 case Instruction::BitCast:
3780 // BitCast is always a noop, and we can handle it as long as it is
3781 // int->int or pointer->pointer (we don't want int<->fp or something).
3782 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3783 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3784 // Don't touch identity bitcasts. These were probably put here by LSR,
3785 // and we don't want to mess around with them. Assume it knows what it
3786 // is doing.
3787 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003788 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003789 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003790 case Instruction::AddrSpaceCast: {
3791 unsigned SrcAS
3792 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3793 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3794 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003795 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003796 return false;
3797 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003798 case Instruction::Add: {
3799 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3800 ExtAddrMode BackupAddrMode = AddrMode;
3801 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003802 // Start a transaction at this point.
3803 // The LHS may match but not the RHS.
3804 // Therefore, we need a higher level restoration point to undo partially
3805 // matched operation.
3806 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3807 TPT.getRestorationPoint();
3808
Sanjay Patelfc580a62015-09-21 23:03:16 +00003809 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3810 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003811 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003812
Chandler Carruthc8925912013-01-05 02:09:22 +00003813 // Restore the old addr mode info.
3814 AddrMode = BackupAddrMode;
3815 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003816 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003817
Chandler Carruthc8925912013-01-05 02:09:22 +00003818 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003819 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3820 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003821 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003822
Chandler Carruthc8925912013-01-05 02:09:22 +00003823 // Otherwise we definitely can't merge the ADD in.
3824 AddrMode = BackupAddrMode;
3825 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003826 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003827 break;
3828 }
3829 //case Instruction::Or:
3830 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3831 //break;
3832 case Instruction::Mul:
3833 case Instruction::Shl: {
3834 // Can only handle X*C and X << C.
3835 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Philip Reames9c3cbee2017-10-30 23:59:51 +00003836 if (!RHS || RHS->getBitWidth() > 64)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003837 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003838 int64_t Scale = RHS->getSExtValue();
3839 if (Opcode == Instruction::Shl)
3840 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003841
Sanjay Patelfc580a62015-09-21 23:03:16 +00003842 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003843 }
3844 case Instruction::GetElementPtr: {
3845 // Scan the GEP. We check it if it contains constant offsets and at most
3846 // one variable offset.
3847 int VariableOperand = -1;
3848 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003849
Chandler Carruthc8925912013-01-05 02:09:22 +00003850 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003851 gep_type_iterator GTI = gep_type_begin(AddrInst);
3852 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003853 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003854 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003855 unsigned Idx =
3856 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3857 ConstantOffset += SL->getElementOffset(Idx);
3858 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003859 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003860 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3861 ConstantOffset += CI->getSExtValue()*TypeSize;
3862 } else if (TypeSize) { // Scales of zero don't do anything.
3863 // We only allow one variable index at the moment.
3864 if (VariableOperand != -1)
3865 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003866
Chandler Carruthc8925912013-01-05 02:09:22 +00003867 // Remember the variable index.
3868 VariableOperand = i;
3869 VariableScale = TypeSize;
3870 }
3871 }
3872 }
Stephen Lin837bba12013-07-15 17:55:02 +00003873
Chandler Carruthc8925912013-01-05 02:09:22 +00003874 // A common case is for the GEP to only do a constant offset. In this case,
3875 // just add it to the disp field and check validity.
3876 if (VariableOperand == -1) {
3877 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003878 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003879 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003880 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003881 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003882 return true;
3883 }
3884 AddrMode.BaseOffs -= ConstantOffset;
3885 return false;
3886 }
3887
3888 // Save the valid addressing mode in case we can't match.
3889 ExtAddrMode BackupAddrMode = AddrMode;
3890 unsigned OldSize = AddrModeInsts.size();
3891
3892 // See if the scale and offset amount is valid for this target.
3893 AddrMode.BaseOffs += ConstantOffset;
3894
3895 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003896 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003897 // If it couldn't be matched, just stuff the value in a register.
3898 if (AddrMode.HasBaseReg) {
3899 AddrMode = BackupAddrMode;
3900 AddrModeInsts.resize(OldSize);
3901 return false;
3902 }
3903 AddrMode.HasBaseReg = true;
3904 AddrMode.BaseReg = AddrInst->getOperand(0);
3905 }
3906
3907 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003908 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003909 Depth)) {
3910 // If it couldn't be matched, try stuffing the base into a register
3911 // instead of matching it, and retrying the match of the scale.
3912 AddrMode = BackupAddrMode;
3913 AddrModeInsts.resize(OldSize);
3914 if (AddrMode.HasBaseReg)
3915 return false;
3916 AddrMode.HasBaseReg = true;
3917 AddrMode.BaseReg = AddrInst->getOperand(0);
3918 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003919 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003920 VariableScale, Depth)) {
3921 // If even that didn't work, bail.
3922 AddrMode = BackupAddrMode;
3923 AddrModeInsts.resize(OldSize);
3924 return false;
3925 }
3926 }
3927
3928 return true;
3929 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003930 case Instruction::SExt:
3931 case Instruction::ZExt: {
3932 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3933 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003934 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003935
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003936 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003937 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003938 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003939 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003940 if (!TPH)
3941 return false;
3942
3943 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3944 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003945 unsigned CreatedInstsCost = 0;
3946 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003947 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003948 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003949 // SExt has been moved away.
3950 // Thus either it will be rematched later in the recursive calls or it is
3951 // gone. Anyway, we must not fold it into the addressing mode at this point.
3952 // E.g.,
3953 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003954 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003955 // addr = gep base, idx
3956 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003957 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003958 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3959 // addr = gep base, op <- match
3960 if (MovedAway)
3961 *MovedAway = true;
3962
3963 assert(PromotedOperand &&
3964 "TypePromotionHelper should have filtered out those cases");
3965
3966 ExtAddrMode BackupAddrMode = AddrMode;
3967 unsigned OldSize = AddrModeInsts.size();
3968
Sanjay Patelfc580a62015-09-21 23:03:16 +00003969 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003970 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003971 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003972 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003973 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003974 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003975 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003976 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003977 AddrMode = BackupAddrMode;
3978 AddrModeInsts.resize(OldSize);
3979 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3980 TPT.rollback(LastKnownGood);
3981 return false;
3982 }
3983 return true;
3984 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003985 }
3986 return false;
3987}
3988
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003989/// If we can, try to add the value of 'Addr' into the current addressing mode.
3990/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3991/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3992/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003993///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003994bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003995 // Start a transaction at this point that we will rollback if the matching
3996 // fails.
3997 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3998 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003999 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4000 // Fold in immediates if legal for the target.
4001 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004002 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004003 return true;
4004 AddrMode.BaseOffs -= CI->getSExtValue();
4005 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4006 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00004007 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004008 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004009 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004010 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00004011 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004012 }
4013 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4014 ExtAddrMode BackupAddrMode = AddrMode;
4015 unsigned OldSize = AddrModeInsts.size();
4016
4017 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004018 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004019 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004020 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004021 // to check here.
4022 if (MovedAway)
4023 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004024 // Okay, it's possible to fold this. Check to see if it is actually
4025 // *profitable* to do so. We use a simple cost model to avoid increasing
4026 // register pressure too much.
4027 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00004028 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004029 AddrModeInsts.push_back(I);
4030 return true;
4031 }
Stephen Lin837bba12013-07-15 17:55:02 +00004032
Chandler Carruthc8925912013-01-05 02:09:22 +00004033 // It isn't profitable to do this, roll back.
4034 //cerr << "NOT FOLDING: " << *I;
4035 AddrMode = BackupAddrMode;
4036 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004037 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004038 }
4039 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00004040 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00004041 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004042 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004043 } else if (isa<ConstantPointerNull>(Addr)) {
4044 // Null pointer gets folded without affecting the addressing mode.
4045 return true;
4046 }
4047
4048 // Worse case, the target should support [reg] addressing modes. :)
4049 if (!AddrMode.HasBaseReg) {
4050 AddrMode.HasBaseReg = true;
4051 AddrMode.BaseReg = Addr;
4052 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004053 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004054 return true;
4055 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00004056 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004057 }
4058
4059 // If the base register is already taken, see if we can do [r+r].
4060 if (AddrMode.Scale == 0) {
4061 AddrMode.Scale = 1;
4062 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004063 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004064 return true;
4065 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00004066 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004067 }
4068 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004069 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004070 return false;
4071}
4072
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004073/// Check to see if all uses of OpVal by the specified inline asm call are due
4074/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00004075static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004076 const TargetLowering &TLI,
4077 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00004078 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00004079 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004080 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004081 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004082
Chandler Carruthc8925912013-01-05 02:09:22 +00004083 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4084 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00004085
Chandler Carruthc8925912013-01-05 02:09:22 +00004086 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004087 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00004088
4089 // If this asm operand is our Value*, and if it isn't an indirect memory
4090 // operand, we can't fold it!
4091 if (OpInfo.CallOperandVal == OpVal &&
4092 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4093 !OpInfo.isIndirect))
4094 return false;
4095 }
4096
4097 return true;
4098}
4099
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004100// Max number of memory uses to look at before aborting the search to conserve
4101// compile time.
4102static constexpr int MaxMemoryUsesToScan = 20;
4103
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004104/// Recursively walk all the uses of I until we find a memory use.
4105/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00004106/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00004107static bool FindAllMemoryUses(
4108 Instruction *I,
4109 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004110 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4111 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004112 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00004113 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00004114 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004115
Chandler Carruthc8925912013-01-05 02:09:22 +00004116 // If this is an obviously unfoldable instruction, bail out.
4117 if (!MightBeFoldableInst(I))
4118 return true;
4119
Philip Reamesac115ed2016-03-09 23:13:12 +00004120 const bool OptSize = I->getFunction()->optForSize();
4121
Chandler Carruthc8925912013-01-05 02:09:22 +00004122 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004123 for (Use &U : I->uses()) {
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004124 // Conservatively return true if we're seeing a large number or a deep chain
4125 // of users. This avoids excessive compilation times in pathological cases.
4126 if (SeenInsts++ >= MaxMemoryUsesToScan)
4127 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004128
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004129 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthcdf47882014-03-09 03:16:01 +00004130 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4131 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00004132 continue;
4133 }
Stephen Lin837bba12013-07-15 17:55:02 +00004134
Chandler Carruthcdf47882014-03-09 03:16:01 +00004135 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4136 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00004137 if (opNo != StoreInst::getPointerOperandIndex())
4138 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00004139 MemoryUses.push_back(std::make_pair(SI, opNo));
4140 continue;
4141 }
Stephen Lin837bba12013-07-15 17:55:02 +00004142
Matt Arsenault02d915b2017-03-15 22:35:20 +00004143 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4144 unsigned opNo = U.getOperandNo();
4145 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4146 return true; // Storing addr, not into addr.
4147 MemoryUses.push_back(std::make_pair(RMW, opNo));
4148 continue;
4149 }
4150
4151 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4152 unsigned opNo = U.getOperandNo();
4153 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4154 return true; // Storing addr, not into addr.
4155 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4156 continue;
4157 }
4158
Chandler Carruthcdf47882014-03-09 03:16:01 +00004159 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004160 // If this is a cold call, we can sink the addressing calculation into
4161 // the cold path. See optimizeCallInst
4162 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4163 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004164
Chandler Carruthc8925912013-01-05 02:09:22 +00004165 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4166 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004167
Chandler Carruthc8925912013-01-05 02:09:22 +00004168 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004169 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004170 return true;
4171 continue;
4172 }
Stephen Lin837bba12013-07-15 17:55:02 +00004173
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004174 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4175 SeenInsts))
Chandler Carruthc8925912013-01-05 02:09:22 +00004176 return true;
4177 }
4178
4179 return false;
4180}
4181
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004182/// Return true if Val is already known to be live at the use site that we're
4183/// folding it into. If so, there is no cost to include it in the addressing
4184/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4185/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004186bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004187 Value *KnownLive2) {
4188 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004189 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004190 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004191
Chandler Carruthc8925912013-01-05 02:09:22 +00004192 // All values other than instructions and arguments (e.g. constants) are live.
4193 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004194
Chandler Carruthc8925912013-01-05 02:09:22 +00004195 // If Val is a constant sized alloca in the entry block, it is live, this is
4196 // true because it is just a reference to the stack/frame pointer, which is
4197 // live for the whole function.
4198 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4199 if (AI->isStaticAlloca())
4200 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004201
Chandler Carruthc8925912013-01-05 02:09:22 +00004202 // Check to see if this value is already used in the memory instruction's
4203 // block. If so, it's already live into the block at the very least, so we
4204 // can reasonably fold it.
4205 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4206}
4207
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004208/// It is possible for the addressing mode of the machine to fold the specified
4209/// instruction into a load or store that ultimately uses it.
4210/// However, the specified instruction has multiple uses.
4211/// Given this, it may actually increase register pressure to fold it
4212/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004213///
4214/// X = ...
4215/// Y = X+1
4216/// use(Y) -> nonload/store
4217/// Z = Y+1
4218/// load Z
4219///
4220/// In this case, Y has multiple uses, and can be folded into the load of Z
4221/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4222/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4223/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4224/// number of computations either.
4225///
4226/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4227/// X was live across 'load Z' for other reasons, we actually *would* want to
4228/// fold the addressing mode in the Z case. This would make Y die earlier.
4229bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004230isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004231 ExtAddrMode &AMAfter) {
4232 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004233
Chandler Carruthc8925912013-01-05 02:09:22 +00004234 // AMBefore is the addressing mode before this instruction was folded into it,
4235 // and AMAfter is the addressing mode after the instruction was folded. Get
4236 // the set of registers referenced by AMAfter and subtract out those
4237 // referenced by AMBefore: this is the set of values which folding in this
4238 // address extends the lifetime of.
4239 //
4240 // Note that there are only two potential values being referenced here,
4241 // BaseReg and ScaleReg (global addresses are always available, as are any
4242 // folded immediates).
4243 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004244
Chandler Carruthc8925912013-01-05 02:09:22 +00004245 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4246 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004247 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004248 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004249 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004250 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004251
4252 // If folding this instruction (and it's subexprs) didn't extend any live
4253 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004254 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004255 return true;
4256
Philip Reamesac115ed2016-03-09 23:13:12 +00004257 // If all uses of this instruction can have the address mode sunk into them,
4258 // we can remove the addressing mode and effectively trade one live register
4259 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004260 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004261 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4262 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004263 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004264 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004265
Chandler Carruthc8925912013-01-05 02:09:22 +00004266 // Now that we know that all uses of this instruction are part of a chain of
4267 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004268 // into a memory use, loop over each of these memory operation uses and see
4269 // if they could *actually* fold the instruction. The assumption is that
4270 // addressing modes are cheap and that duplicating the computation involved
4271 // many times is worthwhile, even on a fastpath. For sinking candidates
4272 // (i.e. cold call sites), this serves as a way to prevent excessive code
4273 // growth since most architectures have some reasonable small and fast way to
4274 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004275 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4276 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4277 Instruction *User = MemoryUses[i].first;
4278 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004279
Chandler Carruthc8925912013-01-05 02:09:22 +00004280 // Get the access type of this use. If the use isn't a pointer, we don't
4281 // know what it accesses.
4282 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004283 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4284 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004285 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004286 Type *AddressAccessTy = AddrTy->getElementType();
4287 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004288
Chandler Carruthc8925912013-01-05 02:09:22 +00004289 // Do a match against the root of this address, ignoring profitability. This
4290 // will tell us if the addressing mode for the memory operation will
4291 // *actually* cover the shared instruction.
4292 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004293 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4294 TPT.getRestorationPoint();
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004295 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
4296 AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004297 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004298 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00004299 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004300 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004301 (void)Success; assert(Success && "Couldn't select *anything*?");
4302
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004303 // The match was to check the profitability, the changes made are not
4304 // part of the original matcher. Therefore, they should be dropped
4305 // otherwise the original matcher will not present the right state.
4306 TPT.rollback(LastKnownGood);
4307
Chandler Carruthc8925912013-01-05 02:09:22 +00004308 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004309 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004310 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004311
Chandler Carruthc8925912013-01-05 02:09:22 +00004312 MatchedAddrModeInsts.clear();
4313 }
Stephen Lin837bba12013-07-15 17:55:02 +00004314
Chandler Carruthc8925912013-01-05 02:09:22 +00004315 return true;
4316}
4317
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004318/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004319/// different basic block than BB.
4320static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4321 if (Instruction *I = dyn_cast<Instruction>(V))
4322 return I->getParent() != BB;
4323 return false;
4324}
4325
Philip Reamesac115ed2016-03-09 23:13:12 +00004326/// Sink addressing mode computation immediate before MemoryInst if doing so
4327/// can be done without increasing register pressure. The need for the
4328/// register pressure constraint means this can end up being an all or nothing
4329/// decision for all uses of the same addressing computation.
4330///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004331/// Load and Store Instructions often have addressing modes that can do
4332/// significant amounts of computation. As such, instruction selection will try
4333/// to get the load or store to do as much computation as possible for the
4334/// program. The problem is that isel can only see within a single block. As
4335/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004336///
4337/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004338/// operands. It's also used to sink addressing computations feeding into cold
4339/// call sites into their (cold) basic block.
4340///
4341/// The motivation for handling sinking into cold blocks is that doing so can
4342/// both enable other address mode sinking (by satisfying the register pressure
4343/// constraint above), and reduce register pressure globally (by removing the
4344/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004345bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004346 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004347 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004348
4349 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004350 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004351 SmallVector<Value*, 8> worklist;
4352 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004353 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004354
John Brawneb83c752017-10-03 13:04:15 +00004355 // Use a worklist to iteratively look through PHI and select nodes, and
4356 // ensure that the addressing mode obtained from the non-PHI/select roots of
John Brawn736bf002017-10-03 13:08:22 +00004357 // the graph are compatible.
John Brawneb83c752017-10-03 13:04:15 +00004358 bool PhiOrSelectSeen = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004359 SmallVector<Instruction*, 16> AddrModeInsts;
Serguei Katkovaee63752017-11-05 07:59:02 +00004360 const SimplifyQuery SQ(*DL, TLInfo);
4361 AddressingModeCombiner AddrModes(SQ, { Addr, MemoryInst->getParent() });
Jun Bum Limdee55652017-04-03 19:20:07 +00004362 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004363 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4364 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004365 while (!worklist.empty()) {
4366 Value *V = worklist.back();
4367 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004368
Serguei Katkov4ea855e2017-07-19 04:49:17 +00004369 // We allow traversing cyclic Phi nodes.
4370 // In case of success after this loop we ensure that traversing through
4371 // Phi nodes ends up with all cases to compute address of the form
4372 // BaseGV + Base + Scale * Index + Offset
4373 // where Scale and Offset are constans and BaseGV, Base and Index
4374 // are exactly the same Values in all cases.
4375 // It means that BaseGV, Scale and Offset dominate our memory instruction
4376 // and have the same value as they had in address computation represented
4377 // as Phi. So we can safely sink address computation to memory instruction.
4378 if (!Visited.insert(V).second)
4379 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00004380
Owen Anderson8ba5f392010-11-27 08:15:55 +00004381 // For a PHI node, push all of its incoming values.
4382 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004383 for (Value *IncValue : P->incoming_values())
4384 worklist.push_back(IncValue);
John Brawneb83c752017-10-03 13:04:15 +00004385 PhiOrSelectSeen = true;
4386 continue;
4387 }
4388 // Similar for select.
4389 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4390 worklist.push_back(SI->getFalseValue());
4391 worklist.push_back(SI->getTrueValue());
4392 PhiOrSelectSeen = true;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004393 continue;
4394 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004395
Philip Reamesac115ed2016-03-09 23:13:12 +00004396 // For non-PHIs, determine the addressing mode being computed. Note that
4397 // the result may differ depending on what other uses our candidate
4398 // addressing instructions might have.
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004399 AddrModeInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004400 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004401 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
4402 InsertedInsts, PromotedInsts, TPT);
John Brawn736bf002017-10-03 13:08:22 +00004403 NewAddrMode.OriginalValue = V;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004404
John Brawn736bf002017-10-03 13:08:22 +00004405 if (!AddrModes.addNewAddrMode(NewAddrMode))
4406 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004407 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004408
John Brawn736bf002017-10-03 13:08:22 +00004409 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4410 // or we have multiple but either couldn't combine them or combining them
4411 // wouldn't do anything useful, bail out now.
4412 if (!AddrModes.combineAddrModes()) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004413 TPT.rollback(LastKnownGood);
4414 return false;
4415 }
4416 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004417
John Brawn736bf002017-10-03 13:08:22 +00004418 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4419 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4420
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004421 // If all the instructions matched are already in this BB, don't do anything.
John Brawneb83c752017-10-03 13:04:15 +00004422 // If we saw a Phi node then it is not local definitely, and if we saw a select
4423 // then we want to push the address calculation past it even if it's already
4424 // in this BB.
4425 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
Justin Lebar838c7f52016-11-21 22:49:11 +00004426 return IsNonLocalValue(V, MemoryInst->getParent());
Serguei Katkov0b7b59a2017-07-11 06:24:44 +00004427 })) {
David Greene74e2d492010-01-05 01:27:11 +00004428 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004429 return false;
4430 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004431
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004432 // Insert this computation right after this user. Since our caller is
4433 // scanning from the top of the BB to the bottom, reuse of the expr are
4434 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004435 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004436
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004437 // Now that we determined the addressing expression we want to use and know
4438 // that we have to sink it into this block. Check to see if we have already
4439 // done this for some other load/store instr in this block. If so, reuse the
Simon Dardis82221602017-11-13 16:41:17 +00004440 // computation.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004441 Value *&SunkAddr = SunkAddrs[Addr];
4442 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00004443 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004444 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004445 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004446 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004447 } else if (AddrSinkUsingGEPs ||
4448 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004449 SubtargetInfo->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004450 // By default, we use the GEP-based method when AA is used later. This
4451 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4452 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004453 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004454 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004455 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004456
4457 // First, find the pointer.
4458 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4459 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004460 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004461 }
4462
4463 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4464 // We can't add more than one pointer together, nor can we scale a
4465 // pointer (both of which seem meaningless).
4466 if (ResultPtr || AddrMode.Scale != 1)
4467 return false;
4468
4469 ResultPtr = AddrMode.ScaledReg;
4470 AddrMode.Scale = 0;
4471 }
4472
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004473 // It is only safe to sign extend the BaseReg if we know that the math
4474 // required to create it did not overflow before we extend it. Since
4475 // the original IR value was tossed in favor of a constant back when
4476 // the AddrMode was created we need to bail out gracefully if widths
4477 // do not match instead of extending it.
4478 //
4479 // (See below for code to add the scale.)
4480 if (AddrMode.Scale) {
4481 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4482 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4483 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4484 return false;
4485 }
4486
Hal Finkelc3998302014-04-12 00:59:48 +00004487 if (AddrMode.BaseGV) {
4488 if (ResultPtr)
4489 return false;
4490
4491 ResultPtr = AddrMode.BaseGV;
4492 }
4493
4494 // If the real base value actually came from an inttoptr, then the matcher
4495 // will look through it and provide only the integer value. In that case,
4496 // use it here.
Keno Fischer05e4ac22017-06-29 20:28:59 +00004497 if (!DL->isNonIntegralPointerType(Addr->getType())) {
4498 if (!ResultPtr && AddrMode.BaseReg) {
4499 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4500 "sunkaddr");
4501 AddrMode.BaseReg = nullptr;
4502 } else if (!ResultPtr && AddrMode.Scale == 1) {
4503 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4504 "sunkaddr");
4505 AddrMode.Scale = 0;
4506 }
Hal Finkelc3998302014-04-12 00:59:48 +00004507 }
4508
4509 if (!ResultPtr &&
4510 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4511 SunkAddr = Constant::getNullValue(Addr->getType());
4512 } else if (!ResultPtr) {
4513 return false;
4514 } else {
4515 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004516 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4517 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004518
4519 // Start with the base register. Do this first so that subsequent address
4520 // matching finds it last, which will prevent it from trying to match it
4521 // as the scaled value in case it happens to be a mul. That would be
4522 // problematic if we've sunk a different mul for the scale, because then
4523 // we'd end up sinking both muls.
4524 if (AddrMode.BaseReg) {
4525 Value *V = AddrMode.BaseReg;
4526 if (V->getType() != IntPtrTy)
4527 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4528
4529 ResultIndex = V;
4530 }
4531
4532 // Add the scale value.
4533 if (AddrMode.Scale) {
4534 Value *V = AddrMode.ScaledReg;
4535 if (V->getType() == IntPtrTy) {
4536 // done.
Hal Finkelc3998302014-04-12 00:59:48 +00004537 } else {
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004538 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4539 cast<IntegerType>(V->getType())->getBitWidth() &&
4540 "We can't transform if ScaledReg is too narrow");
4541 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004542 }
4543
4544 if (AddrMode.Scale != 1)
4545 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4546 "sunkaddr");
4547 if (ResultIndex)
4548 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4549 else
4550 ResultIndex = V;
4551 }
4552
4553 // Add in the Base Offset if present.
4554 if (AddrMode.BaseOffs) {
4555 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4556 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004557 // We need to add this separately from the scale above to help with
4558 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004559 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004560 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004561 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004562 }
4563
4564 ResultIndex = V;
4565 }
4566
4567 if (!ResultIndex) {
4568 SunkAddr = ResultPtr;
4569 } else {
4570 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004571 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004572 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004573 }
4574
4575 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004576 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004577 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004578 } else {
Keno Fischer05e4ac22017-06-29 20:28:59 +00004579 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4580 // non-integral pointers, so in that case bail out now.
4581 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4582 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4583 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4584 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4585 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4586 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4587 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4588 (AddrMode.BaseGV &&
4589 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4590 return false;
4591
David Greene74e2d492010-01-05 01:27:11 +00004592 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004593 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004594 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004595 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004596
4597 // Start with the base register. Do this first so that subsequent address
4598 // matching finds it last, which will prevent it from trying to match it
4599 // as the scaled value in case it happens to be a mul. That would be
4600 // problematic if we've sunk a different mul for the scale, because then
4601 // we'd end up sinking both muls.
4602 if (AddrMode.BaseReg) {
4603 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004604 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004605 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004606 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004607 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004608 Result = V;
4609 }
4610
4611 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004612 if (AddrMode.Scale) {
4613 Value *V = AddrMode.ScaledReg;
4614 if (V->getType() == IntPtrTy) {
4615 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004616 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004617 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004618 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4619 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004620 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004621 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004622 // It is only safe to sign extend the BaseReg if we know that the math
4623 // required to create it did not overflow before we extend it. Since
4624 // the original IR value was tossed in favor of a constant back when
4625 // the AddrMode was created we need to bail out gracefully if widths
4626 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004627 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004628 if (I && (Result != AddrMode.BaseReg))
4629 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004630 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004631 }
4632 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004633 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4634 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004635 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004636 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004637 else
4638 Result = V;
4639 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004640
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004641 // Add in the BaseGV if present.
4642 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004643 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004644 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004645 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004646 else
4647 Result = V;
4648 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004649
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004650 // Add in the Base Offset if present.
4651 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004652 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004653 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004654 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004655 else
4656 Result = V;
4657 }
4658
Craig Topperc0196b12014-04-14 00:51:57 +00004659 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004660 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004661 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004662 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004663 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004664
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004665 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004666
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004667 // If we have no uses, recursively delete the value and all dead instructions
4668 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004669 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004670 // This can cause recursive deletion, which can invalidate our iterator.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004671 // Use a WeakTrackingVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004672 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004673 WeakTrackingVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004674 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004675
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004676 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004677
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004678 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004679 // If the iterator instruction was recursively deleted, start over at the
4680 // start of the block.
4681 CurInstIterator = BB->begin();
4682 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004683 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004684 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004685 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004686 return true;
4687}
4688
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004689/// If there are any memory operands, use OptimizeMemoryInst to sink their
4690/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004691bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004692 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004693
Eric Christopher11e4df72015-02-26 22:38:43 +00004694 const TargetRegisterInfo *TRI =
Sanjay Patel4137d512017-06-07 14:29:52 +00004695 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004696 TargetLowering::AsmOperandInfoVector TargetConstraints =
4697 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004698 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004699 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4700 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004701
Evan Cheng1da25002008-02-26 02:42:37 +00004702 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004703 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004704
Eli Friedman666bbe32008-02-26 18:37:49 +00004705 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4706 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004707 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004708 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004709 } else if (OpInfo.Type == InlineAsm::isInput)
4710 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004711 }
4712
4713 return MadeChange;
4714}
4715
Jun Bum Lim42301012017-03-17 19:05:21 +00004716/// \brief Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004717/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00004718static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4719 assert(!Val->use_empty() && "Input must have at least one use");
4720 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004721 bool IsSExt = isa<SExtInst>(FirstUser);
4722 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00004723 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004724 const Instruction *UI = cast<Instruction>(U);
4725 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4726 return false;
4727 Type *CurTy = UI->getType();
4728 // Same input and output types: Same instruction after CSE.
4729 if (CurTy == ExtTy)
4730 continue;
4731
4732 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00004733 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004734 // b = sext ty1 a to ty2
4735 // c = sext ty1 a to ty3
4736 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00004737 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004738 // b = sext ty1 a to ty2
4739 // c = sext ty2 b to ty3
4740 // However, the last sext is not free.
4741 if (IsSExt)
4742 return false;
4743
4744 // This is a ZExt, maybe this is free to extend from one type to another.
4745 // In that case, we would not account for a different use.
4746 Type *NarrowTy;
4747 Type *LargeTy;
4748 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4749 CurTy->getScalarType()->getIntegerBitWidth()) {
4750 NarrowTy = CurTy;
4751 LargeTy = ExtTy;
4752 } else {
4753 NarrowTy = ExtTy;
4754 LargeTy = CurTy;
4755 }
4756
4757 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4758 return false;
4759 }
4760 // All uses are the same or can be derived from one another for free.
4761 return true;
4762}
4763
Jun Bum Lim42301012017-03-17 19:05:21 +00004764/// \brief Try to speculatively promote extensions in \p Exts and continue
4765/// promoting through newly promoted operands recursively as far as doing so is
4766/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4767/// When some promotion happened, \p TPT contains the proper state to revert
4768/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004769///
Jun Bum Lim42301012017-03-17 19:05:21 +00004770/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00004771bool CodeGenPrepare::tryToPromoteExts(
4772 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4773 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4774 unsigned CreatedInstsCost) {
4775 bool Promoted = false;
4776
4777 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004778 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004779 // Early check if we directly have ext(load).
4780 if (isa<LoadInst>(I->getOperand(0))) {
4781 ProfitablyMovedExts.push_back(I);
4782 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004783 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004784
4785 // Check whether or not we want to do any promotion. The reason we have
4786 // this check inside the for loop is to catch the case where an extension
4787 // is directly fed by a load because in such case the extension can be moved
4788 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004789 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00004790 return false;
4791
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004792 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00004793 TypePromotionHelper::Action TPH =
4794 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004795 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00004796 if (!TPH) {
4797 // Save the current extension as we cannot move up through its operand.
4798 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004799 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00004800 }
4801
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004802 // Save the current state.
4803 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4804 TPT.getRestorationPoint();
4805 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004806 unsigned NewCreatedInstsCost = 0;
4807 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004808 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004809 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4810 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004811 assert(PromotedVal &&
4812 "TypePromotionHelper should have filtered out those cases");
4813
4814 // We would be able to merge only one extension in a load.
4815 // Therefore, if we have more than 1 new extension we heuristically
4816 // cut this search path, because it means we degrade the code quality.
4817 // With exactly 2, the transformation is neutral, because we will merge
4818 // one extension but leave one. However, we optimistically keep going,
4819 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004820 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004821 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00004822 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004823 TotalCreatedInstsCost =
4824 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004825 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004826 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004827 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004828 // This promotion is not profitable, rollback to the previous state, and
4829 // save the current extension in ProfitablyMovedExts as the latest
4830 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004831 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00004832 ProfitablyMovedExts.push_back(I);
4833 continue;
4834 }
4835 // Continue promoting NewExts as far as doing so is profitable.
4836 SmallVector<Instruction *, 2> NewlyMovedExts;
4837 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4838 bool NewPromoted = false;
4839 for (auto ExtInst : NewlyMovedExts) {
4840 Instruction *MovedExt = cast<Instruction>(ExtInst);
4841 Value *ExtOperand = MovedExt->getOperand(0);
4842 // If we have reached to a load, we need this extra profitability check
4843 // as it could potentially be merged into an ext(load).
4844 if (isa<LoadInst>(ExtOperand) &&
4845 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4846 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
4847 continue;
4848
4849 ProfitablyMovedExts.push_back(MovedExt);
4850 NewPromoted = true;
4851 }
4852
4853 // If none of speculative promotions for NewExts is profitable, rollback
4854 // and save the current extension (I) as the last profitable extension.
4855 if (!NewPromoted) {
4856 TPT.rollback(LastKnownGood);
4857 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004858 continue;
4859 }
4860 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00004861 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004862 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004863 return Promoted;
4864}
4865
Jun Bum Limdee55652017-04-03 19:20:07 +00004866/// Merging redundant sexts when one is dominating the other.
4867bool CodeGenPrepare::mergeSExts(Function &F) {
4868 DominatorTree DT(F);
4869 bool Changed = false;
4870 for (auto &Entry : ValToSExtendedUses) {
4871 SExts &Insts = Entry.second;
4872 SExts CurPts;
4873 for (Instruction *Inst : Insts) {
4874 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
4875 Inst->getOperand(0) != Entry.first)
4876 continue;
4877 bool inserted = false;
4878 for (auto &Pt : CurPts) {
4879 if (DT.dominates(Inst, Pt)) {
4880 Pt->replaceAllUsesWith(Inst);
4881 RemovedInsts.insert(Pt);
4882 Pt->removeFromParent();
4883 Pt = Inst;
4884 inserted = true;
4885 Changed = true;
4886 break;
4887 }
4888 if (!DT.dominates(Pt, Inst))
4889 // Give up if we need to merge in a common dominator as the
4890 // expermients show it is not profitable.
4891 continue;
4892 Inst->replaceAllUsesWith(Pt);
4893 RemovedInsts.insert(Inst);
4894 Inst->removeFromParent();
4895 inserted = true;
4896 Changed = true;
4897 break;
4898 }
4899 if (!inserted)
4900 CurPts.push_back(Inst);
4901 }
4902 }
4903 return Changed;
4904}
4905
Jun Bum Lim42301012017-03-17 19:05:21 +00004906/// Return true, if an ext(load) can be formed from an extension in
4907/// \p MovedExts.
4908bool CodeGenPrepare::canFormExtLd(
4909 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
4910 Instruction *&Inst, bool HasPromoted) {
4911 for (auto *MovedExtInst : MovedExts) {
4912 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
4913 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
4914 Inst = MovedExtInst;
4915 break;
4916 }
4917 }
4918 if (!LI)
4919 return false;
4920
4921 // If they're already in the same block, there's nothing to do.
4922 // Make the cheap checks first if we did not promote.
4923 // If we promoted, we need to check if it is indeed profitable.
4924 if (!HasPromoted && LI->getParent() == Inst->getParent())
4925 return false;
4926
Haicheng Wuabdef9e2017-07-15 02:12:16 +00004927 return TLI->isExtLoad(LI, Inst, *DL);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004928}
4929
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004930/// Move a zext or sext fed by a load into the same basic block as the load,
4931/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4932/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00004933///
Jun Bum Limdee55652017-04-03 19:20:07 +00004934/// E.g.,
4935/// \code
4936/// %ld = load i32* %addr
4937/// %add = add nuw i32 %ld, 4
4938/// %zext = zext i32 %add to i64
4939// \endcode
4940/// =>
4941/// \code
4942/// %ld = load i32* %addr
4943/// %zext = zext i32 %ld to i64
4944/// %add = add nuw i64 %zext, 4
4945/// \encode
4946/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
4947/// allow us to match zext(load i32*) to i64.
4948///
4949/// Also, try to promote the computations used to obtain a sign extended
4950/// value used into memory accesses.
4951/// E.g.,
4952/// \code
4953/// a = add nsw i32 b, 3
4954/// d = sext i32 a to i64
4955/// e = getelementptr ..., i64 d
4956/// \endcode
4957/// =>
4958/// \code
4959/// f = sext i32 b to i64
4960/// a = add nsw i64 f, 3
4961/// e = getelementptr ..., i64 a
4962/// \endcode
4963///
4964/// \p Inst[in/out] the extension may be modified during the process if some
4965/// promotions apply.
4966bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
4967 // ExtLoad formation and address type promotion infrastructure requires TLI to
4968 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00004969 if (!TLI)
4970 return false;
4971
Jun Bum Limdee55652017-04-03 19:20:07 +00004972 bool AllowPromotionWithoutCommonHeader = false;
4973 /// See if it is an interesting sext operations for the address type
4974 /// promotion before trying to promote it, e.g., the ones with the right
4975 /// type and used in memory accesses.
4976 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
4977 *Inst, AllowPromotionWithoutCommonHeader);
4978 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004979 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00004980 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004981 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00004982 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
4983 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00004984
Jun Bum Limdee55652017-04-03 19:20:07 +00004985 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00004986
Dan Gohman99429a02009-10-16 20:59:35 +00004987 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004988 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00004989 Instruction *ExtFedByLoad;
4990
4991 // Try to promote a chain of computation if it allows to form an extended
4992 // load.
4993 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
4994 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
4995 TPT.commit();
4996 // Move the extend into the same block as the load
Sanjay Patel674d2c22017-08-29 14:07:48 +00004997 ExtFedByLoad->moveAfter(LI);
Jun Bum Limdee55652017-04-03 19:20:07 +00004998 // CGP does not check if the zext would be speculatively executed when moved
4999 // to the same basic block as the load. Preserving its original location
5000 // would pessimize the debugging experience, as well as negatively impact
5001 // the quality of sample pgo. We don't want to use "line 0" as that has a
5002 // size cost in the line-table section and logically the zext can be seen as
5003 // part of the load. Therefore we conservatively reuse the same debug
5004 // location for the load and the zext.
5005 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
5006 ++NumExtsMoved;
5007 Inst = ExtFedByLoad;
5008 return true;
5009 }
5010
5011 // Continue promoting SExts if known as considerable depending on targets.
5012 if (ATPConsiderable &&
5013 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
5014 HasPromoted, TPT, SpeculativelyMovedExts))
5015 return true;
5016
5017 TPT.rollback(LastKnownGood);
5018 return false;
5019}
5020
5021// Perform address type promotion if doing so is profitable.
5022// If AllowPromotionWithoutCommonHeader == false, we should find other sext
5023// instructions that sign extended the same initial value. However, if
5024// AllowPromotionWithoutCommonHeader == true, we expect promoting the
5025// extension is just profitable.
5026bool CodeGenPrepare::performAddressTypePromotion(
5027 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
5028 bool HasPromoted, TypePromotionTransaction &TPT,
5029 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
5030 bool Promoted = false;
5031 SmallPtrSet<Instruction *, 1> UnhandledExts;
5032 bool AllSeenFirst = true;
5033 for (auto I : SpeculativelyMovedExts) {
5034 Value *HeadOfChain = I->getOperand(0);
5035 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
5036 SeenChainsForSExt.find(HeadOfChain);
5037 // If there is an unhandled SExt which has the same header, try to promote
5038 // it as well.
5039 if (AlreadySeen != SeenChainsForSExt.end()) {
5040 if (AlreadySeen->second != nullptr)
5041 UnhandledExts.insert(AlreadySeen->second);
5042 AllSeenFirst = false;
5043 }
5044 }
5045
5046 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
5047 SpeculativelyMovedExts.size() == 1)) {
5048 TPT.commit();
5049 if (HasPromoted)
5050 Promoted = true;
5051 for (auto I : SpeculativelyMovedExts) {
5052 Value *HeadOfChain = I->getOperand(0);
5053 SeenChainsForSExt[HeadOfChain] = nullptr;
5054 ValToSExtendedUses[HeadOfChain].push_back(I);
5055 }
5056 // Update Inst as promotion happen.
5057 Inst = SpeculativelyMovedExts.pop_back_val();
5058 } else {
5059 // This is the first chain visited from the header, keep the current chain
5060 // as unhandled. Defer to promote this until we encounter another SExt
5061 // chain derived from the same header.
5062 for (auto I : SpeculativelyMovedExts) {
5063 Value *HeadOfChain = I->getOperand(0);
5064 SeenChainsForSExt[HeadOfChain] = Inst;
5065 }
Dan Gohman99429a02009-10-16 20:59:35 +00005066 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005067 }
Dan Gohman99429a02009-10-16 20:59:35 +00005068
Jun Bum Limdee55652017-04-03 19:20:07 +00005069 if (!AllSeenFirst && !UnhandledExts.empty())
5070 for (auto VisitedSExt : UnhandledExts) {
5071 if (RemovedInsts.count(VisitedSExt))
5072 continue;
5073 TypePromotionTransaction TPT(RemovedInsts);
5074 SmallVector<Instruction *, 1> Exts;
5075 SmallVector<Instruction *, 2> Chains;
5076 Exts.push_back(VisitedSExt);
5077 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
5078 TPT.commit();
5079 if (HasPromoted)
5080 Promoted = true;
5081 for (auto I : Chains) {
5082 Value *HeadOfChain = I->getOperand(0);
5083 // Mark this as handled.
5084 SeenChainsForSExt[HeadOfChain] = nullptr;
5085 ValToSExtendedUses[HeadOfChain].push_back(I);
5086 }
5087 }
5088 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00005089}
5090
Sanjay Patelfc580a62015-09-21 23:03:16 +00005091bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00005092 BasicBlock *DefBB = I->getParent();
5093
Bob Wilsonff714f92010-09-21 21:44:14 +00005094 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00005095 // other uses of the source with result of extension.
5096 Value *Src = I->getOperand(0);
5097 if (Src->hasOneUse())
5098 return false;
5099
Evan Cheng2011df42007-12-13 07:50:36 +00005100 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00005101 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00005102 return false;
5103
Evan Cheng7bc89422007-12-12 00:51:06 +00005104 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00005105 // this block.
5106 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00005107 return false;
5108
Evan Chengd3d80172007-12-05 23:58:20 +00005109 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005110 for (User *U : I->users()) {
5111 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00005112
5113 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005114 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00005115 if (UserBB == DefBB) continue;
5116 DefIsLiveOut = true;
5117 break;
5118 }
5119 if (!DefIsLiveOut)
5120 return false;
5121
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00005122 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005123 for (User *U : Src->users()) {
5124 Instruction *UI = cast<Instruction>(U);
5125 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00005126 if (UserBB == DefBB) continue;
5127 // Be conservative. We don't want this xform to end up introducing
5128 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005129 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00005130 return false;
5131 }
5132
Evan Chengd3d80172007-12-05 23:58:20 +00005133 // InsertedTruncs - Only insert one trunc in each block once.
5134 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5135
5136 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005137 for (Use &U : Src->uses()) {
5138 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00005139
5140 // Figure out which BB this ext is used in.
5141 BasicBlock *UserBB = User->getParent();
5142 if (UserBB == DefBB) continue;
5143
5144 // Both src and def are live in this block. Rewrite the use.
5145 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5146
5147 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00005148 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005149 assert(InsertPt != UserBB->end());
5150 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005151 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00005152 }
5153
5154 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005155 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00005156 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00005157 MadeChange = true;
5158 }
5159
5160 return MadeChange;
5161}
5162
Geoff Berry5256fca2015-11-20 22:34:39 +00005163// Find loads whose uses only use some of the loaded value's bits. Add an "and"
5164// just after the load if the target can fold this into one extload instruction,
5165// with the hope of eliminating some of the other later "and" instructions using
5166// the loaded value. "and"s that are made trivially redundant by the insertion
5167// of the new "and" are removed by this function, while others (e.g. those whose
5168// path from the load goes through a phi) are left for isel to potentially
5169// remove.
5170//
5171// For example:
5172//
5173// b0:
5174// x = load i32
5175// ...
5176// b1:
5177// y = and x, 0xff
5178// z = use y
5179//
5180// becomes:
5181//
5182// b0:
5183// x = load i32
5184// x' = and x, 0xff
5185// ...
5186// b1:
5187// z = use x'
5188//
5189// whereas:
5190//
5191// b0:
5192// x1 = load i32
5193// ...
5194// b1:
5195// x2 = load i32
5196// ...
5197// b2:
5198// x = phi x1, x2
5199// y = and x, 0xff
5200//
5201// becomes (after a call to optimizeLoadExt for each load):
5202//
5203// b0:
5204// x1 = load i32
5205// x1' = and x1, 0xff
5206// ...
5207// b1:
5208// x2 = load i32
5209// x2' = and x2, 0xff
5210// ...
5211// b2:
5212// x = phi x1', x2'
5213// y = and x, 0xff
Geoff Berry5256fca2015-11-20 22:34:39 +00005214bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005215 if (!Load->isSimple() ||
5216 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5217 return false;
5218
Geoff Berry5d534b62017-02-21 18:53:14 +00005219 // Skip loads we've already transformed.
5220 if (Load->hasOneUse() &&
5221 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5222 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005223
5224 // Look at all uses of Load, looking through phis, to determine how many bits
5225 // of the loaded value are needed.
5226 SmallVector<Instruction *, 8> WorkList;
5227 SmallPtrSet<Instruction *, 16> Visited;
5228 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5229 for (auto *U : Load->users())
5230 WorkList.push_back(cast<Instruction>(U));
5231
5232 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5233 unsigned BitWidth = LoadResultVT.getSizeInBits();
5234 APInt DemandBits(BitWidth, 0);
5235 APInt WidestAndBits(BitWidth, 0);
5236
5237 while (!WorkList.empty()) {
5238 Instruction *I = WorkList.back();
5239 WorkList.pop_back();
5240
5241 // Break use-def graph loops.
5242 if (!Visited.insert(I).second)
5243 continue;
5244
5245 // For a PHI node, push all of its users.
5246 if (auto *Phi = dyn_cast<PHINode>(I)) {
5247 for (auto *U : Phi->users())
5248 WorkList.push_back(cast<Instruction>(U));
5249 continue;
5250 }
5251
5252 switch (I->getOpcode()) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005253 case Instruction::And: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005254 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5255 if (!AndC)
5256 return false;
5257 APInt AndBits = AndC->getValue();
5258 DemandBits |= AndBits;
5259 // Keep track of the widest and mask we see.
5260 if (AndBits.ugt(WidestAndBits))
5261 WidestAndBits = AndBits;
5262 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5263 AndsToMaybeRemove.push_back(I);
5264 break;
5265 }
5266
Eugene Zelenko900b6332017-08-29 22:32:07 +00005267 case Instruction::Shl: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005268 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5269 if (!ShlC)
5270 return false;
5271 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00005272 DemandBits.setLowBits(BitWidth - ShiftAmt);
Geoff Berry5256fca2015-11-20 22:34:39 +00005273 break;
5274 }
5275
Eugene Zelenko900b6332017-08-29 22:32:07 +00005276 case Instruction::Trunc: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005277 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5278 unsigned TruncBitWidth = TruncVT.getSizeInBits();
Craig Topperfc947bc2017-04-18 17:14:21 +00005279 DemandBits.setLowBits(TruncBitWidth);
Geoff Berry5256fca2015-11-20 22:34:39 +00005280 break;
5281 }
5282
5283 default:
5284 return false;
5285 }
5286 }
5287
5288 uint32_t ActiveBits = DemandBits.getActiveBits();
5289 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5290 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5291 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5292 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5293 // followed by an AND.
5294 // TODO: Look into removing this restriction by fixing backends to either
5295 // return false for isLoadExtLegal for i1 or have them select this pattern to
5296 // a single instruction.
5297 //
5298 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5299 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005300 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005301 WidestAndBits != DemandBits)
5302 return false;
5303
5304 LLVMContext &Ctx = Load->getType()->getContext();
5305 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5306 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5307
5308 // Reject cases that won't be matched as extloads.
5309 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5310 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5311 return false;
5312
5313 IRBuilder<> Builder(Load->getNextNode());
5314 auto *NewAnd = dyn_cast<Instruction>(
5315 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005316 // Mark this instruction as "inserted by CGP", so that other
5317 // optimizations don't touch it.
5318 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005319
5320 // Replace all uses of load with new and (except for the use of load in the
5321 // new and itself).
5322 Load->replaceAllUsesWith(NewAnd);
5323 NewAnd->setOperand(0, Load);
5324
5325 // Remove any and instructions that are now redundant.
5326 for (auto *And : AndsToMaybeRemove)
5327 // Check that the and mask is the same as the one we decided to put on the
5328 // new and.
5329 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5330 And->replaceAllUsesWith(NewAnd);
5331 if (&*CurInstIterator == And)
5332 CurInstIterator = std::next(And->getIterator());
5333 And->eraseFromParent();
5334 ++NumAndUses;
5335 }
5336
5337 ++NumAndsAdded;
5338 return true;
5339}
5340
Sanjay Patel69a50a12015-10-19 21:59:12 +00005341/// Check if V (an operand of a select instruction) is an expensive instruction
5342/// that is only used once.
5343static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5344 auto *I = dyn_cast<Instruction>(V);
5345 // If it's safe to speculatively execute, then it should not have side
5346 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005347 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5348 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005349}
5350
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005351/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005352static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005353 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005354 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005355 // If even a predictable select is cheap, then a branch can't be cheaper.
5356 if (!TLI->isPredictableSelectExpensive())
5357 return false;
5358
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005359 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005360 // whether a select is better represented as a branch.
5361
5362 // If metadata tells us that the select condition is obviously predictable,
5363 // then we want to replace the select with a branch.
5364 uint64_t TrueWeight, FalseWeight;
5365 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5366 uint64_t Max = std::max(TrueWeight, FalseWeight);
5367 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005368 if (Sum != 0) {
5369 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5370 if (Probability > TLI->getPredictableBranchThreshold())
5371 return true;
5372 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005373 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005374
5375 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5376
Sanjay Patel4e652762015-09-28 22:14:51 +00005377 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5378 // comparison condition. If the compare has more than one use, there's
5379 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005380 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005381 return false;
5382
Sanjay Patel69a50a12015-10-19 21:59:12 +00005383 // If either operand of the select is expensive and only needed on one side
5384 // of the select, we should form a branch.
5385 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5386 sinkSelectOperand(TTI, SI->getFalseValue()))
5387 return true;
5388
5389 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005390}
5391
Dehao Chen9bbb9412016-09-12 20:23:28 +00005392/// If \p isTrue is true, return the true value of \p SI, otherwise return
5393/// false value of \p SI. If the true/false value of \p SI is defined by any
5394/// select instructions in \p Selects, look through the defining select
5395/// instruction until the true/false value is not defined in \p Selects.
5396static Value *getTrueOrFalseValue(
5397 SelectInst *SI, bool isTrue,
5398 const SmallPtrSet<const Instruction *, 2> &Selects) {
5399 Value *V;
5400
5401 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5402 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005403 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005404 "The condition of DefSI does not match with SI");
5405 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5406 }
5407 return V;
5408}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005409
Nadav Rotem9d832022012-09-02 12:10:19 +00005410/// If we have a SelectInst that will likely profit from branch prediction,
5411/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005412bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00005413 // Find all consecutive select instructions that share the same condition.
5414 SmallVector<SelectInst *, 2> ASI;
5415 ASI.push_back(SI);
5416 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5417 It != SI->getParent()->end(); ++It) {
5418 SelectInst *I = dyn_cast<SelectInst>(&*It);
5419 if (I && SI->getCondition() == I->getCondition()) {
5420 ASI.push_back(I);
5421 } else {
5422 break;
5423 }
5424 }
5425
5426 SelectInst *LastSI = ASI.back();
5427 // Increment the current iterator to skip all the rest of select instructions
5428 // because they will be either "not lowered" or "all lowered" to branch.
5429 CurInstIterator = std::next(LastSI->getIterator());
5430
Nadav Rotem9d832022012-09-02 12:10:19 +00005431 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5432
5433 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00005434 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
5435 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005436 return false;
5437
Nadav Rotem9d832022012-09-02 12:10:19 +00005438 TargetLowering::SelectSupportKind SelectKind;
5439 if (VectorCond)
5440 SelectKind = TargetLowering::VectorMaskSelect;
5441 else if (SI->getType()->isVectorTy())
5442 SelectKind = TargetLowering::ScalarCondVectorVal;
5443 else
5444 SelectKind = TargetLowering::ScalarValSelect;
5445
Sanjay Pateld66607b2016-04-26 17:11:17 +00005446 if (TLI->isSelectSupported(SelectKind) &&
5447 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5448 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005449
5450 ModifiedDT = true;
5451
Sanjay Patel69a50a12015-10-19 21:59:12 +00005452 // Transform a sequence like this:
5453 // start:
5454 // %cmp = cmp uge i32 %a, %b
5455 // %sel = select i1 %cmp, i32 %c, i32 %d
5456 //
5457 // Into:
5458 // start:
5459 // %cmp = cmp uge i32 %a, %b
5460 // br i1 %cmp, label %select.true, label %select.false
5461 // select.true:
5462 // br label %select.end
5463 // select.false:
5464 // br label %select.end
5465 // select.end:
5466 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5467 //
5468 // In addition, we may sink instructions that produce %c or %d from
5469 // the entry block into the destination(s) of the new branch.
5470 // If the true or false blocks do not contain a sunken instruction, that
5471 // block and its branch may be optimized away. In that case, one side of the
5472 // first branch will point directly to select.end, and the corresponding PHI
5473 // predecessor block will be the start block.
5474
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005475 // First, we split the block containing the select into 2 blocks.
5476 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005477 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005478 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005479
Sanjay Patel69a50a12015-10-19 21:59:12 +00005480 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005481 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005482
5483 // These are the new basic blocks for the conditional branch.
5484 // At least one will become an actual new basic block.
5485 BasicBlock *TrueBlock = nullptr;
5486 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005487 BranchInst *TrueBranch = nullptr;
5488 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005489
5490 // Sink expensive instructions into the conditional blocks to avoid executing
5491 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005492 for (SelectInst *SI : ASI) {
5493 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5494 if (TrueBlock == nullptr) {
5495 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5496 EndBlock->getParent(), EndBlock);
5497 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5498 }
5499 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5500 TrueInst->moveBefore(TrueBranch);
5501 }
5502 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5503 if (FalseBlock == nullptr) {
5504 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5505 EndBlock->getParent(), EndBlock);
5506 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5507 }
5508 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5509 FalseInst->moveBefore(FalseBranch);
5510 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005511 }
5512
5513 // If there was nothing to sink, then arbitrarily choose the 'false' side
5514 // for a new input value to the PHI.
5515 if (TrueBlock == FalseBlock) {
5516 assert(TrueBlock == nullptr &&
5517 "Unexpected basic block transform while optimizing select");
5518
5519 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5520 EndBlock->getParent(), EndBlock);
5521 BranchInst::Create(EndBlock, FalseBlock);
5522 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005523
5524 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005525 // If we did not create a new block for one of the 'true' or 'false' paths
5526 // of the condition, it means that side of the branch goes to the end block
5527 // directly and the path originates from the start block from the point of
5528 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005529 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005530 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005531 TT = EndBlock;
5532 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005533 TrueBlock = StartBlock;
5534 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005535 TT = TrueBlock;
5536 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005537 FalseBlock = StartBlock;
5538 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005539 TT = TrueBlock;
5540 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005541 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005542 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005543
Dehao Chen9bbb9412016-09-12 20:23:28 +00005544 SmallPtrSet<const Instruction *, 2> INS;
5545 INS.insert(ASI.begin(), ASI.end());
5546 // Use reverse iterator because later select may use the value of the
5547 // earlier select, and we need to propagate value through earlier select
5548 // to get the PHI operand.
5549 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5550 SelectInst *SI = *It;
5551 // The select itself is replaced with a PHI Node.
5552 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5553 PN->takeName(SI);
5554 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5555 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00005556
Dehao Chen9bbb9412016-09-12 20:23:28 +00005557 SI->replaceAllUsesWith(PN);
5558 SI->eraseFromParent();
5559 INS.erase(SI);
5560 ++NumSelectsExpanded;
5561 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005562
5563 // Instruct OptimizeBlock to skip to the next block.
5564 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005565 return true;
5566}
5567
Benjamin Kramer573ff362014-03-01 17:24:40 +00005568static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005569 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5570 int SplatElem = -1;
5571 for (unsigned i = 0; i < Mask.size(); ++i) {
5572 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5573 return false;
5574 SplatElem = Mask[i];
5575 }
5576
5577 return true;
5578}
5579
5580/// Some targets have expensive vector shifts if the lanes aren't all the same
5581/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5582/// it's often worth sinking a shufflevector splat down to its use so that
5583/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005584bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005585 BasicBlock *DefBB = SVI->getParent();
5586
5587 // Only do this xform if variable vector shifts are particularly expensive.
5588 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5589 return false;
5590
5591 // We only expect better codegen by sinking a shuffle if we can recognise a
5592 // constant splat.
5593 if (!isBroadcastShuffle(SVI))
5594 return false;
5595
5596 // InsertedShuffles - Only insert a shuffle in each block once.
5597 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5598
5599 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005600 for (User *U : SVI->users()) {
5601 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005602
5603 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005604 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005605 if (UserBB == DefBB) continue;
5606
5607 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005608 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005609
5610 // Everything checks out, sink the shuffle if the user's block doesn't
5611 // already have a copy.
5612 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5613
5614 if (!InsertedShuffle) {
5615 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005616 assert(InsertPt != UserBB->end());
5617 InsertedShuffle =
5618 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5619 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005620 }
5621
Chandler Carruthcdf47882014-03-09 03:16:01 +00005622 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005623 MadeChange = true;
5624 }
5625
5626 // If we removed all uses, nuke the shuffle.
5627 if (SVI->use_empty()) {
5628 SVI->eraseFromParent();
5629 MadeChange = true;
5630 }
5631
5632 return MadeChange;
5633}
5634
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005635bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5636 if (!TLI || !DL)
5637 return false;
5638
5639 Value *Cond = SI->getCondition();
5640 Type *OldType = Cond->getType();
5641 LLVMContext &Context = Cond->getContext();
5642 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5643 unsigned RegWidth = RegType.getSizeInBits();
5644
5645 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5646 return false;
5647
5648 // If the register width is greater than the type width, expand the condition
5649 // of the switch instruction and each case constant to the width of the
5650 // register. By widening the type of the switch condition, subsequent
5651 // comparisons (for case comparisons) will not need to be extended to the
5652 // preferred register width, so we will potentially eliminate N-1 extends,
5653 // where N is the number of cases in the switch.
5654 auto *NewType = Type::getIntNTy(Context, RegWidth);
5655
5656 // Zero-extend the switch condition and case constants unless the switch
5657 // condition is a function argument that is already being sign-extended.
5658 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5659 // everything instead.
5660 Instruction::CastOps ExtType = Instruction::ZExt;
5661 if (auto *Arg = dyn_cast<Argument>(Cond))
5662 if (Arg->hasSExtAttr())
5663 ExtType = Instruction::SExt;
5664
5665 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5666 ExtInst->insertBefore(SI);
5667 SI->setCondition(ExtInst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00005668 for (auto Case : SI->cases()) {
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005669 APInt NarrowConst = Case.getCaseValue()->getValue();
5670 APInt WideConst = (ExtType == Instruction::ZExt) ?
5671 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5672 Case.setValue(ConstantInt::get(Context, WideConst));
5673 }
5674
5675 return true;
5676}
5677
Zaara Syeda3a7578c2017-05-31 17:12:38 +00005678
Quentin Colombetc32615d2014-10-31 17:52:53 +00005679namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005680
Quentin Colombetc32615d2014-10-31 17:52:53 +00005681/// \brief Helper class to promote a scalar operation to a vector one.
5682/// This class is used to move downward extractelement transition.
5683/// E.g.,
5684/// a = vector_op <2 x i32>
5685/// b = extractelement <2 x i32> a, i32 0
5686/// c = scalar_op b
5687/// store c
5688///
5689/// =>
5690/// a = vector_op <2 x i32>
5691/// c = vector_op a (equivalent to scalar_op on the related lane)
5692/// * d = extractelement <2 x i32> c, i32 0
5693/// * store d
5694/// Assuming both extractelement and store can be combine, we get rid of the
5695/// transition.
5696class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005697 /// DataLayout associated with the current module.
5698 const DataLayout &DL;
5699
Quentin Colombetc32615d2014-10-31 17:52:53 +00005700 /// Used to perform some checks on the legality of vector operations.
5701 const TargetLowering &TLI;
5702
5703 /// Used to estimated the cost of the promoted chain.
5704 const TargetTransformInfo &TTI;
5705
5706 /// The transition being moved downwards.
5707 Instruction *Transition;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005708
Quentin Colombetc32615d2014-10-31 17:52:53 +00005709 /// The sequence of instructions to be promoted.
5710 SmallVector<Instruction *, 4> InstsToBePromoted;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005711
Quentin Colombetc32615d2014-10-31 17:52:53 +00005712 /// Cost of combining a store and an extract.
5713 unsigned StoreExtractCombineCost;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005714
Quentin Colombetc32615d2014-10-31 17:52:53 +00005715 /// Instruction that will be combined with the transition.
Eugene Zelenko900b6332017-08-29 22:32:07 +00005716 Instruction *CombineInst = nullptr;
Quentin Colombetc32615d2014-10-31 17:52:53 +00005717
5718 /// \brief The instruction that represents the current end of the transition.
5719 /// Since we are faking the promotion until we reach the end of the chain
5720 /// of computation, we need a way to get the current end of the transition.
5721 Instruction *getEndOfTransition() const {
5722 if (InstsToBePromoted.empty())
5723 return Transition;
5724 return InstsToBePromoted.back();
5725 }
5726
5727 /// \brief Return the index of the original value in the transition.
5728 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5729 /// c, is at index 0.
5730 unsigned getTransitionOriginalValueIdx() const {
5731 assert(isa<ExtractElementInst>(Transition) &&
5732 "Other kind of transitions are not supported yet");
5733 return 0;
5734 }
5735
5736 /// \brief Return the index of the index in the transition.
5737 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5738 /// is at index 1.
5739 unsigned getTransitionIdx() const {
5740 assert(isa<ExtractElementInst>(Transition) &&
5741 "Other kind of transitions are not supported yet");
5742 return 1;
5743 }
5744
5745 /// \brief Get the type of the transition.
5746 /// This is the type of the original value.
5747 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5748 /// transition is <2 x i32>.
5749 Type *getTransitionType() const {
5750 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5751 }
5752
5753 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5754 /// I.e., we have the following sequence:
5755 /// Def = Transition <ty1> a to <ty2>
5756 /// b = ToBePromoted <ty2> Def, ...
5757 /// =>
5758 /// b = ToBePromoted <ty1> a, ...
5759 /// Def = Transition <ty1> ToBePromoted to <ty2>
5760 void promoteImpl(Instruction *ToBePromoted);
5761
5762 /// \brief Check whether or not it is profitable to promote all the
5763 /// instructions enqueued to be promoted.
5764 bool isProfitableToPromote() {
5765 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5766 unsigned Index = isa<ConstantInt>(ValIdx)
5767 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5768 : -1;
5769 Type *PromotedType = getTransitionType();
5770
5771 StoreInst *ST = cast<StoreInst>(CombineInst);
5772 unsigned AS = ST->getPointerAddressSpace();
5773 unsigned Align = ST->getAlignment();
5774 // Check if this store is supported.
5775 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005776 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5777 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005778 // If this is not supported, there is no way we can combine
5779 // the extract with the store.
5780 return false;
5781 }
5782
5783 // The scalar chain of computation has to pay for the transition
5784 // scalar to vector.
5785 // The vector chain has to account for the combining cost.
5786 uint64_t ScalarCost =
5787 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5788 uint64_t VectorCost = StoreExtractCombineCost;
5789 for (const auto &Inst : InstsToBePromoted) {
5790 // Compute the cost.
5791 // By construction, all instructions being promoted are arithmetic ones.
5792 // Moreover, one argument is a constant that can be viewed as a splat
5793 // constant.
5794 Value *Arg0 = Inst->getOperand(0);
5795 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5796 isa<ConstantFP>(Arg0);
5797 TargetTransformInfo::OperandValueKind Arg0OVK =
5798 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5799 : TargetTransformInfo::OK_AnyValue;
5800 TargetTransformInfo::OperandValueKind Arg1OVK =
5801 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5802 : TargetTransformInfo::OK_AnyValue;
5803 ScalarCost += TTI.getArithmeticInstrCost(
5804 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5805 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5806 Arg0OVK, Arg1OVK);
5807 }
5808 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5809 << ScalarCost << "\nVector: " << VectorCost << '\n');
5810 return ScalarCost > VectorCost;
5811 }
5812
5813 /// \brief Generate a constant vector with \p Val with the same
5814 /// number of elements as the transition.
5815 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005816 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005817 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5818 /// otherwise we generate a vector with as many undef as possible:
5819 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5820 /// used at the index of the extract.
5821 Value *getConstantVector(Constant *Val, bool UseSplat) const {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005822 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00005823 if (!UseSplat) {
5824 // If we cannot determine where the constant must be, we have to
5825 // use a splat constant.
5826 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5827 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5828 ExtractIdx = CstVal->getSExtValue();
5829 else
5830 UseSplat = true;
5831 }
5832
5833 unsigned End = getTransitionType()->getVectorNumElements();
5834 if (UseSplat)
5835 return ConstantVector::getSplat(End, Val);
5836
5837 SmallVector<Constant *, 4> ConstVec;
5838 UndefValue *UndefVal = UndefValue::get(Val->getType());
5839 for (unsigned Idx = 0; Idx != End; ++Idx) {
5840 if (Idx == ExtractIdx)
5841 ConstVec.push_back(Val);
5842 else
5843 ConstVec.push_back(UndefVal);
5844 }
5845 return ConstantVector::get(ConstVec);
5846 }
5847
5848 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5849 /// in \p Use can trigger undefined behavior.
5850 static bool canCauseUndefinedBehavior(const Instruction *Use,
5851 unsigned OperandIdx) {
5852 // This is not safe to introduce undef when the operand is on
5853 // the right hand side of a division-like instruction.
5854 if (OperandIdx != 1)
5855 return false;
5856 switch (Use->getOpcode()) {
5857 default:
5858 return false;
5859 case Instruction::SDiv:
5860 case Instruction::UDiv:
5861 case Instruction::SRem:
5862 case Instruction::URem:
5863 return true;
5864 case Instruction::FDiv:
5865 case Instruction::FRem:
5866 return !Use->hasNoNaNs();
5867 }
5868 llvm_unreachable(nullptr);
5869 }
5870
5871public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005872 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5873 const TargetTransformInfo &TTI, Instruction *Transition,
5874 unsigned CombineCost)
5875 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Eugene Zelenko900b6332017-08-29 22:32:07 +00005876 StoreExtractCombineCost(CombineCost) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005877 assert(Transition && "Do not know how to promote null");
5878 }
5879
5880 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5881 bool canPromote(const Instruction *ToBePromoted) const {
5882 // We could support CastInst too.
5883 return isa<BinaryOperator>(ToBePromoted);
5884 }
5885
5886 /// \brief Check if it is profitable to promote \p ToBePromoted
5887 /// by moving downward the transition through.
5888 bool shouldPromote(const Instruction *ToBePromoted) const {
5889 // Promote only if all the operands can be statically expanded.
5890 // Indeed, we do not want to introduce any new kind of transitions.
5891 for (const Use &U : ToBePromoted->operands()) {
5892 const Value *Val = U.get();
5893 if (Val == getEndOfTransition()) {
5894 // If the use is a division and the transition is on the rhs,
5895 // we cannot promote the operation, otherwise we may create a
5896 // division by zero.
5897 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5898 return false;
5899 continue;
5900 }
5901 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5902 !isa<ConstantFP>(Val))
5903 return false;
5904 }
5905 // Check that the resulting operation is legal.
5906 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5907 if (!ISDOpcode)
5908 return false;
5909 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005910 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005911 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005912 }
5913
5914 /// \brief Check whether or not \p Use can be combined
5915 /// with the transition.
5916 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5917 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5918
5919 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5920 void enqueueForPromotion(Instruction *ToBePromoted) {
5921 InstsToBePromoted.push_back(ToBePromoted);
5922 }
5923
5924 /// \brief Set the instruction that will be combined with the transition.
5925 void recordCombineInstruction(Instruction *ToBeCombined) {
5926 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5927 CombineInst = ToBeCombined;
5928 }
5929
5930 /// \brief Promote all the instructions enqueued for promotion if it is
5931 /// is profitable.
5932 /// \return True if the promotion happened, false otherwise.
5933 bool promote() {
5934 // Check if there is something to promote.
5935 // Right now, if we do not have anything to combine with,
5936 // we assume the promotion is not profitable.
5937 if (InstsToBePromoted.empty() || !CombineInst)
5938 return false;
5939
5940 // Check cost.
5941 if (!StressStoreExtract && !isProfitableToPromote())
5942 return false;
5943
5944 // Promote.
5945 for (auto &ToBePromoted : InstsToBePromoted)
5946 promoteImpl(ToBePromoted);
5947 InstsToBePromoted.clear();
5948 return true;
5949 }
5950};
Eugene Zelenko900b6332017-08-29 22:32:07 +00005951
5952} // end anonymous namespace
Quentin Colombetc32615d2014-10-31 17:52:53 +00005953
5954void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5955 // At this point, we know that all the operands of ToBePromoted but Def
5956 // can be statically promoted.
5957 // For Def, we need to use its parameter in ToBePromoted:
5958 // b = ToBePromoted ty1 a
5959 // Def = Transition ty1 b to ty2
5960 // Move the transition down.
5961 // 1. Replace all uses of the promoted operation by the transition.
5962 // = ... b => = ... Def.
5963 assert(ToBePromoted->getType() == Transition->getType() &&
5964 "The type of the result of the transition does not match "
5965 "the final type");
5966 ToBePromoted->replaceAllUsesWith(Transition);
5967 // 2. Update the type of the uses.
5968 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5969 Type *TransitionTy = getTransitionType();
5970 ToBePromoted->mutateType(TransitionTy);
5971 // 3. Update all the operands of the promoted operation with promoted
5972 // operands.
5973 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5974 for (Use &U : ToBePromoted->operands()) {
5975 Value *Val = U.get();
5976 Value *NewVal = nullptr;
5977 if (Val == Transition)
5978 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5979 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5980 isa<ConstantFP>(Val)) {
5981 // Use a splat constant if it is not safe to use undef.
5982 NewVal = getConstantVector(
5983 cast<Constant>(Val),
5984 isa<UndefValue>(Val) ||
5985 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5986 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005987 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5988 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005989 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5990 }
Sanjay Patel674d2c22017-08-29 14:07:48 +00005991 Transition->moveAfter(ToBePromoted);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005992 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5993}
5994
5995/// Some targets can do store(extractelement) with one instruction.
5996/// Try to push the extractelement towards the stores when the target
5997/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005998bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005999 unsigned CombineCost = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006000 if (DisableStoreExtract || !TLI ||
6001 (!StressStoreExtract &&
6002 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
6003 Inst->getOperand(1), CombineCost)))
6004 return false;
6005
6006 // At this point we know that Inst is a vector to scalar transition.
6007 // Try to move it down the def-use chain, until:
6008 // - We can combine the transition with its single use
6009 // => we got rid of the transition.
6010 // - We escape the current basic block
6011 // => we would need to check that we are moving it at a cheaper place and
6012 // we do not do that for now.
6013 BasicBlock *Parent = Inst->getParent();
6014 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00006015 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006016 // If the transition has more than one use, assume this is not going to be
6017 // beneficial.
6018 while (Inst->hasOneUse()) {
6019 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
6020 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
6021
6022 if (ToBePromoted->getParent() != Parent) {
6023 DEBUG(dbgs() << "Instruction to promote is in a different block ("
6024 << ToBePromoted->getParent()->getName()
6025 << ") than the transition (" << Parent->getName() << ").\n");
6026 return false;
6027 }
6028
6029 if (VPH.canCombine(ToBePromoted)) {
6030 DEBUG(dbgs() << "Assume " << *Inst << '\n'
6031 << "will be combined with: " << *ToBePromoted << '\n');
6032 VPH.recordCombineInstruction(ToBePromoted);
6033 bool Changed = VPH.promote();
6034 NumStoreExtractExposed += Changed;
6035 return Changed;
6036 }
6037
6038 DEBUG(dbgs() << "Try promoting.\n");
6039 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6040 return false;
6041
6042 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
6043
6044 VPH.enqueueForPromotion(ToBePromoted);
6045 Inst = ToBePromoted;
6046 }
6047 return false;
6048}
6049
Wei Mia2f0b592016-12-22 19:44:45 +00006050/// For the instruction sequence of store below, F and I values
6051/// are bundled together as an i64 value before being stored into memory.
6052/// Sometimes it is more efficent to generate separate stores for F and I,
6053/// which can remove the bitwise instructions or sink them to colder places.
6054///
6055/// (store (or (zext (bitcast F to i32) to i64),
6056/// (shl (zext I to i64), 32)), addr) -->
6057/// (store F, addr) and (store I, addr+4)
6058///
6059/// Similarly, splitting for other merged store can also be beneficial, like:
6060/// For pair of {i32, i32}, i64 store --> two i32 stores.
6061/// For pair of {i32, i16}, i64 store --> two i32 stores.
6062/// For pair of {i16, i16}, i32 store --> two i16 stores.
6063/// For pair of {i16, i8}, i32 store --> two i16 stores.
6064/// For pair of {i8, i8}, i16 store --> two i8 stores.
6065///
6066/// We allow each target to determine specifically which kind of splitting is
6067/// supported.
6068///
6069/// The store patterns are commonly seen from the simple code snippet below
6070/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
6071/// void goo(const std::pair<int, float> &);
6072/// hoo() {
6073/// ...
6074/// goo(std::make_pair(tmp, ftmp));
6075/// ...
6076/// }
6077///
6078/// Although we already have similar splitting in DAG Combine, we duplicate
6079/// it in CodeGenPrepare to catch the case in which pattern is across
6080/// multiple BBs. The logic in DAG Combine is kept to catch case generated
6081/// during code expansion.
6082static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
6083 const TargetLowering &TLI) {
6084 // Handle simple but common cases only.
6085 Type *StoreType = SI.getValueOperand()->getType();
6086 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6087 DL.getTypeSizeInBits(StoreType) == 0)
6088 return false;
6089
6090 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6091 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6092 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6093 DL.getTypeSizeInBits(SplitStoreType))
6094 return false;
6095
6096 // Match the following patterns:
6097 // (store (or (zext LValue to i64),
6098 // (shl (zext HValue to i64), 32)), HalfValBitSize)
6099 // or
6100 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6101 // (zext LValue to i64),
6102 // Expect both operands of OR and the first operand of SHL have only
6103 // one use.
6104 Value *LValue, *HValue;
6105 if (!match(SI.getValueOperand(),
6106 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6107 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6108 m_SpecificInt(HalfValBitSize))))))
6109 return false;
6110
6111 // Check LValue and HValue are int with size less or equal than 32.
6112 if (!LValue->getType()->isIntegerTy() ||
6113 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6114 !HValue->getType()->isIntegerTy() ||
6115 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6116 return false;
6117
6118 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6119 // as the input of target query.
6120 auto *LBC = dyn_cast<BitCastInst>(LValue);
6121 auto *HBC = dyn_cast<BitCastInst>(HValue);
6122 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6123 : EVT::getEVT(LValue->getType());
6124 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6125 : EVT::getEVT(HValue->getType());
6126 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6127 return false;
6128
6129 // Start to split store.
6130 IRBuilder<> Builder(SI.getContext());
6131 Builder.SetInsertPoint(&SI);
6132
6133 // If LValue/HValue is a bitcast in another BB, create a new one in current
6134 // BB so it may be merged with the splitted stores by dag combiner.
6135 if (LBC && LBC->getParent() != SI.getParent())
6136 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6137 if (HBC && HBC->getParent() != SI.getParent())
6138 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6139
6140 auto CreateSplitStore = [&](Value *V, bool Upper) {
6141 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6142 Value *Addr = Builder.CreateBitCast(
6143 SI.getOperand(1),
6144 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
6145 if (Upper)
6146 Addr = Builder.CreateGEP(
6147 SplitStoreType, Addr,
6148 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6149 Builder.CreateAlignedStore(
6150 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6151 };
6152
6153 CreateSplitStore(LValue, false);
6154 CreateSplitStore(HValue, true);
6155
6156 // Delete the old store.
6157 SI.eraseFromParent();
6158 return true;
6159}
6160
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006161// Return true if the GEP has two operands, the first operand is of a sequential
6162// type, and the second operand is a constant.
6163static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6164 gep_type_iterator I = gep_type_begin(*GEP);
6165 return GEP->getNumOperands() == 2 &&
6166 I.isSequential() &&
6167 isa<ConstantInt>(GEP->getOperand(1));
6168}
6169
6170// Try unmerging GEPs to reduce liveness interference (register pressure) across
6171// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6172// reducing liveness interference across those edges benefits global register
6173// allocation. Currently handles only certain cases.
6174//
6175// For example, unmerge %GEPI and %UGEPI as below.
6176//
6177// ---------- BEFORE ----------
6178// SrcBlock:
6179// ...
6180// %GEPIOp = ...
6181// ...
6182// %GEPI = gep %GEPIOp, Idx
6183// ...
6184// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6185// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6186// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6187// %UGEPI)
6188//
6189// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6190// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6191// ...
6192//
6193// DstBi:
6194// ...
6195// %UGEPI = gep %GEPIOp, UIdx
6196// ...
6197// ---------------------------
6198//
6199// ---------- AFTER ----------
6200// SrcBlock:
6201// ... (same as above)
6202// (* %GEPI is still alive on the indirectbr edges)
6203// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6204// unmerging)
6205// ...
6206//
6207// DstBi:
6208// ...
6209// %UGEPI = gep %GEPI, (UIdx-Idx)
6210// ...
6211// ---------------------------
6212//
6213// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6214// no longer alive on them.
6215//
6216// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6217// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6218// not to disable further simplications and optimizations as a result of GEP
6219// merging.
6220//
6221// Note this unmerging may increase the length of the data flow critical path
6222// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6223// between the register pressure and the length of data-flow critical
6224// path. Restricting this to the uncommon IndirectBr case would minimize the
6225// impact of potentially longer critical path, if any, and the impact on compile
6226// time.
6227static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6228 const TargetTransformInfo *TTI) {
6229 BasicBlock *SrcBlock = GEPI->getParent();
6230 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6231 // (non-IndirectBr) cases exit early here.
6232 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6233 return false;
6234 // Check that GEPI is a simple gep with a single constant index.
6235 if (!GEPSequentialConstIndexed(GEPI))
6236 return false;
6237 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6238 // Check that GEPI is a cheap one.
6239 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6240 > TargetTransformInfo::TCC_Basic)
6241 return false;
6242 Value *GEPIOp = GEPI->getOperand(0);
6243 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6244 if (!isa<Instruction>(GEPIOp))
6245 return false;
6246 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6247 if (GEPIOpI->getParent() != SrcBlock)
6248 return false;
6249 // Check that GEP is used outside the block, meaning it's alive on the
6250 // IndirectBr edge(s).
6251 if (find_if(GEPI->users(), [&](User *Usr) {
6252 if (auto *I = dyn_cast<Instruction>(Usr)) {
6253 if (I->getParent() != SrcBlock) {
6254 return true;
6255 }
6256 }
6257 return false;
6258 }) == GEPI->users().end())
6259 return false;
6260 // The second elements of the GEP chains to be unmerged.
6261 std::vector<GetElementPtrInst *> UGEPIs;
6262 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6263 // on IndirectBr edges.
6264 for (User *Usr : GEPIOp->users()) {
6265 if (Usr == GEPI) continue;
6266 // Check if Usr is an Instruction. If not, give up.
6267 if (!isa<Instruction>(Usr))
6268 return false;
6269 auto *UI = cast<Instruction>(Usr);
6270 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6271 if (UI->getParent() == SrcBlock)
6272 continue;
6273 // Check if Usr is a GEP. If not, give up.
6274 if (!isa<GetElementPtrInst>(Usr))
6275 return false;
6276 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6277 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6278 // the pointer operand to it. If so, record it in the vector. If not, give
6279 // up.
6280 if (!GEPSequentialConstIndexed(UGEPI))
6281 return false;
6282 if (UGEPI->getOperand(0) != GEPIOp)
6283 return false;
6284 if (GEPIIdx->getType() !=
6285 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6286 return false;
6287 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6288 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6289 > TargetTransformInfo::TCC_Basic)
6290 return false;
6291 UGEPIs.push_back(UGEPI);
6292 }
6293 if (UGEPIs.size() == 0)
6294 return false;
6295 // Check the materializing cost of (Uidx-Idx).
6296 for (GetElementPtrInst *UGEPI : UGEPIs) {
6297 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6298 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6299 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6300 if (ImmCost > TargetTransformInfo::TCC_Basic)
6301 return false;
6302 }
6303 // Now unmerge between GEPI and UGEPIs.
6304 for (GetElementPtrInst *UGEPI : UGEPIs) {
6305 UGEPI->setOperand(0, GEPI);
6306 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6307 Constant *NewUGEPIIdx =
6308 ConstantInt::get(GEPIIdx->getType(),
6309 UGEPIIdx->getValue() - GEPIIdx->getValue());
6310 UGEPI->setOperand(1, NewUGEPIIdx);
6311 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6312 // inbounds to avoid UB.
6313 if (!GEPI->isInBounds()) {
6314 UGEPI->setIsInBounds(false);
6315 }
6316 }
6317 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6318 // alive on IndirectBr edges).
6319 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6320 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6321 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6322 return true;
6323}
6324
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006325bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00006326 // Bail out if we inserted the instruction to prevent optimizations from
6327 // stepping on each other's toes.
6328 if (InsertedInsts.count(I))
6329 return false;
6330
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006331 if (PHINode *P = dyn_cast<PHINode>(I)) {
6332 // It is possible for very late stage optimizations (such as SimplifyCFG)
6333 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6334 // trivial PHI, go ahead and zap it here.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00006335 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006336 P->replaceAllUsesWith(V);
6337 P->eraseFromParent();
6338 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00006339 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006340 }
Chris Lattneree588de2011-01-15 07:29:01 +00006341 return false;
6342 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006343
Chris Lattneree588de2011-01-15 07:29:01 +00006344 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006345 // If the source of the cast is a constant, then this should have
6346 // already been constant folded. The only reason NOT to constant fold
6347 // it is if something (e.g. LSR) was careful to place the constant
6348 // evaluation in a block other than then one that uses it (e.g. to hoist
6349 // the address of globals out of a loop). If this is the case, we don't
6350 // want to forward-subst the cast.
6351 if (isa<Constant>(CI->getOperand(0)))
6352 return false;
6353
Mehdi Amini44ede332015-07-09 02:09:04 +00006354 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00006355 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006356
Chris Lattneree588de2011-01-15 07:29:01 +00006357 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006358 /// Sink a zext or sext into its user blocks if the target type doesn't
6359 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00006360 if (TLI &&
6361 TLI->getTypeAction(CI->getContext(),
6362 TLI->getValueType(*DL, CI->getType())) ==
6363 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006364 return SinkCast(CI);
6365 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00006366 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00006367 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006368 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006369 }
Chris Lattneree588de2011-01-15 07:29:01 +00006370 return false;
6371 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006372
Chris Lattneree588de2011-01-15 07:29:01 +00006373 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00006374 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00006375 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00006376
Chris Lattneree588de2011-01-15 07:29:01 +00006377 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006378 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006379 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006380 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006381 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006382 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6383 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006384 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006385 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006386 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006387
Chris Lattneree588de2011-01-15 07:29:01 +00006388 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006389 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6390 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006391 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006392 if (TLI) {
6393 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006394 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006395 SI->getOperand(0)->getType(), AS);
6396 }
Chris Lattneree588de2011-01-15 07:29:01 +00006397 return false;
6398 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006399
Matt Arsenault02d915b2017-03-15 22:35:20 +00006400 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6401 unsigned AS = RMW->getPointerAddressSpace();
6402 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6403 RMW->getType(), AS);
6404 }
6405
6406 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6407 unsigned AS = CmpX->getPointerAddressSpace();
6408 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6409 CmpX->getCompareOperand()->getType(), AS);
6410 }
6411
Yi Jiangd069f632014-04-21 19:34:27 +00006412 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6413
Geoff Berry5d534b62017-02-21 18:53:14 +00006414 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6415 EnableAndCmpSinking && TLI)
6416 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6417
Yi Jiangd069f632014-04-21 19:34:27 +00006418 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6419 BinOp->getOpcode() == Instruction::LShr)) {
6420 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6421 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006422 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006423
6424 return false;
6425 }
6426
Chris Lattneree588de2011-01-15 07:29:01 +00006427 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006428 if (GEPI->hasAllZeroIndices()) {
6429 /// The GEP operand must be a pointer, so must its result -> BitCast
6430 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6431 GEPI->getName(), GEPI);
6432 GEPI->replaceAllUsesWith(NC);
6433 GEPI->eraseFromParent();
6434 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00006435 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00006436 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006437 }
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006438 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
6439 return true;
6440 }
Chris Lattneree588de2011-01-15 07:29:01 +00006441 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006442 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006443
Chris Lattneree588de2011-01-15 07:29:01 +00006444 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006445 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006446
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006447 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006448 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006449
Tim Northoveraeb8e062014-02-19 10:02:43 +00006450 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006451 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006452
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006453 if (auto *Switch = dyn_cast<SwitchInst>(I))
6454 return optimizeSwitchInst(Switch);
6455
Quentin Colombetc32615d2014-10-31 17:52:53 +00006456 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006457 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006458
Chris Lattneree588de2011-01-15 07:29:01 +00006459 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006460}
6461
James Molloyf01488e2016-01-15 09:20:19 +00006462/// Given an OR instruction, check to see if this is a bitreverse
6463/// idiom. If so, insert the new intrinsic and return true.
6464static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6465 const TargetLowering &TLI) {
6466 if (!I.getType()->isIntegerTy() ||
6467 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6468 TLI.getValueType(DL, I.getType(), true)))
6469 return false;
6470
6471 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00006472 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00006473 return false;
6474 Instruction *LastInst = Insts.back();
6475 I.replaceAllUsesWith(LastInst);
6476 RecursivelyDeleteTriviallyDeadInstructions(&I);
6477 return true;
6478}
6479
Chris Lattnerf2836d12007-03-31 04:06:36 +00006480// In this pass we look for GEP and cast instructions that are used
6481// across basic blocks and rewrite them to improve basic-block-at-a-time
6482// selection.
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006483bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00006484 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00006485 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00006486
Chris Lattner7a277142011-01-15 07:14:54 +00006487 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006488 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006489 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006490 if (ModifiedDT)
6491 return true;
6492 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00006493
James Molloyf01488e2016-01-15 09:20:19 +00006494 bool MadeBitReverse = true;
6495 while (TLI && MadeBitReverse) {
6496 MadeBitReverse = false;
6497 for (auto &I : reverse(BB)) {
6498 if (makeBitReverse(I, *DL, *TLI)) {
6499 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00006500 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00006501 break;
6502 }
6503 }
6504 }
James Molloy3ef84c42016-01-15 10:36:01 +00006505 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00006506
Chris Lattnerf2836d12007-03-31 04:06:36 +00006507 return MadeChange;
6508}
Devang Patel53771ba2011-08-18 00:50:51 +00006509
6510// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00006511// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00006512// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006513bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00006514 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006515 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00006516 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006517 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006518 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00006519 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00006520 // Leave dbg.values that refer to an alloca alone. These
Craig Topper87e715f2017-11-07 20:56:17 +00006521 // intrinsics describe the address of a variable (= the alloca)
Adrian Prantl32da8892014-04-25 20:49:25 +00006522 // being taken. They should not be moved next to the alloca
6523 // (and to the beginning of the scope), but rather stay close to
6524 // where said address is used.
6525 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00006526 PrevNonDbgInst = Insn;
6527 continue;
6528 }
6529
6530 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6531 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00006532 // If VI is a phi in a block with an EHPad terminator, we can't insert
6533 // after it.
6534 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6535 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00006536 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
6537 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00006538 if (isa<PHINode>(VI))
6539 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6540 else
6541 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006542 MadeChange = true;
6543 ++NumDbgValueMoved;
6544 }
6545 }
6546 }
6547 return MadeChange;
6548}
Tim Northovercea0abb2014-03-29 08:22:29 +00006549
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006550/// \brief Scale down both weights to fit into uint32_t.
6551static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6552 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006553 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006554 NewTrue = NewTrue / Scale;
6555 NewFalse = NewFalse / Scale;
6556}
6557
6558/// \brief Some targets prefer to split a conditional branch like:
6559/// \code
6560/// %0 = icmp ne i32 %a, 0
6561/// %1 = icmp ne i32 %b, 0
6562/// %or.cond = or i1 %0, %1
6563/// br i1 %or.cond, label %TrueBB, label %FalseBB
6564/// \endcode
6565/// into multiple branch instructions like:
6566/// \code
6567/// bb1:
6568/// %0 = icmp ne i32 %a, 0
6569/// br i1 %0, label %TrueBB, label %bb2
6570/// bb2:
6571/// %1 = icmp ne i32 %b, 0
6572/// br i1 %1, label %TrueBB, label %FalseBB
6573/// \endcode
6574/// This usually allows instruction selection to do even further optimizations
6575/// and combine the compare with the branch instruction. Currently this is
6576/// applied for targets which have "cheap" jump instructions.
6577///
6578/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6579///
6580bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006581 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006582 return false;
6583
6584 bool MadeChange = false;
6585 for (auto &BB : F) {
6586 // Does this BB end with the following?
6587 // %cond1 = icmp|fcmp|binary instruction ...
6588 // %cond2 = icmp|fcmp|binary instruction ...
6589 // %cond.or = or|and i1 %cond1, cond2
6590 // br i1 %cond.or label %dest1, label %dest2"
6591 BinaryOperator *LogicOp;
6592 BasicBlock *TBB, *FBB;
6593 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6594 continue;
6595
Sanjay Patel42574202015-09-02 19:23:23 +00006596 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6597 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6598 continue;
6599
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006600 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006601 Value *Cond1, *Cond2;
6602 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6603 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006604 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006605 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6606 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006607 Opc = Instruction::Or;
6608 else
6609 continue;
6610
6611 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6612 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6613 continue;
6614
6615 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6616
6617 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00006618 auto TmpBB =
6619 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6620 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006621
6622 // Update original basic block by using the first condition directly by the
6623 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006624 Br1->setCondition(Cond1);
6625 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006626
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006627 // Depending on the conditon we have to either replace the true or the false
6628 // successor of the original branch instruction.
6629 if (Opc == Instruction::And)
6630 Br1->setSuccessor(0, TmpBB);
6631 else
6632 Br1->setSuccessor(1, TmpBB);
6633
6634 // Fill in the new basic block.
6635 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006636 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6637 I->removeFromParent();
6638 I->insertBefore(Br2);
6639 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006640
6641 // Update PHI nodes in both successors. The original BB needs to be
Hiroshi Inoue6a391bb2017-06-27 10:35:37 +00006642 // replaced in one successor's PHI nodes, because the branch comes now from
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006643 // the newly generated BB (NewBB). In the other successor we need to add one
6644 // incoming edge to the PHI nodes, because both branch instructions target
6645 // now the same successor. Depending on the original branch condition
6646 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006647 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006648 // This doesn't change the successor order of the just created branch
6649 // instruction (or any other instruction).
6650 if (Opc == Instruction::Or)
6651 std::swap(TBB, FBB);
6652
6653 // Replace the old BB with the new BB.
6654 for (auto &I : *TBB) {
6655 PHINode *PN = dyn_cast<PHINode>(&I);
6656 if (!PN)
6657 break;
6658 int i;
6659 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
6660 PN->setIncomingBlock(i, TmpBB);
6661 }
6662
6663 // Add another incoming edge form the new BB.
6664 for (auto &I : *FBB) {
6665 PHINode *PN = dyn_cast<PHINode>(&I);
6666 if (!PN)
6667 break;
6668 auto *Val = PN->getIncomingValueForBlock(&BB);
6669 PN->addIncoming(Val, TmpBB);
6670 }
6671
6672 // Update the branch weights (from SelectionDAGBuilder::
6673 // FindMergedConditions).
6674 if (Opc == Instruction::Or) {
6675 // Codegen X | Y as:
6676 // BB1:
6677 // jmp_if_X TBB
6678 // jmp TmpBB
6679 // TmpBB:
6680 // jmp_if_Y TBB
6681 // jmp FBB
6682 //
6683
6684 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6685 // The requirement is that
6686 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6687 // = TrueProb for orignal BB.
6688 // Assuming the orignal weights are A and B, one choice is to set BB1's
6689 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6690 // assumes that
6691 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6692 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6693 // TmpBB, but the math is more complicated.
6694 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006695 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006696 uint64_t NewTrueWeight = TrueWeight;
6697 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6698 scaleWeights(NewTrueWeight, NewFalseWeight);
6699 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6700 .createBranchWeights(TrueWeight, FalseWeight));
6701
6702 NewTrueWeight = TrueWeight;
6703 NewFalseWeight = 2 * FalseWeight;
6704 scaleWeights(NewTrueWeight, NewFalseWeight);
6705 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6706 .createBranchWeights(TrueWeight, FalseWeight));
6707 }
6708 } else {
6709 // Codegen X & Y as:
6710 // BB1:
6711 // jmp_if_X TmpBB
6712 // jmp FBB
6713 // TmpBB:
6714 // jmp_if_Y TBB
6715 // jmp FBB
6716 //
6717 // This requires creation of TmpBB after CurBB.
6718
6719 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6720 // The requirement is that
6721 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6722 // = FalseProb for orignal BB.
6723 // Assuming the orignal weights are A and B, one choice is to set BB1's
6724 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6725 // assumes that
6726 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6727 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006728 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006729 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6730 uint64_t NewFalseWeight = FalseWeight;
6731 scaleWeights(NewTrueWeight, NewFalseWeight);
6732 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6733 .createBranchWeights(TrueWeight, FalseWeight));
6734
6735 NewTrueWeight = 2 * TrueWeight;
6736 NewFalseWeight = FalseWeight;
6737 scaleWeights(NewTrueWeight, NewFalseWeight);
6738 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6739 .createBranchWeights(TrueWeight, FalseWeight));
6740 }
6741 }
6742
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006743 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00006744 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006745 ModifiedDT = true;
6746
6747 MadeChange = true;
6748
6749 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6750 TmpBB->dump());
6751 }
6752 return MadeChange;
6753}