blob: 66ac179820811e28f2b1af7b8e82a363222402ae [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
Quentin Colombeta3490842014-02-22 00:07:45 +000016#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Jun Bum Lim90b6b502016-12-16 20:38:39 +000020#include "llvm/Analysis/BlockFrequencyInfo.h"
21#include "llvm/Analysis/BranchProbabilityInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000023#include "llvm/Analysis/LoopInfo.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000024#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000025#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000026#include "llvm/Analysis/TargetTransformInfo.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000027#include "llvm/Analysis/ValueTracking.h"
Petar Jovanovic644b8c12016-04-13 12:25:25 +000028#include "llvm/Analysis/MemoryBuiltins.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000029#include "llvm/CodeGen/Analysis.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000030#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000034#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000036#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/IRBuilder.h"
38#include "llvm/IR/InlineAsm.h"
39#include "llvm/IR/Instructions.h"
40#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000041#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000042#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000043#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000044#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000045#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000046#include "llvm/Pass.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000047#include "llvm/Support/BranchProbability.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000048#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000049#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000050#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000051#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000052#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000053#include "llvm/Transforms/Utils/BasicBlockUtils.h"
54#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000055#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000056#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000057#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000058using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000059using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000060
Chandler Carruth1b9dde02014-04-22 02:02:50 +000061#define DEBUG_TYPE "codegenprepare"
62
Cameron Zwarichced753f2011-01-05 17:27:27 +000063STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000064STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
65STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000066STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
67 "sunken Cmps");
68STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
69 "of sunken Casts");
70STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
71 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000072STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
73STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +000074STATISTIC(NumAndsAdded,
75 "Number of and mask instructions added to form ext loads");
76STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +000077STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000078STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000079STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000080STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000081
Cameron Zwarich338d3622011-03-11 21:52:04 +000082static cl::opt<bool> DisableBranchOpts(
83 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
84 cl::desc("Disable branch optimizations in CodeGenPrepare"));
85
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000086static cl::opt<bool>
87 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
88 cl::desc("Disable GC optimizations in CodeGenPrepare"));
89
Benjamin Kramer3d38c172012-05-06 14:25:16 +000090static cl::opt<bool> DisableSelectToBranch(
91 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
92 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000093
Hal Finkelc3998302014-04-12 00:59:48 +000094static cl::opt<bool> AddrSinkUsingGEPs(
95 "addr-sink-using-gep", cl::Hidden, cl::init(false),
96 cl::desc("Address sinking in CGP using GEPs."));
97
Tim Northovercea0abb2014-03-29 08:22:29 +000098static cl::opt<bool> EnableAndCmpSinking(
99 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
100 cl::desc("Enable sinkinig and/cmp into branches."));
101
Quentin Colombetc32615d2014-10-31 17:52:53 +0000102static cl::opt<bool> DisableStoreExtract(
103 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
104 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
105
106static cl::opt<bool> StressStoreExtract(
107 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
108 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
109
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000110static cl::opt<bool> DisableExtLdPromotion(
111 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
112 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
113 "CodeGenPrepare"));
114
115static cl::opt<bool> StressExtLdPromotion(
116 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
117 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
118 "optimization in CodeGenPrepare"));
119
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000120static cl::opt<bool> DisablePreheaderProtect(
121 "disable-preheader-prot", cl::Hidden, cl::init(false),
122 cl::desc("Disable protection against removing loop preheaders"));
123
Dehao Chen302b69c2016-10-18 20:42:47 +0000124static cl::opt<bool> ProfileGuidedSectionPrefix(
125 "profile-guided-section-prefix", cl::Hidden, cl::init(true),
126 cl::desc("Use profile info to add section prefix for hot/cold functions"));
127
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000128static cl::opt<unsigned> FreqRatioToSkipMerge(
129 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
130 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
131 "(frequency of destination block) is greater than this ratio"));
132
Wei Mia2f0b592016-12-22 19:44:45 +0000133static cl::opt<bool> ForceSplitStore(
134 "force-split-store", cl::Hidden, cl::init(false),
135 cl::desc("Force store splitting no matter what the target query says."));
136
Eric Christopherc1ea1492008-09-24 05:32:41 +0000137namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000138typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000139typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000140typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000141class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000142
Chris Lattner2dd09db2009-09-02 06:11:42 +0000143 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000144 const TargetMachine *TM;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000145 const TargetSubtargetInfo *SubtargetInfo;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000146 const TargetLowering *TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000147 const TargetRegisterInfo *TRI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000148 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000149 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000150 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000151 std::unique_ptr<BlockFrequencyInfo> BFI;
152 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000153
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000154 /// As we scan instructions optimizing them, this is the next instruction
155 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000156 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000157
Evan Cheng0663f232011-03-21 01:19:09 +0000158 /// Keeps track of non-local addresses that have been sunk into a block.
159 /// This allows us to avoid inserting duplicate code for blocks with
160 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000161 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000162
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000163 /// Keeps track of all instructions inserted for the current function.
164 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000165 /// Keeps track of the type of the related instruction before their
166 /// promotion for the current function.
167 InstrToOrigTy PromotedInsts;
168
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000169 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000170 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000171
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000172 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000173 bool OptSize;
174
Mehdi Amini4fe37982015-07-07 18:45:17 +0000175 /// DataLayout for the Function being processed.
176 const DataLayout *DL;
177
Chris Lattnerf2836d12007-03-31 04:06:36 +0000178 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000179 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000180 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000181 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000182 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
183 }
Craig Topper4584cd52014-03-07 09:26:03 +0000184 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000185
Mehdi Amini117296c2016-10-01 02:56:57 +0000186 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000187
Craig Topper4584cd52014-03-07 09:26:03 +0000188 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000189 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000190 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000191 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000192 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000193 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000194 }
195
Chris Lattnerf2836d12007-03-31 04:06:36 +0000196 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000197 bool eliminateFallThrough(Function &F);
198 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000199 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000200 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
201 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000202 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
203 bool isPreheader);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000204 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
205 bool optimizeInst(Instruction *I, bool& ModifiedDT);
206 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000207 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000208 bool optimizeInlineAsmInst(CallInst *CS);
209 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
210 bool moveExtToFormExtLoad(Instruction *&I);
211 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000212 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000213 bool optimizeSelectInst(SelectInst *SI);
214 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000215 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000216 bool optimizeExtractElementInst(Instruction *Inst);
217 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
218 bool placeDbgValues(Function &F);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000219 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000220 Instruction *&Inst,
221 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000222 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000223 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000224 bool simplifyOffsetableRelocate(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000225 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000226}
Devang Patel09f162c2007-05-01 21:15:47 +0000227
Devang Patel8c78a0b2007-05-03 01:11:54 +0000228char CodeGenPrepare::ID = 0;
Dehao Chen302b69c2016-10-18 20:42:47 +0000229INITIALIZE_TM_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
230 "Optimize for code generation", false, false)
231INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
232INITIALIZE_TM_PASS_END(CodeGenPrepare, "codegenprepare",
233 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000234
Bill Wendling7a639ea2013-06-19 21:07:11 +0000235FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
236 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000237}
238
Chris Lattnerf2836d12007-03-31 04:06:36 +0000239bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000240 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000241 return false;
242
Mehdi Amini4fe37982015-07-07 18:45:17 +0000243 DL = &F.getParent()->getDataLayout();
244
Chris Lattnerf2836d12007-03-31 04:06:36 +0000245 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000246 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000247 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000248 PromotedInsts.clear();
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000249 BFI.reset();
250 BPI.reset();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000251
Devang Patel8f606d72011-03-24 15:35:25 +0000252 ModifiedDT = false;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000253 if (TM) {
254 SubtargetInfo = TM->getSubtargetImpl(F);
255 TLI = SubtargetInfo->getTargetLowering();
256 TRI = SubtargetInfo->getRegisterInfo();
257 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000258 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000259 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000260 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000261 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000262
Dehao Chen302b69c2016-10-18 20:42:47 +0000263 if (ProfileGuidedSectionPrefix) {
264 ProfileSummaryInfo *PSI =
265 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
266 if (PSI->isFunctionEntryHot(&F))
267 F.setSectionPrefix(".hot");
268 else if (PSI->isFunctionEntryCold(&F))
269 F.setSectionPrefix(".cold");
270 }
271
Preston Gurdcdf540d2012-09-04 18:22:17 +0000272 /// This optimization identifies DIV instructions that can be
273 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000274 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000275 const DenseMap<unsigned int, unsigned int> &BypassWidths =
276 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000277 BasicBlock* BB = &*F.begin();
278 while (BB != nullptr) {
279 // bypassSlowDivision may create new BBs, but we don't want to reapply the
280 // optimization to those blocks.
281 BasicBlock* Next = BB->getNextNode();
282 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
283 BB = Next;
284 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000285 }
286
287 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000288 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000289 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000290
Devang Patel53771ba2011-08-18 00:50:51 +0000291 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000292 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000293 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000294 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000295
Geoff Berry5d534b62017-02-21 18:53:14 +0000296 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000297 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000298
Chris Lattnerc3748562007-04-02 01:35:34 +0000299 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000300 while (MadeChange) {
301 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000302 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000303 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000304 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000305 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000306
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000307 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000308 if (ModifiedDTOnIteration)
309 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000310 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000311 EverMadeChange |= MadeChange;
312 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000313
314 SunkAddrs.clear();
315
Cameron Zwarich338d3622011-03-11 21:52:04 +0000316 if (!DisableBranchOpts) {
317 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000318 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000319 for (BasicBlock &BB : F) {
320 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
321 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000322 if (!MadeChange) continue;
323
324 for (SmallVectorImpl<BasicBlock*>::iterator
325 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
326 if (pred_begin(*II) == pred_end(*II))
327 WorkList.insert(*II);
328 }
329
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000330 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000331 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000332 while (!WorkList.empty()) {
333 BasicBlock *BB = *WorkList.begin();
334 WorkList.erase(BB);
335 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
336
337 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000338
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000339 for (SmallVectorImpl<BasicBlock*>::iterator
340 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
341 if (pred_begin(*II) == pred_end(*II))
342 WorkList.insert(*II);
343 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000344
Nadav Rotem70409992012-08-14 05:19:07 +0000345 // Merge pairs of basic blocks with unconditional branches, connected by
346 // a single edge.
347 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000348 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000349
Cameron Zwarich338d3622011-03-11 21:52:04 +0000350 EverMadeChange |= MadeChange;
351 }
352
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000353 if (!DisableGCOpts) {
354 SmallVector<Instruction *, 2> Statepoints;
355 for (BasicBlock &BB : F)
356 for (Instruction &I : BB)
357 if (isStatepoint(I))
358 Statepoints.push_back(&I);
359 for (auto &I : Statepoints)
360 EverMadeChange |= simplifyOffsetableRelocate(*I);
361 }
362
Chris Lattnerf2836d12007-03-31 04:06:36 +0000363 return EverMadeChange;
364}
365
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000366/// Merge basic blocks which are connected by a single edge, where one of the
367/// basic blocks has a single successor pointing to the other basic block,
368/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000369bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000370 bool Changed = false;
371 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000372 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000373 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000374 // If the destination block has a single pred, then this is a trivial
375 // edge, just collapse it.
376 BasicBlock *SinglePred = BB->getSinglePredecessor();
377
Evan Cheng64a223a2012-09-28 23:58:57 +0000378 // Don't merge if BB's address is taken.
379 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000380
381 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
382 if (Term && !Term->isConditional()) {
383 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000384 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000385 // Remember if SinglePred was the entry block of the function.
386 // If so, we will need to move BB back to the entry position.
387 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000388 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000389
390 if (isEntry && BB != &BB->getParent()->getEntryBlock())
391 BB->moveBefore(&BB->getParent()->getEntryBlock());
392
393 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000394 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000395 }
396 }
397 return Changed;
398}
399
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000400/// Find a destination block from BB if BB is mergeable empty block.
401BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
402 // If this block doesn't end with an uncond branch, ignore it.
403 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
404 if (!BI || !BI->isUnconditional())
405 return nullptr;
406
407 // If the instruction before the branch (skipping debug info) isn't a phi
408 // node, then other stuff is happening here.
409 BasicBlock::iterator BBI = BI->getIterator();
410 if (BBI != BB->begin()) {
411 --BBI;
412 while (isa<DbgInfoIntrinsic>(BBI)) {
413 if (BBI == BB->begin())
414 break;
415 --BBI;
416 }
417 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
418 return nullptr;
419 }
420
421 // Do not break infinite loops.
422 BasicBlock *DestBB = BI->getSuccessor(0);
423 if (DestBB == BB)
424 return nullptr;
425
426 if (!canMergeBlocks(BB, DestBB))
427 DestBB = nullptr;
428
429 return DestBB;
430}
431
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000432/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
433/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
434/// edges in ways that are non-optimal for isel. Start by eliminating these
435/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000436bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000437 SmallPtrSet<BasicBlock *, 16> Preheaders;
438 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
439 while (!LoopList.empty()) {
440 Loop *L = LoopList.pop_back_val();
441 LoopList.insert(LoopList.end(), L->begin(), L->end());
442 if (BasicBlock *Preheader = L->getLoopPreheader())
443 Preheaders.insert(Preheader);
444 }
445
Chris Lattnerc3748562007-04-02 01:35:34 +0000446 bool MadeChange = false;
447 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000448 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000449 BasicBlock *BB = &*I++;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000450 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
451 if (!DestBB ||
452 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000453 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000454
Sanjay Patelfc580a62015-09-21 23:03:16 +0000455 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000456 MadeChange = true;
457 }
458 return MadeChange;
459}
460
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000461bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
462 BasicBlock *DestBB,
463 bool isPreheader) {
464 // Do not delete loop preheaders if doing so would create a critical edge.
465 // Loop preheaders can be good locations to spill registers. If the
466 // preheader is deleted and we create a critical edge, registers may be
467 // spilled in the loop body instead.
468 if (!DisablePreheaderProtect && isPreheader &&
469 !(BB->getSinglePredecessor() &&
470 BB->getSinglePredecessor()->getSingleSuccessor()))
471 return false;
472
473 // Try to skip merging if the unique predecessor of BB is terminated by a
474 // switch or indirect branch instruction, and BB is used as an incoming block
475 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
476 // add COPY instructions in the predecessor of BB instead of BB (if it is not
477 // merged). Note that the critical edge created by merging such blocks wont be
478 // split in MachineSink because the jump table is not analyzable. By keeping
479 // such empty block (BB), ISel will place COPY instructions in BB, not in the
480 // predecessor of BB.
481 BasicBlock *Pred = BB->getUniquePredecessor();
482 if (!Pred ||
483 !(isa<SwitchInst>(Pred->getTerminator()) ||
484 isa<IndirectBrInst>(Pred->getTerminator())))
485 return true;
486
487 if (BB->getTerminator() != BB->getFirstNonPHI())
488 return true;
489
490 // We use a simple cost heuristic which determine skipping merging is
491 // profitable if the cost of skipping merging is less than the cost of
492 // merging : Cost(skipping merging) < Cost(merging BB), where the
493 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
494 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
495 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
496 // Freq(Pred) / Freq(BB) > 2.
497 // Note that if there are multiple empty blocks sharing the same incoming
498 // value for the PHIs in the DestBB, we consider them together. In such
499 // case, Cost(merging BB) will be the sum of their frequencies.
500
501 if (!isa<PHINode>(DestBB->begin()))
502 return true;
503
504 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
505
506 // Find all other incoming blocks from which incoming values of all PHIs in
507 // DestBB are the same as the ones from BB.
508 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
509 ++PI) {
510 BasicBlock *DestBBPred = *PI;
511 if (DestBBPred == BB)
512 continue;
513
514 bool HasAllSameValue = true;
515 BasicBlock::const_iterator DestBBI = DestBB->begin();
516 while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) {
517 if (DestPN->getIncomingValueForBlock(BB) !=
518 DestPN->getIncomingValueForBlock(DestBBPred)) {
519 HasAllSameValue = false;
520 break;
521 }
522 }
523 if (HasAllSameValue)
524 SameIncomingValueBBs.insert(DestBBPred);
525 }
526
527 // See if all BB's incoming values are same as the value from Pred. In this
528 // case, no reason to skip merging because COPYs are expected to be place in
529 // Pred already.
530 if (SameIncomingValueBBs.count(Pred))
531 return true;
532
533 if (!BFI) {
534 Function &F = *BB->getParent();
535 LoopInfo LI{DominatorTree(F)};
536 BPI.reset(new BranchProbabilityInfo(F, LI));
537 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
538 }
539
540 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
541 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
542
543 for (auto SameValueBB : SameIncomingValueBBs)
544 if (SameValueBB->getUniquePredecessor() == Pred &&
545 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
546 BBFreq += BFI->getBlockFreq(SameValueBB);
547
548 return PredFreq.getFrequency() <=
549 BBFreq.getFrequency() * FreqRatioToSkipMerge;
550}
551
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000552/// Return true if we can merge BB into DestBB if there is a single
553/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000554/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000555bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000556 const BasicBlock *DestBB) const {
557 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
558 // the successor. If there are more complex condition (e.g. preheaders),
559 // don't mess around with them.
560 BasicBlock::const_iterator BBI = BB->begin();
561 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000562 for (const User *U : PN->users()) {
563 const Instruction *UI = cast<Instruction>(U);
564 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000565 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000566 // If User is inside DestBB block and it is a PHINode then check
567 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000568 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000569 if (UI->getParent() == DestBB) {
570 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000571 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
572 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
573 if (Insn && Insn->getParent() == BB &&
574 Insn->getParent() != UPN->getIncomingBlock(I))
575 return false;
576 }
577 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000578 }
579 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000580
Chris Lattnerc3748562007-04-02 01:35:34 +0000581 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
582 // and DestBB may have conflicting incoming values for the block. If so, we
583 // can't merge the block.
584 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
585 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000586
Chris Lattnerc3748562007-04-02 01:35:34 +0000587 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000588 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000589 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
590 // It is faster to get preds from a PHI than with pred_iterator.
591 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
592 BBPreds.insert(BBPN->getIncomingBlock(i));
593 } else {
594 BBPreds.insert(pred_begin(BB), pred_end(BB));
595 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000596
Chris Lattnerc3748562007-04-02 01:35:34 +0000597 // Walk the preds of DestBB.
598 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
599 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
600 if (BBPreds.count(Pred)) { // Common predecessor?
601 BBI = DestBB->begin();
602 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
603 const Value *V1 = PN->getIncomingValueForBlock(Pred);
604 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000605
Chris Lattnerc3748562007-04-02 01:35:34 +0000606 // If V2 is a phi node in BB, look up what the mapped value will be.
607 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
608 if (V2PN->getParent() == BB)
609 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000610
Chris Lattnerc3748562007-04-02 01:35:34 +0000611 // If there is a conflict, bail out.
612 if (V1 != V2) return false;
613 }
614 }
615 }
616
617 return true;
618}
619
620
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000621/// Eliminate a basic block that has only phi's and an unconditional branch in
622/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000623void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000624 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
625 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000626
David Greene74e2d492010-01-05 01:27:11 +0000627 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000628
Chris Lattnerc3748562007-04-02 01:35:34 +0000629 // If the destination block has a single pred, then this is a trivial edge,
630 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000631 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000632 if (SinglePred != DestBB) {
633 // Remember if SinglePred was the entry block of the function. If so, we
634 // will need to move BB back to the entry position.
635 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000636 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000637
Chris Lattner8a172da2008-11-28 19:54:49 +0000638 if (isEntry && BB != &BB->getParent()->getEntryBlock())
639 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000640
David Greene74e2d492010-01-05 01:27:11 +0000641 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000642 return;
643 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000644 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000645
Chris Lattnerc3748562007-04-02 01:35:34 +0000646 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
647 // to handle the new incoming edges it is about to have.
648 PHINode *PN;
649 for (BasicBlock::iterator BBI = DestBB->begin();
650 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
651 // Remove the incoming value for BB, and remember it.
652 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000653
Chris Lattnerc3748562007-04-02 01:35:34 +0000654 // Two options: either the InVal is a phi node defined in BB or it is some
655 // value that dominates BB.
656 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
657 if (InValPhi && InValPhi->getParent() == BB) {
658 // Add all of the input values of the input PHI as inputs of this phi.
659 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
660 PN->addIncoming(InValPhi->getIncomingValue(i),
661 InValPhi->getIncomingBlock(i));
662 } else {
663 // Otherwise, add one instance of the dominating value for each edge that
664 // we will be adding.
665 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
666 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
667 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
668 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000669 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
670 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000671 }
672 }
673 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000674
Chris Lattnerc3748562007-04-02 01:35:34 +0000675 // The PHIs are now updated, change everything that refers to BB to use
676 // DestBB and remove BB.
677 BB->replaceAllUsesWith(DestBB);
678 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000679 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000680
David Greene74e2d492010-01-05 01:27:11 +0000681 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000682}
683
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000684// Computes a map of base pointer relocation instructions to corresponding
685// derived pointer relocation instructions given a vector of all relocate calls
686static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000687 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
688 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
689 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000690 // Collect information in two maps: one primarily for locating the base object
691 // while filling the second map; the second map is the final structure holding
692 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000693 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
694 for (auto *ThisRelocate : AllRelocateCalls) {
695 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
696 ThisRelocate->getDerivedPtrIndex());
697 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000698 }
699 for (auto &Item : RelocateIdxMap) {
700 std::pair<unsigned, unsigned> Key = Item.first;
701 if (Key.first == Key.second)
702 // Base relocation: nothing to insert
703 continue;
704
Manuel Jacob83eefa62016-01-05 04:03:00 +0000705 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000706 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000707
708 // We're iterating over RelocateIdxMap so we cannot modify it.
709 auto MaybeBase = RelocateIdxMap.find(BaseKey);
710 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000711 // TODO: We might want to insert a new base object relocate and gep off
712 // that, if there are enough derived object relocates.
713 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000714
715 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000716 }
717}
718
719// Accepts a GEP and extracts the operands into a vector provided they're all
720// small integer constants
721static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
722 SmallVectorImpl<Value *> &OffsetV) {
723 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
724 // Only accept small constant integer operands
725 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
726 if (!Op || Op->getZExtValue() > 20)
727 return false;
728 }
729
730 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
731 OffsetV.push_back(GEP->getOperand(i));
732 return true;
733}
734
735// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
736// replace, computes a replacement, and affects it.
737static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000738simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
739 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000740 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000741 for (GCRelocateInst *ToReplace : Targets) {
742 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000743 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000744 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000745 // A duplicate relocate call. TODO: coalesce duplicates.
746 continue;
747 }
748
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000749 if (RelocatedBase->getParent() != ToReplace->getParent()) {
750 // Base and derived relocates are in different basic blocks.
751 // In this case transform is only valid when base dominates derived
752 // relocate. However it would be too expensive to check dominance
753 // for each such relocate, so we skip the whole transformation.
754 continue;
755 }
756
Manuel Jacob83eefa62016-01-05 04:03:00 +0000757 Value *Base = ToReplace->getBasePtr();
758 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000759 if (!Derived || Derived->getPointerOperand() != Base)
760 continue;
761
762 SmallVector<Value *, 2> OffsetV;
763 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
764 continue;
765
766 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000767 assert(RelocatedBase->getNextNode() &&
768 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000769
770 // Insert after RelocatedBase
771 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000772 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000773
774 // If gc_relocate does not match the actual type, cast it to the right type.
775 // In theory, there must be a bitcast after gc_relocate if the type does not
776 // match, and we should reuse it to get the derived pointer. But it could be
777 // cases like this:
778 // bb1:
779 // ...
780 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
781 // br label %merge
782 //
783 // bb2:
784 // ...
785 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
786 // br label %merge
787 //
788 // merge:
789 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
790 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
791 //
792 // In this case, we can not find the bitcast any more. So we insert a new bitcast
793 // no matter there is already one or not. In this way, we can handle all cases, and
794 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000795 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000796 if (RelocatedBase->getType() != Base->getType()) {
797 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000798 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000799 }
David Blaikie68d535c2015-03-24 22:38:16 +0000800 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000801 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000802 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000803 // If the newly generated derived pointer's type does not match the original derived
804 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000805 Value *ActualReplacement = Replacement;
806 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000807 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000808 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000809 }
810 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000811 ToReplace->eraseFromParent();
812
813 MadeChange = true;
814 }
815 return MadeChange;
816}
817
818// Turns this:
819//
820// %base = ...
821// %ptr = gep %base + 15
822// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
823// %base' = relocate(%tok, i32 4, i32 4)
824// %ptr' = relocate(%tok, i32 4, i32 5)
825// %val = load %ptr'
826//
827// into this:
828//
829// %base = ...
830// %ptr = gep %base + 15
831// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
832// %base' = gc.relocate(%tok, i32 4, i32 4)
833// %ptr' = gep %base' + 15
834// %val = load %ptr'
835bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
836 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000837 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000838
839 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000840 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000841 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000842 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000843
844 // We need atleast one base pointer relocation + one derived pointer
845 // relocation to mangle
846 if (AllRelocateCalls.size() < 2)
847 return false;
848
849 // RelocateInstMap is a mapping from the base relocate instruction to the
850 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +0000851 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000852 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
853 if (RelocateInstMap.empty())
854 return false;
855
856 for (auto &Item : RelocateInstMap)
857 // Item.first is the RelocatedBase to offset against
858 // Item.second is the vector of Targets to replace
859 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
860 return MadeChange;
861}
862
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000863/// SinkCast - Sink the specified cast instruction into its user blocks
864static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000865 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000866
Chris Lattnerf2836d12007-03-31 04:06:36 +0000867 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000868 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000869
Chris Lattnerf2836d12007-03-31 04:06:36 +0000870 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000871 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000872 UI != E; ) {
873 Use &TheUse = UI.getUse();
874 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000875
Chris Lattnerf2836d12007-03-31 04:06:36 +0000876 // Figure out which BB this cast is used in. For PHI's this is the
877 // appropriate predecessor block.
878 BasicBlock *UserBB = User->getParent();
879 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000880 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000881 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000882
Chris Lattnerf2836d12007-03-31 04:06:36 +0000883 // Preincrement use iterator so we don't invalidate it.
884 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000885
David Majnemer0c80e2e2016-04-27 19:36:38 +0000886 // The first insertion point of a block containing an EH pad is after the
887 // pad. If the pad is the user, we cannot sink the cast past the pad.
888 if (User->isEHPad())
889 continue;
890
Andrew Kaylord0430e82015-11-23 19:16:15 +0000891 // If the block selected to receive the cast is an EH pad that does not
892 // allow non-PHI instructions before the terminator, we can't sink the
893 // cast.
894 if (UserBB->getTerminator()->isEHPad())
895 continue;
896
Chris Lattnerf2836d12007-03-31 04:06:36 +0000897 // If this user is in the same block as the cast, don't change the cast.
898 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000899
Chris Lattnerf2836d12007-03-31 04:06:36 +0000900 // If we have already inserted a cast into this block, use it.
901 CastInst *&InsertedCast = InsertedCasts[UserBB];
902
903 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000904 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000905 assert(InsertPt != UserBB->end());
906 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
907 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000908 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000909
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000910 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000911 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000912 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000913 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000914 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000915
Chris Lattnerf2836d12007-03-31 04:06:36 +0000916 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000917 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000918 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000919 MadeChange = true;
920 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000921
Chris Lattnerf2836d12007-03-31 04:06:36 +0000922 return MadeChange;
923}
924
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000925/// If the specified cast instruction is a noop copy (e.g. it's casting from
926/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
927/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000928///
929/// Return true if any changes are made.
930///
Mehdi Amini44ede332015-07-09 02:09:04 +0000931static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
932 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +0000933 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
934 // than sinking only nop casts, but is helpful on some platforms.
935 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
936 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
937 ASC->getDestAddressSpace()))
938 return false;
939 }
940
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000941 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000942 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
943 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000944
945 // This is an fp<->int conversion?
946 if (SrcVT.isInteger() != DstVT.isInteger())
947 return false;
948
949 // If this is an extension, it will be a zero or sign extension, which
950 // isn't a noop.
951 if (SrcVT.bitsLT(DstVT)) return false;
952
953 // If these values will be promoted, find out what they will be promoted
954 // to. This helps us consider truncates on PPC as noop copies when they
955 // are.
956 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
957 TargetLowering::TypePromoteInteger)
958 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
959 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
960 TargetLowering::TypePromoteInteger)
961 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
962
963 // If, after promotion, these are the same types, this is a noop copy.
964 if (SrcVT != DstVT)
965 return false;
966
967 return SinkCast(CI);
968}
969
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000970/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
971/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000972///
973/// Return true if any changes were made.
974static bool CombineUAddWithOverflow(CmpInst *CI) {
975 Value *A, *B;
976 Instruction *AddI;
977 if (!match(CI,
978 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
979 return false;
980
981 Type *Ty = AddI->getType();
982 if (!isa<IntegerType>(Ty))
983 return false;
984
985 // We don't want to move around uses of condition values this late, so we we
986 // check if it is legal to create the call to the intrinsic in the basic
987 // block containing the icmp:
988
989 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
990 return false;
991
992#ifndef NDEBUG
993 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
994 // for now:
995 if (AddI->hasOneUse())
996 assert(*AddI->user_begin() == CI && "expected!");
997#endif
998
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000999 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001000 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1001
1002 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1003
1004 auto *UAddWithOverflow =
1005 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1006 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1007 auto *Overflow =
1008 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1009
1010 CI->replaceAllUsesWith(Overflow);
1011 AddI->replaceAllUsesWith(UAdd);
1012 CI->eraseFromParent();
1013 AddI->eraseFromParent();
1014 return true;
1015}
1016
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001017/// Sink the given CmpInst into user blocks to reduce the number of virtual
1018/// registers that must be created and coalesced. This is a clear win except on
1019/// targets with multiple condition code registers (PowerPC), where it might
1020/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001021///
1022/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001023static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001024 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001025
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001026 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001027 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001028 return false;
1029
1030 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001031 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001032
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001033 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001034 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001035 UI != E; ) {
1036 Use &TheUse = UI.getUse();
1037 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001038
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001039 // Preincrement use iterator so we don't invalidate it.
1040 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001041
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001042 // Don't bother for PHI nodes.
1043 if (isa<PHINode>(User))
1044 continue;
1045
1046 // Figure out which BB this cmp is used in.
1047 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001048
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001049 // If this user is in the same block as the cmp, don't change the cmp.
1050 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001051
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001052 // If we have already inserted a cmp into this block, use it.
1053 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1054
1055 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001056 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001057 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001058 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001059 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1060 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001061 // Propagate the debug info.
1062 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001063 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001064
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001065 // Replace a use of the cmp with a use of the new cmp.
1066 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001067 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001068 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001069 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001070
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001071 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001072 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001073 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001074 MadeChange = true;
1075 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001076
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001077 return MadeChange;
1078}
1079
Peter Zotovf87e5502016-04-03 17:11:53 +00001080static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001081 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001082 return true;
1083
1084 if (CombineUAddWithOverflow(CI))
1085 return true;
1086
1087 return false;
1088}
1089
Geoff Berry5d534b62017-02-21 18:53:14 +00001090/// Duplicate and sink the given 'and' instruction into user blocks where it is
1091/// used in a compare to allow isel to generate better code for targets where
1092/// this operation can be combined.
1093///
1094/// Return true if any changes are made.
1095static bool sinkAndCmp0Expression(Instruction *AndI,
1096 const TargetLowering &TLI,
1097 SetOfInstrs &InsertedInsts) {
1098 // Double-check that we're not trying to optimize an instruction that was
1099 // already optimized by some other part of this pass.
1100 assert(!InsertedInsts.count(AndI) &&
1101 "Attempting to optimize already optimized and instruction");
1102 (void) InsertedInsts;
1103
1104 // Nothing to do for single use in same basic block.
1105 if (AndI->hasOneUse() &&
1106 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1107 return false;
1108
1109 // Try to avoid cases where sinking/duplicating is likely to increase register
1110 // pressure.
1111 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1112 !isa<ConstantInt>(AndI->getOperand(1)) &&
1113 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1114 return false;
1115
1116 for (auto *U : AndI->users()) {
1117 Instruction *User = cast<Instruction>(U);
1118
1119 // Only sink for and mask feeding icmp with 0.
1120 if (!isa<ICmpInst>(User))
1121 return false;
1122
1123 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1124 if (!CmpC || !CmpC->isZero())
1125 return false;
1126 }
1127
1128 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1129 return false;
1130
1131 DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1132 DEBUG(AndI->getParent()->dump());
1133
1134 // Push the 'and' into the same block as the icmp 0. There should only be
1135 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1136 // others, so we don't need to keep track of which BBs we insert into.
1137 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1138 UI != E; ) {
1139 Use &TheUse = UI.getUse();
1140 Instruction *User = cast<Instruction>(*UI);
1141
1142 // Preincrement use iterator so we don't invalidate it.
1143 ++UI;
1144
1145 DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1146
1147 // Keep the 'and' in the same place if the use is already in the same block.
1148 Instruction *InsertPt =
1149 User->getParent() == AndI->getParent() ? AndI : User;
1150 Instruction *InsertedAnd =
1151 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1152 AndI->getOperand(1), "", InsertPt);
1153 // Propagate the debug info.
1154 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1155
1156 // Replace a use of the 'and' with a use of the new 'and'.
1157 TheUse = InsertedAnd;
1158 ++NumAndUses;
1159 DEBUG(User->getParent()->dump());
1160 }
1161
1162 // We removed all uses, nuke the and.
1163 AndI->eraseFromParent();
1164 return true;
1165}
1166
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001167/// Check if the candidates could be combined with a shift instruction, which
1168/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001169/// 1. Truncate instruction
1170/// 2. And instruction and the imm is a mask of the low bits:
1171/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001172static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001173 if (!isa<TruncInst>(User)) {
1174 if (User->getOpcode() != Instruction::And ||
1175 !isa<ConstantInt>(User->getOperand(1)))
1176 return false;
1177
Quentin Colombetd4f44692014-04-22 01:20:34 +00001178 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001179
Quentin Colombetd4f44692014-04-22 01:20:34 +00001180 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001181 return false;
1182 }
1183 return true;
1184}
1185
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001186/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001187static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001188SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1189 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001190 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001191 BasicBlock *UserBB = User->getParent();
1192 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1193 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1194 bool MadeChange = false;
1195
1196 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1197 TruncE = TruncI->user_end();
1198 TruncUI != TruncE;) {
1199
1200 Use &TruncTheUse = TruncUI.getUse();
1201 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1202 // Preincrement use iterator so we don't invalidate it.
1203
1204 ++TruncUI;
1205
1206 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1207 if (!ISDOpcode)
1208 continue;
1209
Tim Northovere2239ff2014-07-29 10:20:22 +00001210 // If the use is actually a legal node, there will not be an
1211 // implicit truncate.
1212 // FIXME: always querying the result type is just an
1213 // approximation; some nodes' legality is determined by the
1214 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001215 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001216 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001217 continue;
1218
1219 // Don't bother for PHI nodes.
1220 if (isa<PHINode>(TruncUser))
1221 continue;
1222
1223 BasicBlock *TruncUserBB = TruncUser->getParent();
1224
1225 if (UserBB == TruncUserBB)
1226 continue;
1227
1228 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1229 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1230
1231 if (!InsertedShift && !InsertedTrunc) {
1232 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001233 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001234 // Sink the shift
1235 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001236 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1237 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001238 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001239 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1240 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001241
1242 // Sink the trunc
1243 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1244 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001245 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001246
1247 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001248 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001249
1250 MadeChange = true;
1251
1252 TruncTheUse = InsertedTrunc;
1253 }
1254 }
1255 return MadeChange;
1256}
1257
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001258/// Sink the shift *right* instruction into user blocks if the uses could
1259/// potentially be combined with this shift instruction and generate BitExtract
1260/// instruction. It will only be applied if the architecture supports BitExtract
1261/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001262/// BB1:
1263/// %x.extract.shift = lshr i64 %arg1, 32
1264/// BB2:
1265/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1266/// ==>
1267///
1268/// BB2:
1269/// %x.extract.shift.1 = lshr i64 %arg1, 32
1270/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1271///
1272/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1273/// instruction.
1274/// Return true if any changes are made.
1275static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001276 const TargetLowering &TLI,
1277 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001278 BasicBlock *DefBB = ShiftI->getParent();
1279
1280 /// Only insert instructions in each block once.
1281 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1282
Mehdi Amini44ede332015-07-09 02:09:04 +00001283 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001284
1285 bool MadeChange = false;
1286 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1287 UI != E;) {
1288 Use &TheUse = UI.getUse();
1289 Instruction *User = cast<Instruction>(*UI);
1290 // Preincrement use iterator so we don't invalidate it.
1291 ++UI;
1292
1293 // Don't bother for PHI nodes.
1294 if (isa<PHINode>(User))
1295 continue;
1296
1297 if (!isExtractBitsCandidateUse(User))
1298 continue;
1299
1300 BasicBlock *UserBB = User->getParent();
1301
1302 if (UserBB == DefBB) {
1303 // If the shift and truncate instruction are in the same BB. The use of
1304 // the truncate(TruncUse) may still introduce another truncate if not
1305 // legal. In this case, we would like to sink both shift and truncate
1306 // instruction to the BB of TruncUse.
1307 // for example:
1308 // BB1:
1309 // i64 shift.result = lshr i64 opnd, imm
1310 // trunc.result = trunc shift.result to i16
1311 //
1312 // BB2:
1313 // ----> We will have an implicit truncate here if the architecture does
1314 // not have i16 compare.
1315 // cmp i16 trunc.result, opnd2
1316 //
1317 if (isa<TruncInst>(User) && shiftIsLegal
1318 // If the type of the truncate is legal, no trucate will be
1319 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001320 &&
1321 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001322 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001323 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001324
1325 continue;
1326 }
1327 // If we have already inserted a shift into this block, use it.
1328 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1329
1330 if (!InsertedShift) {
1331 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001332 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001333
1334 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001335 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1336 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001337 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001338 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1339 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001340
1341 MadeChange = true;
1342 }
1343
1344 // Replace a use of the shift with a use of the new shift.
1345 TheUse = InsertedShift;
1346 }
1347
1348 // If we removed all uses, nuke the shift.
1349 if (ShiftI->use_empty())
1350 ShiftI->eraseFromParent();
1351
1352 return MadeChange;
1353}
1354
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001355// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001356// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1357// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001358// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001359// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001360//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001361// %1 = bitcast i8* %addr to i32*
1362// %2 = extractelement <16 x i1> %mask, i32 0
1363// %3 = icmp eq i1 %2, true
1364// br i1 %3, label %cond.load, label %else
1365//
1366//cond.load: ; preds = %0
1367// %4 = getelementptr i32* %1, i32 0
1368// %5 = load i32* %4
1369// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1370// br label %else
1371//
1372//else: ; preds = %0, %cond.load
1373// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1374// %7 = extractelement <16 x i1> %mask, i32 1
1375// %8 = icmp eq i1 %7, true
1376// br i1 %8, label %cond.load1, label %else2
1377//
1378//cond.load1: ; preds = %else
1379// %9 = getelementptr i32* %1, i32 1
1380// %10 = load i32* %9
1381// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1382// br label %else2
1383//
1384//else2: ; preds = %else, %cond.load1
1385// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1386// %12 = extractelement <16 x i1> %mask, i32 2
1387// %13 = icmp eq i1 %12, true
1388// br i1 %13, label %cond.load4, label %else5
1389//
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001390static void scalarizeMaskedLoad(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001391 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001392 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001393 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001394 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001395
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001396 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1397 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001398 assert(VecType && "Unexpected return type of masked load intrinsic");
1399
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001400 Type *EltTy = CI->getType()->getVectorElementType();
1401
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001402 IRBuilder<> Builder(CI->getContext());
1403 Instruction *InsertPt = CI;
1404 BasicBlock *IfBlock = CI->getParent();
1405 BasicBlock *CondBlock = nullptr;
1406 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001407
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001408 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001409 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1410
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001411 // Short-cut if the mask is all-true.
1412 bool IsAllOnesMask = isa<Constant>(Mask) &&
1413 cast<Constant>(Mask)->isAllOnesValue();
1414
1415 if (IsAllOnesMask) {
1416 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1417 CI->replaceAllUsesWith(NewI);
1418 CI->eraseFromParent();
1419 return;
1420 }
1421
1422 // Adjust alignment for the scalar instruction.
1423 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001424 // Bitcast %addr fron i8* to EltTy*
1425 Type *NewPtrType =
1426 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1427 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001428 unsigned VectorWidth = VecType->getNumElements();
1429
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001430 Value *UndefVal = UndefValue::get(VecType);
1431
1432 // The result vector
1433 Value *VResult = UndefVal;
1434
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001435 if (isa<ConstantVector>(Mask)) {
1436 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1437 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1438 continue;
1439 Value *Gep =
1440 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1441 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1442 VResult = Builder.CreateInsertElement(VResult, Load,
1443 Builder.getInt32(Idx));
1444 }
1445 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1446 CI->replaceAllUsesWith(NewI);
1447 CI->eraseFromParent();
1448 return;
1449 }
1450
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001451 PHINode *Phi = nullptr;
1452 Value *PrevPhi = UndefVal;
1453
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001454 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1455
1456 // Fill the "else" block, created in the previous iteration
1457 //
1458 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1459 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1460 // %to_load = icmp eq i1 %mask_1, true
1461 // br i1 %to_load, label %cond.load, label %else
1462 //
1463 if (Idx > 0) {
1464 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1465 Phi->addIncoming(VResult, CondBlock);
1466 Phi->addIncoming(PrevPhi, PrevIfBlock);
1467 PrevPhi = Phi;
1468 VResult = Phi;
1469 }
1470
1471 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1472 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1473 ConstantInt::get(Predicate->getType(), 1));
1474
1475 // Create "cond" block
1476 //
1477 // %EltAddr = getelementptr i32* %1, i32 0
1478 // %Elt = load i32* %EltAddr
1479 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1480 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001481 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001482 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001483
1484 Value *Gep =
1485 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001486 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001487 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1488
1489 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001490 BasicBlock *NewIfBlock =
1491 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001492 Builder.SetInsertPoint(InsertPt);
1493 Instruction *OldBr = IfBlock->getTerminator();
1494 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1495 OldBr->eraseFromParent();
1496 PrevIfBlock = IfBlock;
1497 IfBlock = NewIfBlock;
1498 }
1499
1500 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1501 Phi->addIncoming(VResult, CondBlock);
1502 Phi->addIncoming(PrevPhi, PrevIfBlock);
1503 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1504 CI->replaceAllUsesWith(NewI);
1505 CI->eraseFromParent();
1506}
1507
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001508// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001509// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1510// <16 x i1> %mask)
1511// to a chain of basic blocks, that stores element one-by-one if
1512// the appropriate mask bit is set
1513//
1514// %1 = bitcast i8* %addr to i32*
1515// %2 = extractelement <16 x i1> %mask, i32 0
1516// %3 = icmp eq i1 %2, true
1517// br i1 %3, label %cond.store, label %else
1518//
1519// cond.store: ; preds = %0
1520// %4 = extractelement <16 x i32> %val, i32 0
1521// %5 = getelementptr i32* %1, i32 0
1522// store i32 %4, i32* %5
1523// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001524//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001525// else: ; preds = %0, %cond.store
1526// %6 = extractelement <16 x i1> %mask, i32 1
1527// %7 = icmp eq i1 %6, true
1528// br i1 %7, label %cond.store1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001529//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001530// cond.store1: ; preds = %else
1531// %8 = extractelement <16 x i32> %val, i32 1
1532// %9 = getelementptr i32* %1, i32 1
1533// store i32 %8, i32* %9
1534// br label %else2
1535// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001536static void scalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001537 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001538 Value *Ptr = CI->getArgOperand(1);
1539 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001540 Value *Mask = CI->getArgOperand(3);
1541
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001542 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001543 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001544 assert(VecType && "Unexpected data type in masked store intrinsic");
1545
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001546 Type *EltTy = VecType->getElementType();
1547
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001548 IRBuilder<> Builder(CI->getContext());
1549 Instruction *InsertPt = CI;
1550 BasicBlock *IfBlock = CI->getParent();
1551 Builder.SetInsertPoint(InsertPt);
1552 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1553
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001554 // Short-cut if the mask is all-true.
1555 bool IsAllOnesMask = isa<Constant>(Mask) &&
1556 cast<Constant>(Mask)->isAllOnesValue();
1557
1558 if (IsAllOnesMask) {
1559 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1560 CI->eraseFromParent();
1561 return;
1562 }
1563
1564 // Adjust alignment for the scalar instruction.
1565 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001566 // Bitcast %addr fron i8* to EltTy*
1567 Type *NewPtrType =
1568 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1569 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001570 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001571
1572 if (isa<ConstantVector>(Mask)) {
1573 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1574 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1575 continue;
1576 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1577 Value *Gep =
1578 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1579 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1580 }
1581 CI->eraseFromParent();
1582 return;
1583 }
1584
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001585 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1586
1587 // Fill the "else" block, created in the previous iteration
1588 //
1589 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1590 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001591 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001592 //
1593 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1594 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1595 ConstantInt::get(Predicate->getType(), 1));
1596
1597 // Create "cond" block
1598 //
1599 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1600 // %EltAddr = getelementptr i32* %1, i32 0
1601 // %store i32 %OneElt, i32* %EltAddr
1602 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001603 BasicBlock *CondBlock =
1604 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001605 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001606
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001607 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001608 Value *Gep =
1609 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001610 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001611
1612 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001613 BasicBlock *NewIfBlock =
1614 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001615 Builder.SetInsertPoint(InsertPt);
1616 Instruction *OldBr = IfBlock->getTerminator();
1617 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1618 OldBr->eraseFromParent();
1619 IfBlock = NewIfBlock;
1620 }
1621 CI->eraseFromParent();
1622}
1623
Elena Demikhovsky09285852015-10-25 15:37:55 +00001624// Translate a masked gather intrinsic like
1625// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1626// <16 x i1> %Mask, <16 x i32> %Src)
1627// to a chain of basic blocks, with loading element one-by-one if
1628// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001629//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001630// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1631// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1632// % ToLoad0 = icmp eq i1 % Mask0, true
1633// br i1 % ToLoad0, label %cond.load, label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001634//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001635// cond.load:
1636// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1637// % Load0 = load i32, i32* % Ptr0, align 4
1638// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1639// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001640//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001641// else:
1642// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1643// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1644// % ToLoad1 = icmp eq i1 % Mask1, true
1645// br i1 % ToLoad1, label %cond.load1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001646//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001647// cond.load1:
1648// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1649// % Load1 = load i32, i32* % Ptr1, align 4
1650// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1651// br label %else2
1652// . . .
1653// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1654// ret <16 x i32> %Result
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001655static void scalarizeMaskedGather(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001656 Value *Ptrs = CI->getArgOperand(0);
1657 Value *Alignment = CI->getArgOperand(1);
1658 Value *Mask = CI->getArgOperand(2);
1659 Value *Src0 = CI->getArgOperand(3);
1660
1661 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1662
1663 assert(VecType && "Unexpected return type of masked load intrinsic");
1664
1665 IRBuilder<> Builder(CI->getContext());
1666 Instruction *InsertPt = CI;
1667 BasicBlock *IfBlock = CI->getParent();
1668 BasicBlock *CondBlock = nullptr;
1669 BasicBlock *PrevIfBlock = CI->getParent();
1670 Builder.SetInsertPoint(InsertPt);
1671 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1672
1673 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1674
1675 Value *UndefVal = UndefValue::get(VecType);
1676
1677 // The result vector
1678 Value *VResult = UndefVal;
1679 unsigned VectorWidth = VecType->getNumElements();
1680
1681 // Shorten the way if the mask is a vector of constants.
1682 bool IsConstMask = isa<ConstantVector>(Mask);
1683
1684 if (IsConstMask) {
1685 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1686 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1687 continue;
1688 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1689 "Ptr" + Twine(Idx));
1690 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1691 "Load" + Twine(Idx));
1692 VResult = Builder.CreateInsertElement(VResult, Load,
1693 Builder.getInt32(Idx),
1694 "Res" + Twine(Idx));
1695 }
1696 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1697 CI->replaceAllUsesWith(NewI);
1698 CI->eraseFromParent();
1699 return;
1700 }
1701
1702 PHINode *Phi = nullptr;
1703 Value *PrevPhi = UndefVal;
1704
1705 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1706
1707 // Fill the "else" block, created in the previous iteration
1708 //
1709 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1710 // %ToLoad1 = icmp eq i1 %Mask1, true
1711 // br i1 %ToLoad1, label %cond.load, label %else
1712 //
1713 if (Idx > 0) {
1714 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1715 Phi->addIncoming(VResult, CondBlock);
1716 Phi->addIncoming(PrevPhi, PrevIfBlock);
1717 PrevPhi = Phi;
1718 VResult = Phi;
1719 }
1720
1721 Value *Predicate = Builder.CreateExtractElement(Mask,
1722 Builder.getInt32(Idx),
1723 "Mask" + Twine(Idx));
1724 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1725 ConstantInt::get(Predicate->getType(), 1),
1726 "ToLoad" + Twine(Idx));
1727
1728 // Create "cond" block
1729 //
1730 // %EltAddr = getelementptr i32* %1, i32 0
1731 // %Elt = load i32* %EltAddr
1732 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1733 //
1734 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1735 Builder.SetInsertPoint(InsertPt);
1736
1737 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1738 "Ptr" + Twine(Idx));
1739 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1740 "Load" + Twine(Idx));
1741 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1742 "Res" + Twine(Idx));
1743
1744 // Create "else" block, fill it in the next iteration
1745 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1746 Builder.SetInsertPoint(InsertPt);
1747 Instruction *OldBr = IfBlock->getTerminator();
1748 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1749 OldBr->eraseFromParent();
1750 PrevIfBlock = IfBlock;
1751 IfBlock = NewIfBlock;
1752 }
1753
1754 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1755 Phi->addIncoming(VResult, CondBlock);
1756 Phi->addIncoming(PrevPhi, PrevIfBlock);
1757 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1758 CI->replaceAllUsesWith(NewI);
1759 CI->eraseFromParent();
1760}
1761
1762// Translate a masked scatter intrinsic, like
1763// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1764// <16 x i1> %Mask)
1765// to a chain of basic blocks, that stores element one-by-one if
1766// the appropriate mask bit is set.
1767//
1768// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1769// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1770// % ToStore0 = icmp eq i1 % Mask0, true
1771// br i1 %ToStore0, label %cond.store, label %else
1772//
1773// cond.store:
1774// % Elt0 = extractelement <16 x i32> %Src, i32 0
1775// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1776// store i32 %Elt0, i32* % Ptr0, align 4
1777// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001778//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001779// else:
1780// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1781// % ToStore1 = icmp eq i1 % Mask1, true
1782// br i1 % ToStore1, label %cond.store1, label %else2
1783//
1784// cond.store1:
1785// % Elt1 = extractelement <16 x i32> %Src, i32 1
1786// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1787// store i32 % Elt1, i32* % Ptr1, align 4
1788// br label %else2
1789// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001790static void scalarizeMaskedScatter(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001791 Value *Src = CI->getArgOperand(0);
1792 Value *Ptrs = CI->getArgOperand(1);
1793 Value *Alignment = CI->getArgOperand(2);
1794 Value *Mask = CI->getArgOperand(3);
1795
1796 assert(isa<VectorType>(Src->getType()) &&
1797 "Unexpected data type in masked scatter intrinsic");
1798 assert(isa<VectorType>(Ptrs->getType()) &&
1799 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1800 "Vector of pointers is expected in masked scatter intrinsic");
1801
1802 IRBuilder<> Builder(CI->getContext());
1803 Instruction *InsertPt = CI;
1804 BasicBlock *IfBlock = CI->getParent();
1805 Builder.SetInsertPoint(InsertPt);
1806 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1807
1808 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1809 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1810
1811 // Shorten the way if the mask is a vector of constants.
1812 bool IsConstMask = isa<ConstantVector>(Mask);
1813
1814 if (IsConstMask) {
1815 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1816 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1817 continue;
1818 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1819 "Elt" + Twine(Idx));
1820 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1821 "Ptr" + Twine(Idx));
1822 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1823 }
1824 CI->eraseFromParent();
1825 return;
1826 }
1827 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1828 // Fill the "else" block, created in the previous iteration
1829 //
1830 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1831 // % ToStore = icmp eq i1 % Mask1, true
1832 // br i1 % ToStore, label %cond.store, label %else
1833 //
1834 Value *Predicate = Builder.CreateExtractElement(Mask,
1835 Builder.getInt32(Idx),
1836 "Mask" + Twine(Idx));
1837 Value *Cmp =
1838 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1839 ConstantInt::get(Predicate->getType(), 1),
1840 "ToStore" + Twine(Idx));
1841
1842 // Create "cond" block
1843 //
1844 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1845 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1846 // %store i32 % Elt1, i32* % Ptr1
1847 //
1848 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1849 Builder.SetInsertPoint(InsertPt);
1850
1851 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1852 "Elt" + Twine(Idx));
1853 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1854 "Ptr" + Twine(Idx));
1855 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1856
1857 // Create "else" block, fill it in the next iteration
1858 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1859 Builder.SetInsertPoint(InsertPt);
1860 Instruction *OldBr = IfBlock->getTerminator();
1861 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1862 OldBr->eraseFromParent();
1863 IfBlock = NewIfBlock;
1864 }
1865 CI->eraseFromParent();
1866}
1867
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001868/// If counting leading or trailing zeros is an expensive operation and a zero
1869/// input is defined, add a check for zero to avoid calling the intrinsic.
1870///
1871/// We want to transform:
1872/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1873///
1874/// into:
1875/// entry:
1876/// %cmpz = icmp eq i64 %A, 0
1877/// br i1 %cmpz, label %cond.end, label %cond.false
1878/// cond.false:
1879/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1880/// br label %cond.end
1881/// cond.end:
1882/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1883///
1884/// If the transform is performed, return true and set ModifiedDT to true.
1885static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1886 const TargetLowering *TLI,
1887 const DataLayout *DL,
1888 bool &ModifiedDT) {
1889 if (!TLI || !DL)
1890 return false;
1891
1892 // If a zero input is undefined, it doesn't make sense to despeculate that.
1893 if (match(CountZeros->getOperand(1), m_One()))
1894 return false;
1895
1896 // If it's cheap to speculate, there's nothing to do.
1897 auto IntrinsicID = CountZeros->getIntrinsicID();
1898 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1899 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1900 return false;
1901
1902 // Only handle legal scalar cases. Anything else requires too much work.
1903 Type *Ty = CountZeros->getType();
1904 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001905 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001906 return false;
1907
1908 // The intrinsic will be sunk behind a compare against zero and branch.
1909 BasicBlock *StartBlock = CountZeros->getParent();
1910 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1911
1912 // Create another block after the count zero intrinsic. A PHI will be added
1913 // in this block to select the result of the intrinsic or the bit-width
1914 // constant if the input to the intrinsic is zero.
1915 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1916 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1917
1918 // Set up a builder to create a compare, conditional branch, and PHI.
1919 IRBuilder<> Builder(CountZeros->getContext());
1920 Builder.SetInsertPoint(StartBlock->getTerminator());
1921 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1922
1923 // Replace the unconditional branch that was created by the first split with
1924 // a compare against zero and a conditional branch.
1925 Value *Zero = Constant::getNullValue(Ty);
1926 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1927 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1928 StartBlock->getTerminator()->eraseFromParent();
1929
1930 // Create a PHI in the end block to select either the output of the intrinsic
1931 // or the bit width of the operand.
1932 Builder.SetInsertPoint(&EndBlock->front());
1933 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1934 CountZeros->replaceAllUsesWith(PN);
1935 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1936 PN->addIncoming(BitWidth, StartBlock);
1937 PN->addIncoming(CountZeros, CallBlock);
1938
1939 // We are explicitly handling the zero case, so we can set the intrinsic's
1940 // undefined zero argument to 'true'. This will also prevent reprocessing the
1941 // intrinsic; we only despeculate when a zero input is defined.
1942 CountZeros->setArgOperand(1, Builder.getTrue());
1943 ModifiedDT = true;
1944 return true;
1945}
1946
Sanjay Patelfc580a62015-09-21 23:03:16 +00001947bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001948 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001949
Chris Lattner7a277142011-01-15 07:14:54 +00001950 // Lower inline assembly if we can.
1951 // If we found an inline asm expession, and if the target knows how to
1952 // lower it to normal LLVM code, do so now.
1953 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1954 if (TLI->ExpandInlineAsm(CI)) {
1955 // Avoid invalidating the iterator.
1956 CurInstIterator = BB->begin();
1957 // Avoid processing instructions out of order, which could cause
1958 // reuse before a value is defined.
1959 SunkAddrs.clear();
1960 return true;
1961 }
1962 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001963 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001964 return true;
1965 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001966
John Brawn0dbcd652015-03-18 12:01:59 +00001967 // Align the pointer arguments to this call if the target thinks it's a good
1968 // idea
1969 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001970 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001971 for (auto &Arg : CI->arg_operands()) {
1972 // We want to align both objects whose address is used directly and
1973 // objects whose address is used in casts and GEPs, though it only makes
1974 // sense for GEPs if the offset is a multiple of the desired alignment and
1975 // if size - offset meets the size threshold.
1976 if (!Arg->getType()->isPointerTy())
1977 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001978 APInt Offset(DL->getPointerSizeInBits(
1979 cast<PointerType>(Arg->getType())->getAddressSpace()),
1980 0);
1981 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001982 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001983 if ((Offset2 & (PrefAlign-1)) != 0)
1984 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001985 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001986 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1987 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001988 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001989 // Global variables can only be aligned if they are defined in this
1990 // object (i.e. they are uniquely initialized in this object), and
1991 // over-aligning global variables that have an explicit section is
1992 // forbidden.
1993 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001994 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001995 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001996 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001997 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001998 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001999 }
2000 // If this is a memcpy (or similar) then we may be able to improve the
2001 // alignment
2002 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00002003 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00002004 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00002005 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00002006 if (Align > MI->getAlignment())
2007 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00002008 }
2009 }
2010
Philip Reamesac115ed2016-03-09 23:13:12 +00002011 // If we have a cold call site, try to sink addressing computation into the
2012 // cold block. This interacts with our handling for loads and stores to
2013 // ensure that we can fold all uses of a potential addressing computation
2014 // into their uses. TODO: generalize this to work over profiling data
2015 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
2016 for (auto &Arg : CI->arg_operands()) {
2017 if (!Arg->getType()->isPointerTy())
2018 continue;
2019 unsigned AS = Arg->getType()->getPointerAddressSpace();
2020 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
2021 }
Junmo Park6098cbb2016-03-11 07:05:32 +00002022
Eric Christopher4b7948e2010-03-11 02:41:03 +00002023 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002024 if (II) {
2025 switch (II->getIntrinsicID()) {
2026 default: break;
2027 case Intrinsic::objectsize: {
2028 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00002029 ConstantInt *RetVal =
2030 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002031 // Substituting this can cause recursive simplifications, which can
2032 // invalidate our iterator. Use a WeakVH to hold onto it in case this
2033 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00002034 Value *CurValue = &*CurInstIterator;
2035 WeakVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00002036
Sanjay Patel545a4562016-01-20 18:59:16 +00002037 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00002038
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002039 // If the iterator instruction was recursively deleted, start over at the
2040 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00002041 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002042 CurInstIterator = BB->begin();
2043 SunkAddrs.clear();
2044 }
2045 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00002046 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002047 case Intrinsic::masked_load: {
2048 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00002049 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002050 scalarizeMaskedLoad(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002051 ModifiedDT = true;
2052 return true;
2053 }
2054 return false;
2055 }
2056 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00002057 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002058 scalarizeMaskedStore(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002059 ModifiedDT = true;
2060 return true;
2061 }
2062 return false;
2063 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00002064 case Intrinsic::masked_gather: {
2065 if (!TTI->isLegalMaskedGather(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002066 scalarizeMaskedGather(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00002067 ModifiedDT = true;
2068 return true;
2069 }
2070 return false;
2071 }
2072 case Intrinsic::masked_scatter: {
2073 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002074 scalarizeMaskedScatter(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00002075 ModifiedDT = true;
2076 return true;
2077 }
2078 return false;
2079 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002080 case Intrinsic::aarch64_stlxr:
2081 case Intrinsic::aarch64_stxr: {
2082 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2083 if (!ExtVal || !ExtVal->hasOneUse() ||
2084 ExtVal->getParent() == CI->getParent())
2085 return false;
2086 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2087 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002088 // Mark this instruction as "inserted by CGP", so that other
2089 // optimizations don't touch it.
2090 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002091 return true;
2092 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00002093 case Intrinsic::invariant_group_barrier:
2094 II->replaceAllUsesWith(II->getArgOperand(0));
2095 II->eraseFromParent();
2096 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00002097
2098 case Intrinsic::cttz:
2099 case Intrinsic::ctlz:
2100 // If counting zeros is expensive, try to avoid it.
2101 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002102 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00002103
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002104 if (TLI) {
2105 SmallVector<Value*, 2> PtrOps;
2106 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00002107 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2108 while (!PtrOps.empty()) {
2109 Value *PtrVal = PtrOps.pop_back_val();
2110 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2111 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002112 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00002113 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002114 }
Pete Cooper615fd892012-03-13 20:59:56 +00002115 }
2116
Eric Christopher4b7948e2010-03-11 02:41:03 +00002117 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00002118 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00002119
Benjamin Kramer7b88a492010-03-12 09:27:41 +00002120 // Lower all default uses of _chk calls. This is very similar
2121 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002122 // to fortified library functions (e.g. __memcpy_chk) that have the default
2123 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002124 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002125 if (Value *V = Simplifier.optimizeCall(CI)) {
2126 CI->replaceAllUsesWith(V);
2127 CI->eraseFromParent();
2128 return true;
2129 }
2130 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00002131}
Chris Lattner1b93be52011-01-15 07:25:29 +00002132
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002133/// Look for opportunities to duplicate return instructions to the predecessor
2134/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002135/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002136/// bb0:
2137/// %tmp0 = tail call i32 @f0()
2138/// br label %return
2139/// bb1:
2140/// %tmp1 = tail call i32 @f1()
2141/// br label %return
2142/// bb2:
2143/// %tmp2 = tail call i32 @f2()
2144/// br label %return
2145/// return:
2146/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2147/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002148/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00002149///
2150/// =>
2151///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002152/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002153/// bb0:
2154/// %tmp0 = tail call i32 @f0()
2155/// ret i32 %tmp0
2156/// bb1:
2157/// %tmp1 = tail call i32 @f1()
2158/// ret i32 %tmp1
2159/// bb2:
2160/// %tmp2 = tail call i32 @f2()
2161/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002162/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00002163bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00002164 if (!TLI)
2165 return false;
2166
Michael Kuperstein71321562016-09-07 20:29:49 +00002167 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2168 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00002169 return false;
2170
Craig Topperc0196b12014-04-14 00:51:57 +00002171 PHINode *PN = nullptr;
2172 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00002173 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00002174 if (V) {
2175 BCI = dyn_cast<BitCastInst>(V);
2176 if (BCI)
2177 V = BCI->getOperand(0);
2178
2179 PN = dyn_cast<PHINode>(V);
2180 if (!PN)
2181 return false;
2182 }
Evan Cheng0663f232011-03-21 01:19:09 +00002183
Cameron Zwarich4649f172011-03-24 04:52:10 +00002184 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002185 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00002186
Cameron Zwarich4649f172011-03-24 04:52:10 +00002187 // Make sure there are no instructions between the PHI and return, or that the
2188 // return is the first instruction in the block.
2189 if (PN) {
2190 BasicBlock::iterator BI = BB->begin();
2191 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00002192 if (&*BI == BCI)
2193 // Also skip over the bitcast.
2194 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002195 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002196 return false;
2197 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002198 BasicBlock::iterator BI = BB->begin();
2199 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002200 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002201 return false;
2202 }
Evan Cheng0663f232011-03-21 01:19:09 +00002203
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002204 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2205 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002206 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002207 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00002208 if (PN) {
2209 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2210 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2211 // Make sure the phi value is indeed produced by the tail call.
2212 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002213 TLI->mayBeEmittedAsTailCall(CI) &&
2214 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002215 TailCalls.push_back(CI);
2216 }
2217 } else {
2218 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002219 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002220 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002221 continue;
2222
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002223 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002224 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2225 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002226 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2227 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002228 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002229
Cameron Zwarich4649f172011-03-24 04:52:10 +00002230 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002231 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2232 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002233 TailCalls.push_back(CI);
2234 }
Evan Cheng0663f232011-03-21 01:19:09 +00002235 }
2236
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002237 bool Changed = false;
2238 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2239 CallInst *CI = TailCalls[i];
2240 CallSite CS(CI);
2241
2242 // Conservatively require the attributes of the call to match those of the
2243 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00002244 AttributeSet CalleeAttrs = CS.getAttributes();
2245 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002246 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00002247 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002248 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002249 continue;
2250
2251 // Make sure the call instruction is followed by an unconditional branch to
2252 // the return block.
2253 BasicBlock *CallBB = CI->getParent();
2254 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2255 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2256 continue;
2257
2258 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002259 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002260 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002261 ++NumRetsDup;
2262 }
2263
2264 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002265 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002266 BB->eraseFromParent();
2267
2268 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002269}
2270
Chris Lattner728f9022008-11-25 07:09:13 +00002271//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002272// Memory Optimization
2273//===----------------------------------------------------------------------===//
2274
Chandler Carruthc8925912013-01-05 02:09:22 +00002275namespace {
2276
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002277/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002278/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002279struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002280 Value *BaseReg;
2281 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002282 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002283 void print(raw_ostream &OS) const;
2284 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002285
Chandler Carruthc8925912013-01-05 02:09:22 +00002286 bool operator==(const ExtAddrMode& O) const {
2287 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2288 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2289 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2290 }
2291};
2292
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002293#ifndef NDEBUG
2294static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2295 AM.print(OS);
2296 return OS;
2297}
2298#endif
2299
Chandler Carruthc8925912013-01-05 02:09:22 +00002300void ExtAddrMode::print(raw_ostream &OS) const {
2301 bool NeedPlus = false;
2302 OS << "[";
2303 if (BaseGV) {
2304 OS << (NeedPlus ? " + " : "")
2305 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002306 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002307 NeedPlus = true;
2308 }
2309
Richard Trieuc0f91212014-05-30 03:15:17 +00002310 if (BaseOffs) {
2311 OS << (NeedPlus ? " + " : "")
2312 << BaseOffs;
2313 NeedPlus = true;
2314 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002315
2316 if (BaseReg) {
2317 OS << (NeedPlus ? " + " : "")
2318 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002319 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002320 NeedPlus = true;
2321 }
2322 if (Scale) {
2323 OS << (NeedPlus ? " + " : "")
2324 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002325 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002326 }
2327
2328 OS << ']';
2329}
2330
2331#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002332LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002333 print(dbgs());
2334 dbgs() << '\n';
2335}
2336#endif
2337
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002338/// \brief This class provides transaction based operation on the IR.
2339/// Every change made through this class is recorded in the internal state and
2340/// can be undone (rollback) until commit is called.
2341class TypePromotionTransaction {
2342
2343 /// \brief This represents the common interface of the individual transaction.
2344 /// Each class implements the logic for doing one specific modification on
2345 /// the IR via the TypePromotionTransaction.
2346 class TypePromotionAction {
2347 protected:
2348 /// The Instruction modified.
2349 Instruction *Inst;
2350
2351 public:
2352 /// \brief Constructor of the action.
2353 /// The constructor performs the related action on the IR.
2354 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2355
2356 virtual ~TypePromotionAction() {}
2357
2358 /// \brief Undo the modification done by this action.
2359 /// When this method is called, the IR must be in the same state as it was
2360 /// before this action was applied.
2361 /// \pre Undoing the action works if and only if the IR is in the exact same
2362 /// state as it was directly after this action was applied.
2363 virtual void undo() = 0;
2364
2365 /// \brief Advocate every change made by this action.
2366 /// When the results on the IR of the action are to be kept, it is important
2367 /// to call this function, otherwise hidden information may be kept forever.
2368 virtual void commit() {
2369 // Nothing to be done, this action is not doing anything.
2370 }
2371 };
2372
2373 /// \brief Utility to remember the position of an instruction.
2374 class InsertionHandler {
2375 /// Position of an instruction.
2376 /// Either an instruction:
2377 /// - Is the first in a basic block: BB is used.
2378 /// - Has a previous instructon: PrevInst is used.
2379 union {
2380 Instruction *PrevInst;
2381 BasicBlock *BB;
2382 } Point;
2383 /// Remember whether or not the instruction had a previous instruction.
2384 bool HasPrevInstruction;
2385
2386 public:
2387 /// \brief Record the position of \p Inst.
2388 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002389 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002390 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2391 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002392 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002393 else
2394 Point.BB = Inst->getParent();
2395 }
2396
2397 /// \brief Insert \p Inst at the recorded position.
2398 void insert(Instruction *Inst) {
2399 if (HasPrevInstruction) {
2400 if (Inst->getParent())
2401 Inst->removeFromParent();
2402 Inst->insertAfter(Point.PrevInst);
2403 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002404 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002405 if (Inst->getParent())
2406 Inst->moveBefore(Position);
2407 else
2408 Inst->insertBefore(Position);
2409 }
2410 }
2411 };
2412
2413 /// \brief Move an instruction before another.
2414 class InstructionMoveBefore : public TypePromotionAction {
2415 /// Original position of the instruction.
2416 InsertionHandler Position;
2417
2418 public:
2419 /// \brief Move \p Inst before \p Before.
2420 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2421 : TypePromotionAction(Inst), Position(Inst) {
2422 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2423 Inst->moveBefore(Before);
2424 }
2425
2426 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002427 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002428 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2429 Position.insert(Inst);
2430 }
2431 };
2432
2433 /// \brief Set the operand of an instruction with a new value.
2434 class OperandSetter : public TypePromotionAction {
2435 /// Original operand of the instruction.
2436 Value *Origin;
2437 /// Index of the modified instruction.
2438 unsigned Idx;
2439
2440 public:
2441 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2442 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2443 : TypePromotionAction(Inst), Idx(Idx) {
2444 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2445 << "for:" << *Inst << "\n"
2446 << "with:" << *NewVal << "\n");
2447 Origin = Inst->getOperand(Idx);
2448 Inst->setOperand(Idx, NewVal);
2449 }
2450
2451 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002452 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002453 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2454 << "for: " << *Inst << "\n"
2455 << "with: " << *Origin << "\n");
2456 Inst->setOperand(Idx, Origin);
2457 }
2458 };
2459
2460 /// \brief Hide the operands of an instruction.
2461 /// Do as if this instruction was not using any of its operands.
2462 class OperandsHider : public TypePromotionAction {
2463 /// The list of original operands.
2464 SmallVector<Value *, 4> OriginalValues;
2465
2466 public:
2467 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2468 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2469 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2470 unsigned NumOpnds = Inst->getNumOperands();
2471 OriginalValues.reserve(NumOpnds);
2472 for (unsigned It = 0; It < NumOpnds; ++It) {
2473 // Save the current operand.
2474 Value *Val = Inst->getOperand(It);
2475 OriginalValues.push_back(Val);
2476 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002477 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002478 // that we are not willing to pay.
2479 Inst->setOperand(It, UndefValue::get(Val->getType()));
2480 }
2481 }
2482
2483 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002484 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002485 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2486 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2487 Inst->setOperand(It, OriginalValues[It]);
2488 }
2489 };
2490
2491 /// \brief Build a truncate instruction.
2492 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002493 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002494 public:
2495 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2496 /// result.
2497 /// trunc Opnd to Ty.
2498 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2499 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002500 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2501 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002502 }
2503
Quentin Colombetac55b152014-09-16 22:36:07 +00002504 /// \brief Get the built value.
2505 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002506
2507 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002508 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002509 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2510 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2511 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002512 }
2513 };
2514
2515 /// \brief Build a sign extension instruction.
2516 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002517 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002518 public:
2519 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2520 /// result.
2521 /// sext Opnd to Ty.
2522 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002523 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002524 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002525 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2526 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002527 }
2528
Quentin Colombetac55b152014-09-16 22:36:07 +00002529 /// \brief Get the built value.
2530 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002531
2532 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002533 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002534 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2535 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2536 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002537 }
2538 };
2539
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002540 /// \brief Build a zero extension instruction.
2541 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002542 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002543 public:
2544 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2545 /// result.
2546 /// zext Opnd to Ty.
2547 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002548 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002549 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002550 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2551 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002552 }
2553
Quentin Colombetac55b152014-09-16 22:36:07 +00002554 /// \brief Get the built value.
2555 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002556
2557 /// \brief Remove the built instruction.
2558 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002559 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2560 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2561 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002562 }
2563 };
2564
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002565 /// \brief Mutate an instruction to another type.
2566 class TypeMutator : public TypePromotionAction {
2567 /// Record the original type.
2568 Type *OrigTy;
2569
2570 public:
2571 /// \brief Mutate the type of \p Inst into \p NewTy.
2572 TypeMutator(Instruction *Inst, Type *NewTy)
2573 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2574 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2575 << "\n");
2576 Inst->mutateType(NewTy);
2577 }
2578
2579 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002580 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002581 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2582 << "\n");
2583 Inst->mutateType(OrigTy);
2584 }
2585 };
2586
2587 /// \brief Replace the uses of an instruction by another instruction.
2588 class UsesReplacer : public TypePromotionAction {
2589 /// Helper structure to keep track of the replaced uses.
2590 struct InstructionAndIdx {
2591 /// The instruction using the instruction.
2592 Instruction *Inst;
2593 /// The index where this instruction is used for Inst.
2594 unsigned Idx;
2595 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2596 : Inst(Inst), Idx(Idx) {}
2597 };
2598
2599 /// Keep track of the original uses (pair Instruction, Index).
2600 SmallVector<InstructionAndIdx, 4> OriginalUses;
2601 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2602
2603 public:
2604 /// \brief Replace all the use of \p Inst by \p New.
2605 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2606 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2607 << "\n");
2608 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002609 for (Use &U : Inst->uses()) {
2610 Instruction *UserI = cast<Instruction>(U.getUser());
2611 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002612 }
2613 // Now, we can replace the uses.
2614 Inst->replaceAllUsesWith(New);
2615 }
2616
2617 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002618 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002619 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2620 for (use_iterator UseIt = OriginalUses.begin(),
2621 EndIt = OriginalUses.end();
2622 UseIt != EndIt; ++UseIt) {
2623 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2624 }
2625 }
2626 };
2627
2628 /// \brief Remove an instruction from the IR.
2629 class InstructionRemover : public TypePromotionAction {
2630 /// Original position of the instruction.
2631 InsertionHandler Inserter;
2632 /// Helper structure to hide all the link to the instruction. In other
2633 /// words, this helps to do as if the instruction was removed.
2634 OperandsHider Hider;
2635 /// Keep track of the uses replaced, if any.
2636 UsesReplacer *Replacer;
2637
2638 public:
2639 /// \brief Remove all reference of \p Inst and optinally replace all its
2640 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002641 /// \pre If !Inst->use_empty(), then New != nullptr
2642 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002643 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002644 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002645 if (New)
2646 Replacer = new UsesReplacer(Inst, New);
2647 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2648 Inst->removeFromParent();
2649 }
2650
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002651 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002652
2653 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002654 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002655
2656 /// \brief Resurrect the instruction and reassign it to the proper uses if
2657 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002658 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002659 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2660 Inserter.insert(Inst);
2661 if (Replacer)
2662 Replacer->undo();
2663 Hider.undo();
2664 }
2665 };
2666
2667public:
2668 /// Restoration point.
2669 /// The restoration point is a pointer to an action instead of an iterator
2670 /// because the iterator may be invalidated but not the pointer.
2671 typedef const TypePromotionAction *ConstRestorationPt;
2672 /// Advocate every changes made in that transaction.
2673 void commit();
2674 /// Undo all the changes made after the given point.
2675 void rollback(ConstRestorationPt Point);
2676 /// Get the current restoration point.
2677 ConstRestorationPt getRestorationPoint() const;
2678
2679 /// \name API for IR modification with state keeping to support rollback.
2680 /// @{
2681 /// Same as Instruction::setOperand.
2682 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2683 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002684 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002685 /// Same as Value::replaceAllUsesWith.
2686 void replaceAllUsesWith(Instruction *Inst, Value *New);
2687 /// Same as Value::mutateType.
2688 void mutateType(Instruction *Inst, Type *NewTy);
2689 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002690 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002691 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002692 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002693 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002694 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002695 /// Same as Instruction::moveBefore.
2696 void moveBefore(Instruction *Inst, Instruction *Before);
2697 /// @}
2698
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002699private:
2700 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002701 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2702 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002703};
2704
2705void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2706 Value *NewVal) {
2707 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002708 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002709}
2710
2711void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2712 Value *NewVal) {
2713 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002714 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002715}
2716
2717void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2718 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002719 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002720}
2721
2722void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002723 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002724}
2725
Quentin Colombetac55b152014-09-16 22:36:07 +00002726Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2727 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002728 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002729 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002730 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002731 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002732}
2733
Quentin Colombetac55b152014-09-16 22:36:07 +00002734Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2735 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002736 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002737 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002738 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002739 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002740}
2741
Quentin Colombetac55b152014-09-16 22:36:07 +00002742Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2743 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002744 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002745 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002746 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002747 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002748}
2749
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002750void TypePromotionTransaction::moveBefore(Instruction *Inst,
2751 Instruction *Before) {
2752 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002753 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002754}
2755
2756TypePromotionTransaction::ConstRestorationPt
2757TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002758 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002759}
2760
2761void TypePromotionTransaction::commit() {
2762 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002763 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002764 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002765 Actions.clear();
2766}
2767
2768void TypePromotionTransaction::rollback(
2769 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002770 while (!Actions.empty() && Point != Actions.back().get()) {
2771 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002772 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002773 }
2774}
2775
Chandler Carruthc8925912013-01-05 02:09:22 +00002776/// \brief A helper class for matching addressing modes.
2777///
2778/// This encapsulates the logic for matching the target-legal addressing modes.
2779class AddressingModeMatcher {
2780 SmallVectorImpl<Instruction*> &AddrModeInsts;
2781 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002782 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002783 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002784
2785 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2786 /// the memory instruction that we're computing this address for.
2787 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002788 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002789 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002790
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002791 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002792 /// part of the return value of this addressing mode matching stuff.
2793 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002794
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002795 /// The instructions inserted by other CodeGenPrepare optimizations.
2796 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002797 /// A map from the instructions to their type before promotion.
2798 InstrToOrigTy &PromotedInsts;
2799 /// The ongoing transaction where every action should be registered.
2800 TypePromotionTransaction &TPT;
2801
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002802 /// This is set to true when we should not do profitability checks.
2803 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002804 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002805
Eric Christopherd75c00c2015-02-26 22:38:34 +00002806 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002807 const TargetLowering &TLI,
2808 const TargetRegisterInfo &TRI,
2809 Type *AT, unsigned AS,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002810 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002811 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002812 InstrToOrigTy &PromotedInsts,
2813 TypePromotionTransaction &TPT)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002814 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002815 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2816 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2817 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002818 IgnoreProfitability = false;
2819 }
2820public:
Stephen Lin837bba12013-07-15 17:55:02 +00002821
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002822 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002823 /// give an access type of AccessTy. This returns a list of involved
2824 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002825 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002826 /// optimizations.
2827 /// \p PromotedInsts maps the instructions to their type before promotion.
2828 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002829 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002830 Instruction *MemoryInst,
2831 SmallVectorImpl<Instruction*> &AddrModeInsts,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002832 const TargetLowering &TLI,
2833 const TargetRegisterInfo &TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002834 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002835 InstrToOrigTy &PromotedInsts,
2836 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002837 ExtAddrMode Result;
2838
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002839 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
2840 AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002841 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002842 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002843 (void)Success; assert(Success && "Couldn't select *anything*?");
2844 return Result;
2845 }
2846private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002847 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2848 bool matchAddr(Value *V, unsigned Depth);
2849 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002850 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002851 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002852 ExtAddrMode &AMBefore,
2853 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002854 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2855 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002856 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002857};
2858
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002859/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002860/// Return true and update AddrMode if this addr mode is legal for the target,
2861/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002862bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002863 unsigned Depth) {
2864 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2865 // mode. Just process that directly.
2866 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002867 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002868
Chandler Carruthc8925912013-01-05 02:09:22 +00002869 // If the scale is 0, it takes nothing to add this.
2870 if (Scale == 0)
2871 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002872
Chandler Carruthc8925912013-01-05 02:09:22 +00002873 // If we already have a scale of this value, we can add to it, otherwise, we
2874 // need an available scale field.
2875 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2876 return false;
2877
2878 ExtAddrMode TestAddrMode = AddrMode;
2879
2880 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2881 // [A+B + A*7] -> [B+A*8].
2882 TestAddrMode.Scale += Scale;
2883 TestAddrMode.ScaledReg = ScaleReg;
2884
2885 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002886 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002887 return false;
2888
2889 // It was legal, so commit it.
2890 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002891
Chandler Carruthc8925912013-01-05 02:09:22 +00002892 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2893 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2894 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002895 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002896 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2897 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2898 TestAddrMode.ScaledReg = AddLHS;
2899 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002900
Chandler Carruthc8925912013-01-05 02:09:22 +00002901 // If this addressing mode is legal, commit it and remember that we folded
2902 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002903 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002904 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2905 AddrMode = TestAddrMode;
2906 return true;
2907 }
2908 }
2909
2910 // Otherwise, not (x+c)*scale, just return what we have.
2911 return true;
2912}
2913
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002914/// This is a little filter, which returns true if an addressing computation
2915/// involving I might be folded into a load/store accessing it.
2916/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002917/// the set of instructions that MatchOperationAddr can.
2918static bool MightBeFoldableInst(Instruction *I) {
2919 switch (I->getOpcode()) {
2920 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002921 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002922 // Don't touch identity bitcasts.
2923 if (I->getType() == I->getOperand(0)->getType())
2924 return false;
2925 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2926 case Instruction::PtrToInt:
2927 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2928 return true;
2929 case Instruction::IntToPtr:
2930 // We know the input is intptr_t, so this is foldable.
2931 return true;
2932 case Instruction::Add:
2933 return true;
2934 case Instruction::Mul:
2935 case Instruction::Shl:
2936 // Can only handle X*C and X << C.
2937 return isa<ConstantInt>(I->getOperand(1));
2938 case Instruction::GetElementPtr:
2939 return true;
2940 default:
2941 return false;
2942 }
2943}
2944
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002945/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2946/// \note \p Val is assumed to be the product of some type promotion.
2947/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2948/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002949static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2950 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002951 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2952 if (!PromotedInst)
2953 return false;
2954 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2955 // If the ISDOpcode is undefined, it was undefined before the promotion.
2956 if (!ISDOpcode)
2957 return true;
2958 // Otherwise, check if the promoted instruction is legal or not.
2959 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002960 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002961}
2962
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002963/// \brief Hepler class to perform type promotion.
2964class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002965 /// \brief Utility function to check whether or not a sign or zero extension
2966 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2967 /// either using the operands of \p Inst or promoting \p Inst.
2968 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002969 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002970 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002971 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002972 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002973 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002974 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002975 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002976 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2977 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002978
2979 /// \brief Utility function to determine if \p OpIdx should be promoted when
2980 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002981 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00002982 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002983 }
2984
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002985 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002986 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002987 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002988 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002989 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002990 /// Newly added extensions are inserted in \p Exts.
2991 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002992 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002993 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002994 static Value *promoteOperandForTruncAndAnyExt(
2995 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002996 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002997 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002998 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002999
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003000 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003001 /// operand is promotable and is not a supported trunc or sext.
3002 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003003 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003004 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003005 /// Newly added extensions are inserted in \p Exts.
3006 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003007 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003008 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003009 static Value *promoteOperandForOther(Instruction *Ext,
3010 TypePromotionTransaction &TPT,
3011 InstrToOrigTy &PromotedInsts,
3012 unsigned &CreatedInstsCost,
3013 SmallVectorImpl<Instruction *> *Exts,
3014 SmallVectorImpl<Instruction *> *Truncs,
3015 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003016
3017 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003018 static Value *signExtendOperandForOther(
3019 Instruction *Ext, TypePromotionTransaction &TPT,
3020 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3021 SmallVectorImpl<Instruction *> *Exts,
3022 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3023 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3024 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003025 }
3026
3027 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003028 static Value *zeroExtendOperandForOther(
3029 Instruction *Ext, TypePromotionTransaction &TPT,
3030 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3031 SmallVectorImpl<Instruction *> *Exts,
3032 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3033 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3034 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003035 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003036
3037public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003038 /// Type for the utility function that promotes the operand of Ext.
3039 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003040 InstrToOrigTy &PromotedInsts,
3041 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003042 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003043 SmallVectorImpl<Instruction *> *Truncs,
3044 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003045 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3046 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003047 /// \return NULL if no promotable action is possible with the current
3048 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003049 /// \p InsertedInsts keeps track of all the instructions inserted by the
3050 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003051 /// because we do not want to promote these instructions as CodeGenPrepare
3052 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3053 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003054 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003055 const TargetLowering &TLI,
3056 const InstrToOrigTy &PromotedInsts);
3057};
3058
3059bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003060 Type *ConsideredExtType,
3061 const InstrToOrigTy &PromotedInsts,
3062 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003063 // The promotion helper does not know how to deal with vector types yet.
3064 // To be able to fix that, we would need to fix the places where we
3065 // statically extend, e.g., constants and such.
3066 if (Inst->getType()->isVectorTy())
3067 return false;
3068
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003069 // We can always get through zext.
3070 if (isa<ZExtInst>(Inst))
3071 return true;
3072
3073 // sext(sext) is ok too.
3074 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003075 return true;
3076
3077 // We can get through binary operator, if it is legal. In other words, the
3078 // binary operator must have a nuw or nsw flag.
3079 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3080 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003081 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3082 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003083 return true;
3084
3085 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003086 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003087 if (!isa<TruncInst>(Inst))
3088 return false;
3089
3090 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003091 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003092 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003093 if (!OpndVal->getType()->isIntegerTy() ||
3094 OpndVal->getType()->getIntegerBitWidth() >
3095 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003096 return false;
3097
3098 // If the operand of the truncate is not an instruction, we will not have
3099 // any information on the dropped bits.
3100 // (Actually we could for constant but it is not worth the extra logic).
3101 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3102 if (!Opnd)
3103 return false;
3104
3105 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003106 // I.e., check that trunc just drops extended bits of the same kind of
3107 // the extension.
3108 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003109 const Type *OpndType;
3110 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003111 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3112 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003113 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3114 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003115 else
3116 return false;
3117
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003118 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003119 return Inst->getType()->getIntegerBitWidth() >=
3120 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003121}
3122
3123TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003124 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003125 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003126 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3127 "Unexpected instruction type");
3128 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3129 Type *ExtTy = Ext->getType();
3130 bool IsSExt = isa<SExtInst>(Ext);
3131 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003132 // get through.
3133 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003134 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003135 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003136
3137 // Do not promote if the operand has been added by codegenprepare.
3138 // Otherwise, it means we are undoing an optimization that is likely to be
3139 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003140 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003141 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003142
3143 // SExt or Trunc instructions.
3144 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003145 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3146 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003147 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003148
3149 // Regular instruction.
3150 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003151 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003152 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003153 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003154}
3155
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003156Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003157 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003158 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003159 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003160 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003161 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3162 // get through it and this method should not be called.
3163 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003164 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003165 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003166 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003167 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003168 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003169 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003170 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003171 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3172 TPT.replaceAllUsesWith(SExt, ZExt);
3173 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003174 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003175 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003176 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3177 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003178 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3179 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003180 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003181
3182 // Remove dead code.
3183 if (SExtOpnd->use_empty())
3184 TPT.eraseInstruction(SExtOpnd);
3185
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003186 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003187 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003188 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003189 if (ExtInst) {
3190 if (Exts)
3191 Exts->push_back(ExtInst);
3192 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3193 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003194 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003195 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003196
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003197 // At this point we have: ext ty opnd to ty.
3198 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3199 Value *NextVal = ExtInst->getOperand(0);
3200 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003201 return NextVal;
3202}
3203
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003204Value *TypePromotionHelper::promoteOperandForOther(
3205 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003206 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003207 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003208 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3209 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003210 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003211 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003212 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003213 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003214 if (!ExtOpnd->hasOneUse()) {
3215 // ExtOpnd will be promoted.
3216 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003217 // promoted version.
3218 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003219 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003220 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3221 ITrunc->removeFromParent();
3222 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003223 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003224 if (Truncs)
3225 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003226 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003227
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003228 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003229 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003230 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003231 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003232 }
3233
3234 // Get through the Instruction:
3235 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003236 // 2. Replace the uses of Ext by Inst.
3237 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003238
3239 // Remember the original type of the instruction before promotion.
3240 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003241 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3242 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003243 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003244 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003245 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003246 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003247 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003248 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003249
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003250 DEBUG(dbgs() << "Propagate Ext to operands\n");
3251 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003252 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003253 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3254 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3255 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003256 DEBUG(dbgs() << "No need to propagate\n");
3257 continue;
3258 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003259 // Check if we can statically extend the operand.
3260 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003261 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003262 DEBUG(dbgs() << "Statically extend\n");
3263 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3264 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3265 : Cst->getValue().zext(BitWidth);
3266 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003267 continue;
3268 }
3269 // UndefValue are typed, so we have to statically sign extend them.
3270 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003271 DEBUG(dbgs() << "Statically extend\n");
3272 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003273 continue;
3274 }
3275
3276 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003277 // Check if Ext was reused to extend an operand.
3278 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003279 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003280 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003281 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3282 : TPT.createZExt(Ext, Opnd, Ext->getType());
3283 if (!isa<Instruction>(ValForExtOpnd)) {
3284 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3285 continue;
3286 }
3287 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003288 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003289 if (Exts)
3290 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003291 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003292
3293 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003294 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3295 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003296 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003297 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003298 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003299 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003300 if (ExtForOpnd == Ext) {
3301 DEBUG(dbgs() << "Extension is useless now\n");
3302 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003303 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003304 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003305}
3306
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003307/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003308/// \p NewCost gives the cost of extension instructions created by the
3309/// promotion.
3310/// \p OldCost gives the cost of extension instructions before the promotion
3311/// plus the number of instructions that have been
3312/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003313/// \p PromotedOperand is the value that has been promoted.
3314/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003315bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003316 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3317 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3318 // The cost of the new extensions is greater than the cost of the
3319 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003320 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003321 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003322 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003323 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003324 return true;
3325 // The promotion is neutral but it may help folding the sign extension in
3326 // loads for instance.
3327 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003328 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003329}
3330
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003331/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003332/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003333/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003334/// If \p MovedAway is not NULL, it contains the information of whether or
3335/// not AddrInst has to be folded into the addressing mode on success.
3336/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3337/// because it has been moved away.
3338/// Thus AddrInst must not be added in the matched instructions.
3339/// This state can happen when AddrInst is a sext, since it may be moved away.
3340/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3341/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003342bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003343 unsigned Depth,
3344 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003345 // Avoid exponential behavior on extremely deep expression trees.
3346 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003347
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003348 // By default, all matched instructions stay in place.
3349 if (MovedAway)
3350 *MovedAway = false;
3351
Chandler Carruthc8925912013-01-05 02:09:22 +00003352 switch (Opcode) {
3353 case Instruction::PtrToInt:
3354 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003355 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003356 case Instruction::IntToPtr: {
3357 auto AS = AddrInst->getType()->getPointerAddressSpace();
3358 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003359 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003360 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003361 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003362 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003363 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003364 case Instruction::BitCast:
3365 // BitCast is always a noop, and we can handle it as long as it is
3366 // int->int or pointer->pointer (we don't want int<->fp or something).
3367 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3368 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3369 // Don't touch identity bitcasts. These were probably put here by LSR,
3370 // and we don't want to mess around with them. Assume it knows what it
3371 // is doing.
3372 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003373 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003374 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003375 case Instruction::AddrSpaceCast: {
3376 unsigned SrcAS
3377 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3378 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3379 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003380 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003381 return false;
3382 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003383 case Instruction::Add: {
3384 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3385 ExtAddrMode BackupAddrMode = AddrMode;
3386 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003387 // Start a transaction at this point.
3388 // The LHS may match but not the RHS.
3389 // Therefore, we need a higher level restoration point to undo partially
3390 // matched operation.
3391 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3392 TPT.getRestorationPoint();
3393
Sanjay Patelfc580a62015-09-21 23:03:16 +00003394 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3395 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003396 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003397
Chandler Carruthc8925912013-01-05 02:09:22 +00003398 // Restore the old addr mode info.
3399 AddrMode = BackupAddrMode;
3400 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003401 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003402
Chandler Carruthc8925912013-01-05 02:09:22 +00003403 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003404 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3405 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003406 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003407
Chandler Carruthc8925912013-01-05 02:09:22 +00003408 // Otherwise we definitely can't merge the ADD in.
3409 AddrMode = BackupAddrMode;
3410 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003411 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003412 break;
3413 }
3414 //case Instruction::Or:
3415 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3416 //break;
3417 case Instruction::Mul:
3418 case Instruction::Shl: {
3419 // Can only handle X*C and X << C.
3420 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003421 if (!RHS)
3422 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003423 int64_t Scale = RHS->getSExtValue();
3424 if (Opcode == Instruction::Shl)
3425 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003426
Sanjay Patelfc580a62015-09-21 23:03:16 +00003427 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003428 }
3429 case Instruction::GetElementPtr: {
3430 // Scan the GEP. We check it if it contains constant offsets and at most
3431 // one variable offset.
3432 int VariableOperand = -1;
3433 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003434
Chandler Carruthc8925912013-01-05 02:09:22 +00003435 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003436 gep_type_iterator GTI = gep_type_begin(AddrInst);
3437 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003438 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003439 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003440 unsigned Idx =
3441 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3442 ConstantOffset += SL->getElementOffset(Idx);
3443 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003444 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003445 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3446 ConstantOffset += CI->getSExtValue()*TypeSize;
3447 } else if (TypeSize) { // Scales of zero don't do anything.
3448 // We only allow one variable index at the moment.
3449 if (VariableOperand != -1)
3450 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003451
Chandler Carruthc8925912013-01-05 02:09:22 +00003452 // Remember the variable index.
3453 VariableOperand = i;
3454 VariableScale = TypeSize;
3455 }
3456 }
3457 }
Stephen Lin837bba12013-07-15 17:55:02 +00003458
Chandler Carruthc8925912013-01-05 02:09:22 +00003459 // A common case is for the GEP to only do a constant offset. In this case,
3460 // just add it to the disp field and check validity.
3461 if (VariableOperand == -1) {
3462 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003463 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003464 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003465 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003466 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003467 return true;
3468 }
3469 AddrMode.BaseOffs -= ConstantOffset;
3470 return false;
3471 }
3472
3473 // Save the valid addressing mode in case we can't match.
3474 ExtAddrMode BackupAddrMode = AddrMode;
3475 unsigned OldSize = AddrModeInsts.size();
3476
3477 // See if the scale and offset amount is valid for this target.
3478 AddrMode.BaseOffs += ConstantOffset;
3479
3480 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003481 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003482 // If it couldn't be matched, just stuff the value in a register.
3483 if (AddrMode.HasBaseReg) {
3484 AddrMode = BackupAddrMode;
3485 AddrModeInsts.resize(OldSize);
3486 return false;
3487 }
3488 AddrMode.HasBaseReg = true;
3489 AddrMode.BaseReg = AddrInst->getOperand(0);
3490 }
3491
3492 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003493 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003494 Depth)) {
3495 // If it couldn't be matched, try stuffing the base into a register
3496 // instead of matching it, and retrying the match of the scale.
3497 AddrMode = BackupAddrMode;
3498 AddrModeInsts.resize(OldSize);
3499 if (AddrMode.HasBaseReg)
3500 return false;
3501 AddrMode.HasBaseReg = true;
3502 AddrMode.BaseReg = AddrInst->getOperand(0);
3503 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003504 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003505 VariableScale, Depth)) {
3506 // If even that didn't work, bail.
3507 AddrMode = BackupAddrMode;
3508 AddrModeInsts.resize(OldSize);
3509 return false;
3510 }
3511 }
3512
3513 return true;
3514 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003515 case Instruction::SExt:
3516 case Instruction::ZExt: {
3517 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3518 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003519 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003520
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003521 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003522 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003523 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003524 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003525 if (!TPH)
3526 return false;
3527
3528 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3529 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003530 unsigned CreatedInstsCost = 0;
3531 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003532 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003533 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003534 // SExt has been moved away.
3535 // Thus either it will be rematched later in the recursive calls or it is
3536 // gone. Anyway, we must not fold it into the addressing mode at this point.
3537 // E.g.,
3538 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003539 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003540 // addr = gep base, idx
3541 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003542 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003543 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3544 // addr = gep base, op <- match
3545 if (MovedAway)
3546 *MovedAway = true;
3547
3548 assert(PromotedOperand &&
3549 "TypePromotionHelper should have filtered out those cases");
3550
3551 ExtAddrMode BackupAddrMode = AddrMode;
3552 unsigned OldSize = AddrModeInsts.size();
3553
Sanjay Patelfc580a62015-09-21 23:03:16 +00003554 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003555 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003556 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003557 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003558 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003559 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003560 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003561 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003562 AddrMode = BackupAddrMode;
3563 AddrModeInsts.resize(OldSize);
3564 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3565 TPT.rollback(LastKnownGood);
3566 return false;
3567 }
3568 return true;
3569 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003570 }
3571 return false;
3572}
3573
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003574/// If we can, try to add the value of 'Addr' into the current addressing mode.
3575/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3576/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3577/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003578///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003579bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003580 // Start a transaction at this point that we will rollback if the matching
3581 // fails.
3582 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3583 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003584 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3585 // Fold in immediates if legal for the target.
3586 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003587 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003588 return true;
3589 AddrMode.BaseOffs -= CI->getSExtValue();
3590 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3591 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003592 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003593 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003594 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003595 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003596 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003597 }
3598 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3599 ExtAddrMode BackupAddrMode = AddrMode;
3600 unsigned OldSize = AddrModeInsts.size();
3601
3602 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003603 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003604 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003605 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003606 // to check here.
3607 if (MovedAway)
3608 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003609 // Okay, it's possible to fold this. Check to see if it is actually
3610 // *profitable* to do so. We use a simple cost model to avoid increasing
3611 // register pressure too much.
3612 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003613 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003614 AddrModeInsts.push_back(I);
3615 return true;
3616 }
Stephen Lin837bba12013-07-15 17:55:02 +00003617
Chandler Carruthc8925912013-01-05 02:09:22 +00003618 // It isn't profitable to do this, roll back.
3619 //cerr << "NOT FOLDING: " << *I;
3620 AddrMode = BackupAddrMode;
3621 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003622 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003623 }
3624 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003625 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003626 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003627 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003628 } else if (isa<ConstantPointerNull>(Addr)) {
3629 // Null pointer gets folded without affecting the addressing mode.
3630 return true;
3631 }
3632
3633 // Worse case, the target should support [reg] addressing modes. :)
3634 if (!AddrMode.HasBaseReg) {
3635 AddrMode.HasBaseReg = true;
3636 AddrMode.BaseReg = Addr;
3637 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003638 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003639 return true;
3640 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003641 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003642 }
3643
3644 // If the base register is already taken, see if we can do [r+r].
3645 if (AddrMode.Scale == 0) {
3646 AddrMode.Scale = 1;
3647 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003648 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003649 return true;
3650 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003651 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003652 }
3653 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003654 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003655 return false;
3656}
3657
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003658/// Check to see if all uses of OpVal by the specified inline asm call are due
3659/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003660static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003661 const TargetLowering &TLI,
3662 const TargetRegisterInfo &TRI) {
Eric Christopher11e4df72015-02-26 22:38:43 +00003663 const Function *F = CI->getParent()->getParent();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003664 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003665 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003666 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003667
Chandler Carruthc8925912013-01-05 02:09:22 +00003668 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3669 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003670
Chandler Carruthc8925912013-01-05 02:09:22 +00003671 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003672 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003673
3674 // If this asm operand is our Value*, and if it isn't an indirect memory
3675 // operand, we can't fold it!
3676 if (OpInfo.CallOperandVal == OpVal &&
3677 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3678 !OpInfo.isIndirect))
3679 return false;
3680 }
3681
3682 return true;
3683}
3684
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003685/// Recursively walk all the uses of I until we find a memory use.
3686/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003687/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003688static bool FindAllMemoryUses(
3689 Instruction *I,
3690 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003691 SmallPtrSetImpl<Instruction *> &ConsideredInsts,
3692 const TargetLowering &TLI, const TargetRegisterInfo &TRI) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003693 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003694 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003695 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003696
Chandler Carruthc8925912013-01-05 02:09:22 +00003697 // If this is an obviously unfoldable instruction, bail out.
3698 if (!MightBeFoldableInst(I))
3699 return true;
3700
Philip Reamesac115ed2016-03-09 23:13:12 +00003701 const bool OptSize = I->getFunction()->optForSize();
3702
Chandler Carruthc8925912013-01-05 02:09:22 +00003703 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003704 for (Use &U : I->uses()) {
3705 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003706
Chandler Carruthcdf47882014-03-09 03:16:01 +00003707 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3708 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003709 continue;
3710 }
Stephen Lin837bba12013-07-15 17:55:02 +00003711
Chandler Carruthcdf47882014-03-09 03:16:01 +00003712 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3713 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003714 if (opNo == 0) return true; // Storing addr, not into addr.
3715 MemoryUses.push_back(std::make_pair(SI, opNo));
3716 continue;
3717 }
Stephen Lin837bba12013-07-15 17:55:02 +00003718
Chandler Carruthcdf47882014-03-09 03:16:01 +00003719 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00003720 // If this is a cold call, we can sink the addressing calculation into
3721 // the cold path. See optimizeCallInst
3722 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3723 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00003724
Chandler Carruthc8925912013-01-05 02:09:22 +00003725 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3726 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003727
Chandler Carruthc8925912013-01-05 02:09:22 +00003728 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003729 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00003730 return true;
3731 continue;
3732 }
Stephen Lin837bba12013-07-15 17:55:02 +00003733
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003734 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00003735 return true;
3736 }
3737
3738 return false;
3739}
3740
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003741/// Return true if Val is already known to be live at the use site that we're
3742/// folding it into. If so, there is no cost to include it in the addressing
3743/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3744/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003745bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003746 Value *KnownLive2) {
3747 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003748 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003749 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003750
Chandler Carruthc8925912013-01-05 02:09:22 +00003751 // All values other than instructions and arguments (e.g. constants) are live.
3752 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003753
Chandler Carruthc8925912013-01-05 02:09:22 +00003754 // If Val is a constant sized alloca in the entry block, it is live, this is
3755 // true because it is just a reference to the stack/frame pointer, which is
3756 // live for the whole function.
3757 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3758 if (AI->isStaticAlloca())
3759 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003760
Chandler Carruthc8925912013-01-05 02:09:22 +00003761 // Check to see if this value is already used in the memory instruction's
3762 // block. If so, it's already live into the block at the very least, so we
3763 // can reasonably fold it.
3764 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3765}
3766
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003767/// It is possible for the addressing mode of the machine to fold the specified
3768/// instruction into a load or store that ultimately uses it.
3769/// However, the specified instruction has multiple uses.
3770/// Given this, it may actually increase register pressure to fold it
3771/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003772///
3773/// X = ...
3774/// Y = X+1
3775/// use(Y) -> nonload/store
3776/// Z = Y+1
3777/// load Z
3778///
3779/// In this case, Y has multiple uses, and can be folded into the load of Z
3780/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3781/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3782/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3783/// number of computations either.
3784///
3785/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3786/// X was live across 'load Z' for other reasons, we actually *would* want to
3787/// fold the addressing mode in the Z case. This would make Y die earlier.
3788bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003789isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003790 ExtAddrMode &AMAfter) {
3791 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003792
Chandler Carruthc8925912013-01-05 02:09:22 +00003793 // AMBefore is the addressing mode before this instruction was folded into it,
3794 // and AMAfter is the addressing mode after the instruction was folded. Get
3795 // the set of registers referenced by AMAfter and subtract out those
3796 // referenced by AMBefore: this is the set of values which folding in this
3797 // address extends the lifetime of.
3798 //
3799 // Note that there are only two potential values being referenced here,
3800 // BaseReg and ScaleReg (global addresses are always available, as are any
3801 // folded immediates).
3802 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003803
Chandler Carruthc8925912013-01-05 02:09:22 +00003804 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3805 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003806 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003807 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003808 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003809 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003810
3811 // If folding this instruction (and it's subexprs) didn't extend any live
3812 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003813 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003814 return true;
3815
Philip Reamesac115ed2016-03-09 23:13:12 +00003816 // If all uses of this instruction can have the address mode sunk into them,
3817 // we can remove the addressing mode and effectively trade one live register
3818 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00003819 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00003820 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3821 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003822 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00003823 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003824
Chandler Carruthc8925912013-01-05 02:09:22 +00003825 // Now that we know that all uses of this instruction are part of a chain of
3826 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00003827 // into a memory use, loop over each of these memory operation uses and see
3828 // if they could *actually* fold the instruction. The assumption is that
3829 // addressing modes are cheap and that duplicating the computation involved
3830 // many times is worthwhile, even on a fastpath. For sinking candidates
3831 // (i.e. cold call sites), this serves as a way to prevent excessive code
3832 // growth since most architectures have some reasonable small and fast way to
3833 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00003834 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3835 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3836 Instruction *User = MemoryUses[i].first;
3837 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003838
Chandler Carruthc8925912013-01-05 02:09:22 +00003839 // Get the access type of this use. If the use isn't a pointer, we don't
3840 // know what it accesses.
3841 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003842 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3843 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003844 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003845 Type *AddressAccessTy = AddrTy->getElementType();
3846 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003847
Chandler Carruthc8925912013-01-05 02:09:22 +00003848 // Do a match against the root of this address, ignoring profitability. This
3849 // will tell us if the addressing mode for the memory operation will
3850 // *actually* cover the shared instruction.
3851 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003852 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3853 TPT.getRestorationPoint();
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003854 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
3855 AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003856 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003857 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003858 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003859 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003860 (void)Success; assert(Success && "Couldn't select *anything*?");
3861
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003862 // The match was to check the profitability, the changes made are not
3863 // part of the original matcher. Therefore, they should be dropped
3864 // otherwise the original matcher will not present the right state.
3865 TPT.rollback(LastKnownGood);
3866
Chandler Carruthc8925912013-01-05 02:09:22 +00003867 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00003868 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00003869 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003870
Chandler Carruthc8925912013-01-05 02:09:22 +00003871 MatchedAddrModeInsts.clear();
3872 }
Stephen Lin837bba12013-07-15 17:55:02 +00003873
Chandler Carruthc8925912013-01-05 02:09:22 +00003874 return true;
3875}
3876
3877} // end anonymous namespace
3878
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003879/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003880/// different basic block than BB.
3881static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3882 if (Instruction *I = dyn_cast<Instruction>(V))
3883 return I->getParent() != BB;
3884 return false;
3885}
3886
Philip Reamesac115ed2016-03-09 23:13:12 +00003887/// Sink addressing mode computation immediate before MemoryInst if doing so
3888/// can be done without increasing register pressure. The need for the
3889/// register pressure constraint means this can end up being an all or nothing
3890/// decision for all uses of the same addressing computation.
3891///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003892/// Load and Store Instructions often have addressing modes that can do
3893/// significant amounts of computation. As such, instruction selection will try
3894/// to get the load or store to do as much computation as possible for the
3895/// program. The problem is that isel can only see within a single block. As
3896/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003897///
3898/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00003899/// operands. It's also used to sink addressing computations feeding into cold
3900/// call sites into their (cold) basic block.
3901///
3902/// The motivation for handling sinking into cold blocks is that doing so can
3903/// both enable other address mode sinking (by satisfying the register pressure
3904/// constraint above), and reduce register pressure globally (by removing the
3905/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00003906bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003907 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003908 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003909
3910 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003911 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003912 SmallVector<Value*, 8> worklist;
3913 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003914 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003915
Owen Anderson8ba5f392010-11-27 08:15:55 +00003916 // Use a worklist to iteratively look through PHI nodes, and ensure that
3917 // the addressing mode obtained from the non-PHI roots of the graph
3918 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003919 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003920 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003921 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003922 SmallVector<Instruction*, 16> AddrModeInsts;
3923 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003924 TypePromotionTransaction TPT;
3925 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3926 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003927 while (!worklist.empty()) {
3928 Value *V = worklist.back();
3929 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003930
Owen Anderson8ba5f392010-11-27 08:15:55 +00003931 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003932 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003933 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003934 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003935 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003936
Owen Anderson8ba5f392010-11-27 08:15:55 +00003937 // For a PHI node, push all of its incoming values.
3938 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003939 for (Value *IncValue : P->incoming_values())
3940 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003941 continue;
3942 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003943
Philip Reamesac115ed2016-03-09 23:13:12 +00003944 // For non-PHIs, determine the addressing mode being computed. Note that
3945 // the result may differ depending on what other uses our candidate
3946 // addressing instructions might have.
Owen Anderson8ba5f392010-11-27 08:15:55 +00003947 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003948 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003949 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TLI, *TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003950 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003951
3952 // This check is broken into two cases with very similar code to avoid using
3953 // getNumUses() as much as possible. Some values have a lot of uses, so
3954 // calling getNumUses() unconditionally caused a significant compile-time
3955 // regression.
3956 if (!Consensus) {
3957 Consensus = V;
3958 AddrMode = NewAddrMode;
3959 AddrModeInsts = NewAddrModeInsts;
3960 continue;
3961 } else if (NewAddrMode == AddrMode) {
3962 if (!IsNumUsesConsensusValid) {
3963 NumUsesConsensus = Consensus->getNumUses();
3964 IsNumUsesConsensusValid = true;
3965 }
3966
3967 // Ensure that the obtained addressing mode is equivalent to that obtained
3968 // for all other roots of the PHI traversal. Also, when choosing one
3969 // such root as representative, select the one with the most uses in order
3970 // to keep the cost modeling heuristics in AddressingModeMatcher
3971 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003972 unsigned NumUses = V->getNumUses();
3973 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003974 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003975 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003976 AddrModeInsts = NewAddrModeInsts;
3977 }
3978 continue;
3979 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003980
Craig Topperc0196b12014-04-14 00:51:57 +00003981 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003982 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003983 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003984
Owen Anderson8ba5f392010-11-27 08:15:55 +00003985 // If the addressing mode couldn't be determined, or if multiple different
3986 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003987 if (!Consensus) {
3988 TPT.rollback(LastKnownGood);
3989 return false;
3990 }
3991 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003992
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003993 // If all the instructions matched are already in this BB, don't do anything.
Justin Lebar838c7f52016-11-21 22:49:11 +00003994 if (none_of(AddrModeInsts, [&](Value *V) {
3995 return IsNonLocalValue(V, MemoryInst->getParent());
3996 })) {
David Greene74e2d492010-01-05 01:27:11 +00003997 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003998 return false;
3999 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004000
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004001 // Insert this computation right after this user. Since our caller is
4002 // scanning from the top of the BB to the bottom, reuse of the expr are
4003 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004004 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004005
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004006 // Now that we determined the addressing expression we want to use and know
4007 // that we have to sink it into this block. Check to see if we have already
4008 // done this for some other load/store instr in this block. If so, reuse the
4009 // computation.
4010 Value *&SunkAddr = SunkAddrs[Addr];
4011 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00004012 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004013 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004014 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004015 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004016 } else if (AddrSinkUsingGEPs ||
4017 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004018 SubtargetInfo->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004019 // By default, we use the GEP-based method when AA is used later. This
4020 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4021 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004022 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004023 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004024 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004025
4026 // First, find the pointer.
4027 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4028 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004029 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004030 }
4031
4032 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4033 // We can't add more than one pointer together, nor can we scale a
4034 // pointer (both of which seem meaningless).
4035 if (ResultPtr || AddrMode.Scale != 1)
4036 return false;
4037
4038 ResultPtr = AddrMode.ScaledReg;
4039 AddrMode.Scale = 0;
4040 }
4041
4042 if (AddrMode.BaseGV) {
4043 if (ResultPtr)
4044 return false;
4045
4046 ResultPtr = AddrMode.BaseGV;
4047 }
4048
4049 // If the real base value actually came from an inttoptr, then the matcher
4050 // will look through it and provide only the integer value. In that case,
4051 // use it here.
4052 if (!ResultPtr && AddrMode.BaseReg) {
4053 ResultPtr =
4054 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00004055 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004056 } else if (!ResultPtr && AddrMode.Scale == 1) {
4057 ResultPtr =
4058 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
4059 AddrMode.Scale = 0;
4060 }
4061
4062 if (!ResultPtr &&
4063 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4064 SunkAddr = Constant::getNullValue(Addr->getType());
4065 } else if (!ResultPtr) {
4066 return false;
4067 } else {
4068 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004069 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4070 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004071
4072 // Start with the base register. Do this first so that subsequent address
4073 // matching finds it last, which will prevent it from trying to match it
4074 // as the scaled value in case it happens to be a mul. That would be
4075 // problematic if we've sunk a different mul for the scale, because then
4076 // we'd end up sinking both muls.
4077 if (AddrMode.BaseReg) {
4078 Value *V = AddrMode.BaseReg;
4079 if (V->getType() != IntPtrTy)
4080 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4081
4082 ResultIndex = V;
4083 }
4084
4085 // Add the scale value.
4086 if (AddrMode.Scale) {
4087 Value *V = AddrMode.ScaledReg;
4088 if (V->getType() == IntPtrTy) {
4089 // done.
4090 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4091 cast<IntegerType>(V->getType())->getBitWidth()) {
4092 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4093 } else {
4094 // It is only safe to sign extend the BaseReg if we know that the math
4095 // required to create it did not overflow before we extend it. Since
4096 // the original IR value was tossed in favor of a constant back when
4097 // the AddrMode was created we need to bail out gracefully if widths
4098 // do not match instead of extending it.
4099 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
4100 if (I && (ResultIndex != AddrMode.BaseReg))
4101 I->eraseFromParent();
4102 return false;
4103 }
4104
4105 if (AddrMode.Scale != 1)
4106 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4107 "sunkaddr");
4108 if (ResultIndex)
4109 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4110 else
4111 ResultIndex = V;
4112 }
4113
4114 // Add in the Base Offset if present.
4115 if (AddrMode.BaseOffs) {
4116 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4117 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004118 // We need to add this separately from the scale above to help with
4119 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004120 if (ResultPtr->getType() != I8PtrTy)
4121 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004122 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004123 }
4124
4125 ResultIndex = V;
4126 }
4127
4128 if (!ResultIndex) {
4129 SunkAddr = ResultPtr;
4130 } else {
4131 if (ResultPtr->getType() != I8PtrTy)
4132 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004133 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004134 }
4135
4136 if (SunkAddr->getType() != Addr->getType())
4137 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
4138 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004139 } else {
David Greene74e2d492010-01-05 01:27:11 +00004140 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004141 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004142 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004143 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004144
4145 // Start with the base register. Do this first so that subsequent address
4146 // matching finds it last, which will prevent it from trying to match it
4147 // as the scaled value in case it happens to be a mul. That would be
4148 // problematic if we've sunk a different mul for the scale, because then
4149 // we'd end up sinking both muls.
4150 if (AddrMode.BaseReg) {
4151 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004152 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004153 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004154 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004155 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004156 Result = V;
4157 }
4158
4159 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004160 if (AddrMode.Scale) {
4161 Value *V = AddrMode.ScaledReg;
4162 if (V->getType() == IntPtrTy) {
4163 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004164 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004165 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004166 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4167 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004168 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004169 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004170 // It is only safe to sign extend the BaseReg if we know that the math
4171 // required to create it did not overflow before we extend it. Since
4172 // the original IR value was tossed in favor of a constant back when
4173 // the AddrMode was created we need to bail out gracefully if widths
4174 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004175 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004176 if (I && (Result != AddrMode.BaseReg))
4177 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004178 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004179 }
4180 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004181 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4182 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004183 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004184 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004185 else
4186 Result = V;
4187 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004188
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004189 // Add in the BaseGV if present.
4190 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004191 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004192 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004193 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004194 else
4195 Result = V;
4196 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004197
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004198 // Add in the Base Offset if present.
4199 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004200 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004201 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004202 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004203 else
4204 Result = V;
4205 }
4206
Craig Topperc0196b12014-04-14 00:51:57 +00004207 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004208 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004209 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004210 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004211 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004212
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004213 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004214
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004215 // If we have no uses, recursively delete the value and all dead instructions
4216 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004217 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004218 // This can cause recursive deletion, which can invalidate our iterator.
4219 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004220 Value *CurValue = &*CurInstIterator;
4221 WeakVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004222 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004223
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004224 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004225
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004226 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004227 // If the iterator instruction was recursively deleted, start over at the
4228 // start of the block.
4229 CurInstIterator = BB->begin();
4230 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004231 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004232 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004233 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004234 return true;
4235}
4236
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004237/// If there are any memory operands, use OptimizeMemoryInst to sink their
4238/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004239bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004240 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004241
Eric Christopher11e4df72015-02-26 22:38:43 +00004242 const TargetRegisterInfo *TRI =
4243 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004244 TargetLowering::AsmOperandInfoVector TargetConstraints =
4245 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004246 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004247 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4248 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004249
Evan Cheng1da25002008-02-26 02:42:37 +00004250 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004251 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004252
Eli Friedman666bbe32008-02-26 18:37:49 +00004253 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4254 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004255 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004256 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004257 } else if (OpInfo.Type == InlineAsm::isInput)
4258 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004259 }
4260
4261 return MadeChange;
4262}
4263
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004264/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
4265/// sign extensions.
4266static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
4267 assert(!Inst->use_empty() && "Input must have at least one use");
4268 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
4269 bool IsSExt = isa<SExtInst>(FirstUser);
4270 Type *ExtTy = FirstUser->getType();
4271 for (const User *U : Inst->users()) {
4272 const Instruction *UI = cast<Instruction>(U);
4273 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4274 return false;
4275 Type *CurTy = UI->getType();
4276 // Same input and output types: Same instruction after CSE.
4277 if (CurTy == ExtTy)
4278 continue;
4279
4280 // If IsSExt is true, we are in this situation:
4281 // a = Inst
4282 // b = sext ty1 a to ty2
4283 // c = sext ty1 a to ty3
4284 // Assuming ty2 is shorter than ty3, this could be turned into:
4285 // a = Inst
4286 // b = sext ty1 a to ty2
4287 // c = sext ty2 b to ty3
4288 // However, the last sext is not free.
4289 if (IsSExt)
4290 return false;
4291
4292 // This is a ZExt, maybe this is free to extend from one type to another.
4293 // In that case, we would not account for a different use.
4294 Type *NarrowTy;
4295 Type *LargeTy;
4296 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4297 CurTy->getScalarType()->getIntegerBitWidth()) {
4298 NarrowTy = CurTy;
4299 LargeTy = ExtTy;
4300 } else {
4301 NarrowTy = ExtTy;
4302 LargeTy = CurTy;
4303 }
4304
4305 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4306 return false;
4307 }
4308 // All uses are the same or can be derived from one another for free.
4309 return true;
4310}
4311
4312/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4313/// load instruction.
4314/// If an ext(load) can be formed, it is returned via \p LI for the load
4315/// and \p Inst for the extension.
4316/// Otherwise LI == nullptr and Inst == nullptr.
4317/// When some promotion happened, \p TPT contains the proper state to
4318/// revert them.
4319///
4320/// \return true when promoting was necessary to expose the ext(load)
4321/// opportunity, false otherwise.
4322///
4323/// Example:
4324/// \code
4325/// %ld = load i32* %addr
4326/// %add = add nuw i32 %ld, 4
4327/// %zext = zext i32 %add to i64
4328/// \endcode
4329/// =>
4330/// \code
4331/// %ld = load i32* %addr
4332/// %zext = zext i32 %ld to i64
4333/// %add = add nuw i64 %zext, 4
Haicheng Wu8ce2d142017-01-18 21:12:10 +00004334/// \endcode
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004335/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004336bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004337 LoadInst *&LI, Instruction *&Inst,
4338 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004339 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004340 // Iterate over all the extensions to see if one form an ext(load).
4341 for (auto I : Exts) {
4342 // Check if we directly have ext(load).
4343 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4344 Inst = I;
4345 // No promotion happened here.
4346 return false;
4347 }
4348 // Check whether or not we want to do any promotion.
4349 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4350 continue;
4351 // Get the action to perform the promotion.
4352 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004353 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004354 // Check if we can promote.
4355 if (!TPH)
4356 continue;
4357 // Save the current state.
4358 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4359 TPT.getRestorationPoint();
4360 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004361 unsigned NewCreatedInstsCost = 0;
4362 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004363 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004364 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4365 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004366 assert(PromotedVal &&
4367 "TypePromotionHelper should have filtered out those cases");
4368
4369 // We would be able to merge only one extension in a load.
4370 // Therefore, if we have more than 1 new extension we heuristically
4371 // cut this search path, because it means we degrade the code quality.
4372 // With exactly 2, the transformation is neutral, because we will merge
4373 // one extension but leave one. However, we optimistically keep going,
4374 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004375 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004376 // FIXME: It would be possible to propagate a negative value instead of
4377 // conservatively ceiling it to 0.
4378 TotalCreatedInstsCost =
4379 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004380 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004381 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004382 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004383 // The promotion is not profitable, rollback to the previous state.
4384 TPT.rollback(LastKnownGood);
4385 continue;
4386 }
4387 // The promotion is profitable.
4388 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004389 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004390 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004391 // If we have created a new extension, i.e., now we have two
4392 // extensions. We must make sure one of them is merged with
4393 // the load, otherwise we may degrade the code quality.
4394 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4395 // Promotion happened.
4396 return true;
4397 // If this does not help to expose an ext(load) then, rollback.
4398 TPT.rollback(LastKnownGood);
4399 }
4400 // None of the extension can form an ext(load).
4401 LI = nullptr;
4402 Inst = nullptr;
4403 return false;
4404}
4405
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004406/// Move a zext or sext fed by a load into the same basic block as the load,
4407/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4408/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004409/// \p I[in/out] the extension may be modified during the process if some
4410/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004411///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004412bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Chandler Carruth0f139b42016-11-04 06:54:00 +00004413 // ExtLoad formation infrastructure requires TLI to be effective.
4414 if (!TLI)
4415 return false;
4416
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004417 // Try to promote a chain of computation if it allows to form
4418 // an extended load.
4419 TypePromotionTransaction TPT;
4420 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4421 TPT.getRestorationPoint();
4422 SmallVector<Instruction *, 1> Exts;
4423 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004424 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004425 LoadInst *LI = nullptr;
4426 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004427 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004428 if (!LI || !I) {
4429 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4430 "the code must remain the same");
4431 I = OldExt;
4432 return false;
4433 }
Dan Gohman99429a02009-10-16 20:59:35 +00004434
4435 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004436 // Make the cheap checks first if we did not promote.
4437 // If we promoted, we need to check if it is indeed profitable.
4438 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004439 return false;
4440
Mehdi Amini44ede332015-07-09 02:09:04 +00004441 EVT VT = TLI->getValueType(*DL, I->getType());
4442 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004443
Dan Gohman99429a02009-10-16 20:59:35 +00004444 // If the load has other users and the truncate is not free, this probably
4445 // isn't worthwhile.
Chandler Carruth0f139b42016-11-04 06:54:00 +00004446 if (!LI->hasOneUse() &&
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004447 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004448 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4449 I = OldExt;
4450 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004451 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004452 }
Dan Gohman99429a02009-10-16 20:59:35 +00004453
4454 // Check whether the target supports casts folded into loads.
4455 unsigned LType;
4456 if (isa<ZExtInst>(I))
4457 LType = ISD::ZEXTLOAD;
4458 else {
4459 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4460 LType = ISD::SEXTLOAD;
4461 }
Chandler Carruth0f139b42016-11-04 06:54:00 +00004462 if (!TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004463 I = OldExt;
4464 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004465 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004466 }
Dan Gohman99429a02009-10-16 20:59:35 +00004467
4468 // Move the extend into the same block as the load, so that SelectionDAG
4469 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004470 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004471 I->removeFromParent();
4472 I->insertAfter(LI);
Andrea Di Biagiofa90c692016-10-17 11:32:26 +00004473 // CGP does not check if the zext would be speculatively executed when moved
4474 // to the same basic block as the load. Preserving its original location would
4475 // pessimize the debugging experience, as well as negatively impact the
4476 // quality of sample pgo. We don't want to use "line 0" as that has a
4477 // size cost in the line-table section and logically the zext can be seen as
4478 // part of the load. Therefore we conservatively reuse the same debug location
4479 // for the load and the zext.
4480 I->setDebugLoc(LI->getDebugLoc());
Cameron Zwarichced753f2011-01-05 17:27:27 +00004481 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004482 return true;
4483}
4484
Sanjay Patelfc580a62015-09-21 23:03:16 +00004485bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004486 BasicBlock *DefBB = I->getParent();
4487
Bob Wilsonff714f92010-09-21 21:44:14 +00004488 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004489 // other uses of the source with result of extension.
4490 Value *Src = I->getOperand(0);
4491 if (Src->hasOneUse())
4492 return false;
4493
Evan Cheng2011df42007-12-13 07:50:36 +00004494 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004495 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004496 return false;
4497
Evan Cheng7bc89422007-12-12 00:51:06 +00004498 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004499 // this block.
4500 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004501 return false;
4502
Evan Chengd3d80172007-12-05 23:58:20 +00004503 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004504 for (User *U : I->users()) {
4505 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004506
4507 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004508 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004509 if (UserBB == DefBB) continue;
4510 DefIsLiveOut = true;
4511 break;
4512 }
4513 if (!DefIsLiveOut)
4514 return false;
4515
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004516 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004517 for (User *U : Src->users()) {
4518 Instruction *UI = cast<Instruction>(U);
4519 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004520 if (UserBB == DefBB) continue;
4521 // Be conservative. We don't want this xform to end up introducing
4522 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004523 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004524 return false;
4525 }
4526
Evan Chengd3d80172007-12-05 23:58:20 +00004527 // InsertedTruncs - Only insert one trunc in each block once.
4528 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4529
4530 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004531 for (Use &U : Src->uses()) {
4532 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004533
4534 // Figure out which BB this ext is used in.
4535 BasicBlock *UserBB = User->getParent();
4536 if (UserBB == DefBB) continue;
4537
4538 // Both src and def are live in this block. Rewrite the use.
4539 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4540
4541 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004542 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004543 assert(InsertPt != UserBB->end());
4544 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004545 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004546 }
4547
4548 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004549 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004550 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004551 MadeChange = true;
4552 }
4553
4554 return MadeChange;
4555}
4556
Geoff Berry5256fca2015-11-20 22:34:39 +00004557// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4558// just after the load if the target can fold this into one extload instruction,
4559// with the hope of eliminating some of the other later "and" instructions using
4560// the loaded value. "and"s that are made trivially redundant by the insertion
4561// of the new "and" are removed by this function, while others (e.g. those whose
4562// path from the load goes through a phi) are left for isel to potentially
4563// remove.
4564//
4565// For example:
4566//
4567// b0:
4568// x = load i32
4569// ...
4570// b1:
4571// y = and x, 0xff
4572// z = use y
4573//
4574// becomes:
4575//
4576// b0:
4577// x = load i32
4578// x' = and x, 0xff
4579// ...
4580// b1:
4581// z = use x'
4582//
4583// whereas:
4584//
4585// b0:
4586// x1 = load i32
4587// ...
4588// b1:
4589// x2 = load i32
4590// ...
4591// b2:
4592// x = phi x1, x2
4593// y = and x, 0xff
4594//
4595// becomes (after a call to optimizeLoadExt for each load):
4596//
4597// b0:
4598// x1 = load i32
4599// x1' = and x1, 0xff
4600// ...
4601// b1:
4602// x2 = load i32
4603// x2' = and x2, 0xff
4604// ...
4605// b2:
4606// x = phi x1', x2'
4607// y = and x, 0xff
4608//
4609
4610bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4611
4612 if (!Load->isSimple() ||
4613 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4614 return false;
4615
Geoff Berry5d534b62017-02-21 18:53:14 +00004616 // Skip loads we've already transformed.
4617 if (Load->hasOneUse() &&
4618 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
4619 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00004620
4621 // Look at all uses of Load, looking through phis, to determine how many bits
4622 // of the loaded value are needed.
4623 SmallVector<Instruction *, 8> WorkList;
4624 SmallPtrSet<Instruction *, 16> Visited;
4625 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4626 for (auto *U : Load->users())
4627 WorkList.push_back(cast<Instruction>(U));
4628
4629 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4630 unsigned BitWidth = LoadResultVT.getSizeInBits();
4631 APInt DemandBits(BitWidth, 0);
4632 APInt WidestAndBits(BitWidth, 0);
4633
4634 while (!WorkList.empty()) {
4635 Instruction *I = WorkList.back();
4636 WorkList.pop_back();
4637
4638 // Break use-def graph loops.
4639 if (!Visited.insert(I).second)
4640 continue;
4641
4642 // For a PHI node, push all of its users.
4643 if (auto *Phi = dyn_cast<PHINode>(I)) {
4644 for (auto *U : Phi->users())
4645 WorkList.push_back(cast<Instruction>(U));
4646 continue;
4647 }
4648
4649 switch (I->getOpcode()) {
4650 case llvm::Instruction::And: {
4651 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4652 if (!AndC)
4653 return false;
4654 APInt AndBits = AndC->getValue();
4655 DemandBits |= AndBits;
4656 // Keep track of the widest and mask we see.
4657 if (AndBits.ugt(WidestAndBits))
4658 WidestAndBits = AndBits;
4659 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4660 AndsToMaybeRemove.push_back(I);
4661 break;
4662 }
4663
4664 case llvm::Instruction::Shl: {
4665 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4666 if (!ShlC)
4667 return false;
4668 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4669 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4670 DemandBits |= ShlDemandBits;
4671 break;
4672 }
4673
4674 case llvm::Instruction::Trunc: {
4675 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4676 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4677 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4678 DemandBits |= TruncBits;
4679 break;
4680 }
4681
4682 default:
4683 return false;
4684 }
4685 }
4686
4687 uint32_t ActiveBits = DemandBits.getActiveBits();
4688 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4689 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4690 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4691 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4692 // followed by an AND.
4693 // TODO: Look into removing this restriction by fixing backends to either
4694 // return false for isLoadExtLegal for i1 or have them select this pattern to
4695 // a single instruction.
4696 //
4697 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4698 // mask, since these are the only ands that will be removed by isel.
4699 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4700 WidestAndBits != DemandBits)
4701 return false;
4702
4703 LLVMContext &Ctx = Load->getType()->getContext();
4704 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4705 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4706
4707 // Reject cases that won't be matched as extloads.
4708 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4709 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4710 return false;
4711
4712 IRBuilder<> Builder(Load->getNextNode());
4713 auto *NewAnd = dyn_cast<Instruction>(
4714 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00004715 // Mark this instruction as "inserted by CGP", so that other
4716 // optimizations don't touch it.
4717 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00004718
4719 // Replace all uses of load with new and (except for the use of load in the
4720 // new and itself).
4721 Load->replaceAllUsesWith(NewAnd);
4722 NewAnd->setOperand(0, Load);
4723
4724 // Remove any and instructions that are now redundant.
4725 for (auto *And : AndsToMaybeRemove)
4726 // Check that the and mask is the same as the one we decided to put on the
4727 // new and.
4728 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4729 And->replaceAllUsesWith(NewAnd);
4730 if (&*CurInstIterator == And)
4731 CurInstIterator = std::next(And->getIterator());
4732 And->eraseFromParent();
4733 ++NumAndUses;
4734 }
4735
4736 ++NumAndsAdded;
4737 return true;
4738}
4739
Sanjay Patel69a50a12015-10-19 21:59:12 +00004740/// Check if V (an operand of a select instruction) is an expensive instruction
4741/// that is only used once.
4742static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4743 auto *I = dyn_cast<Instruction>(V);
4744 // If it's safe to speculatively execute, then it should not have side
4745 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004746 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4747 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004748}
4749
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004750/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004751static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00004752 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00004753 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00004754 // If even a predictable select is cheap, then a branch can't be cheaper.
4755 if (!TLI->isPredictableSelectExpensive())
4756 return false;
4757
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004758 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00004759 // whether a select is better represented as a branch.
4760
4761 // If metadata tells us that the select condition is obviously predictable,
4762 // then we want to replace the select with a branch.
4763 uint64_t TrueWeight, FalseWeight;
4764 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
4765 uint64_t Max = std::max(TrueWeight, FalseWeight);
4766 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00004767 if (Sum != 0) {
4768 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
4769 if (Probability > TLI->getPredictableBranchThreshold())
4770 return true;
4771 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00004772 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004773
4774 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4775
Sanjay Patel4e652762015-09-28 22:14:51 +00004776 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4777 // comparison condition. If the compare has more than one use, there's
4778 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004779 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004780 return false;
4781
Sanjay Patel69a50a12015-10-19 21:59:12 +00004782 // If either operand of the select is expensive and only needed on one side
4783 // of the select, we should form a branch.
4784 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4785 sinkSelectOperand(TTI, SI->getFalseValue()))
4786 return true;
4787
4788 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004789}
4790
Dehao Chen9bbb9412016-09-12 20:23:28 +00004791/// If \p isTrue is true, return the true value of \p SI, otherwise return
4792/// false value of \p SI. If the true/false value of \p SI is defined by any
4793/// select instructions in \p Selects, look through the defining select
4794/// instruction until the true/false value is not defined in \p Selects.
4795static Value *getTrueOrFalseValue(
4796 SelectInst *SI, bool isTrue,
4797 const SmallPtrSet<const Instruction *, 2> &Selects) {
4798 Value *V;
4799
4800 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
4801 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00004802 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00004803 "The condition of DefSI does not match with SI");
4804 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
4805 }
4806 return V;
4807}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004808
Nadav Rotem9d832022012-09-02 12:10:19 +00004809/// If we have a SelectInst that will likely profit from branch prediction,
4810/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004811bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00004812 // Find all consecutive select instructions that share the same condition.
4813 SmallVector<SelectInst *, 2> ASI;
4814 ASI.push_back(SI);
4815 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
4816 It != SI->getParent()->end(); ++It) {
4817 SelectInst *I = dyn_cast<SelectInst>(&*It);
4818 if (I && SI->getCondition() == I->getCondition()) {
4819 ASI.push_back(I);
4820 } else {
4821 break;
4822 }
4823 }
4824
4825 SelectInst *LastSI = ASI.back();
4826 // Increment the current iterator to skip all the rest of select instructions
4827 // because they will be either "not lowered" or "all lowered" to branch.
4828 CurInstIterator = std::next(LastSI->getIterator());
4829
Nadav Rotem9d832022012-09-02 12:10:19 +00004830 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4831
4832 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00004833 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
4834 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004835 return false;
4836
Nadav Rotem9d832022012-09-02 12:10:19 +00004837 TargetLowering::SelectSupportKind SelectKind;
4838 if (VectorCond)
4839 SelectKind = TargetLowering::VectorMaskSelect;
4840 else if (SI->getType()->isVectorTy())
4841 SelectKind = TargetLowering::ScalarCondVectorVal;
4842 else
4843 SelectKind = TargetLowering::ScalarValSelect;
4844
Sanjay Pateld66607b2016-04-26 17:11:17 +00004845 if (TLI->isSelectSupported(SelectKind) &&
4846 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
4847 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004848
4849 ModifiedDT = true;
4850
Sanjay Patel69a50a12015-10-19 21:59:12 +00004851 // Transform a sequence like this:
4852 // start:
4853 // %cmp = cmp uge i32 %a, %b
4854 // %sel = select i1 %cmp, i32 %c, i32 %d
4855 //
4856 // Into:
4857 // start:
4858 // %cmp = cmp uge i32 %a, %b
4859 // br i1 %cmp, label %select.true, label %select.false
4860 // select.true:
4861 // br label %select.end
4862 // select.false:
4863 // br label %select.end
4864 // select.end:
4865 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4866 //
4867 // In addition, we may sink instructions that produce %c or %d from
4868 // the entry block into the destination(s) of the new branch.
4869 // If the true or false blocks do not contain a sunken instruction, that
4870 // block and its branch may be optimized away. In that case, one side of the
4871 // first branch will point directly to select.end, and the corresponding PHI
4872 // predecessor block will be the start block.
4873
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004874 // First, we split the block containing the select into 2 blocks.
4875 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00004876 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004877 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004878
Sanjay Patel69a50a12015-10-19 21:59:12 +00004879 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004880 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004881
4882 // These are the new basic blocks for the conditional branch.
4883 // At least one will become an actual new basic block.
4884 BasicBlock *TrueBlock = nullptr;
4885 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00004886 BranchInst *TrueBranch = nullptr;
4887 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004888
4889 // Sink expensive instructions into the conditional blocks to avoid executing
4890 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00004891 for (SelectInst *SI : ASI) {
4892 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4893 if (TrueBlock == nullptr) {
4894 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4895 EndBlock->getParent(), EndBlock);
4896 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4897 }
4898 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4899 TrueInst->moveBefore(TrueBranch);
4900 }
4901 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4902 if (FalseBlock == nullptr) {
4903 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4904 EndBlock->getParent(), EndBlock);
4905 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4906 }
4907 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4908 FalseInst->moveBefore(FalseBranch);
4909 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00004910 }
4911
4912 // If there was nothing to sink, then arbitrarily choose the 'false' side
4913 // for a new input value to the PHI.
4914 if (TrueBlock == FalseBlock) {
4915 assert(TrueBlock == nullptr &&
4916 "Unexpected basic block transform while optimizing select");
4917
4918 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4919 EndBlock->getParent(), EndBlock);
4920 BranchInst::Create(EndBlock, FalseBlock);
4921 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004922
4923 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004924 // If we did not create a new block for one of the 'true' or 'false' paths
4925 // of the condition, it means that side of the branch goes to the end block
4926 // directly and the path originates from the start block from the point of
4927 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00004928 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004929 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004930 TT = EndBlock;
4931 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004932 TrueBlock = StartBlock;
4933 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004934 TT = TrueBlock;
4935 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004936 FalseBlock = StartBlock;
4937 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004938 TT = TrueBlock;
4939 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004940 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00004941 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004942
Dehao Chen9bbb9412016-09-12 20:23:28 +00004943 SmallPtrSet<const Instruction *, 2> INS;
4944 INS.insert(ASI.begin(), ASI.end());
4945 // Use reverse iterator because later select may use the value of the
4946 // earlier select, and we need to propagate value through earlier select
4947 // to get the PHI operand.
4948 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
4949 SelectInst *SI = *It;
4950 // The select itself is replaced with a PHI Node.
4951 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
4952 PN->takeName(SI);
4953 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
4954 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004955
Dehao Chen9bbb9412016-09-12 20:23:28 +00004956 SI->replaceAllUsesWith(PN);
4957 SI->eraseFromParent();
4958 INS.erase(SI);
4959 ++NumSelectsExpanded;
4960 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004961
4962 // Instruct OptimizeBlock to skip to the next block.
4963 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004964 return true;
4965}
4966
Benjamin Kramer573ff362014-03-01 17:24:40 +00004967static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004968 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4969 int SplatElem = -1;
4970 for (unsigned i = 0; i < Mask.size(); ++i) {
4971 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4972 return false;
4973 SplatElem = Mask[i];
4974 }
4975
4976 return true;
4977}
4978
4979/// Some targets have expensive vector shifts if the lanes aren't all the same
4980/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4981/// it's often worth sinking a shufflevector splat down to its use so that
4982/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004983bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004984 BasicBlock *DefBB = SVI->getParent();
4985
4986 // Only do this xform if variable vector shifts are particularly expensive.
4987 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4988 return false;
4989
4990 // We only expect better codegen by sinking a shuffle if we can recognise a
4991 // constant splat.
4992 if (!isBroadcastShuffle(SVI))
4993 return false;
4994
4995 // InsertedShuffles - Only insert a shuffle in each block once.
4996 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4997
4998 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004999 for (User *U : SVI->users()) {
5000 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005001
5002 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005003 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005004 if (UserBB == DefBB) continue;
5005
5006 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005007 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005008
5009 // Everything checks out, sink the shuffle if the user's block doesn't
5010 // already have a copy.
5011 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5012
5013 if (!InsertedShuffle) {
5014 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005015 assert(InsertPt != UserBB->end());
5016 InsertedShuffle =
5017 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5018 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005019 }
5020
Chandler Carruthcdf47882014-03-09 03:16:01 +00005021 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005022 MadeChange = true;
5023 }
5024
5025 // If we removed all uses, nuke the shuffle.
5026 if (SVI->use_empty()) {
5027 SVI->eraseFromParent();
5028 MadeChange = true;
5029 }
5030
5031 return MadeChange;
5032}
5033
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005034bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5035 if (!TLI || !DL)
5036 return false;
5037
5038 Value *Cond = SI->getCondition();
5039 Type *OldType = Cond->getType();
5040 LLVMContext &Context = Cond->getContext();
5041 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5042 unsigned RegWidth = RegType.getSizeInBits();
5043
5044 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5045 return false;
5046
5047 // If the register width is greater than the type width, expand the condition
5048 // of the switch instruction and each case constant to the width of the
5049 // register. By widening the type of the switch condition, subsequent
5050 // comparisons (for case comparisons) will not need to be extended to the
5051 // preferred register width, so we will potentially eliminate N-1 extends,
5052 // where N is the number of cases in the switch.
5053 auto *NewType = Type::getIntNTy(Context, RegWidth);
5054
5055 // Zero-extend the switch condition and case constants unless the switch
5056 // condition is a function argument that is already being sign-extended.
5057 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5058 // everything instead.
5059 Instruction::CastOps ExtType = Instruction::ZExt;
5060 if (auto *Arg = dyn_cast<Argument>(Cond))
5061 if (Arg->hasSExtAttr())
5062 ExtType = Instruction::SExt;
5063
5064 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5065 ExtInst->insertBefore(SI);
5066 SI->setCondition(ExtInst);
5067 for (SwitchInst::CaseIt Case : SI->cases()) {
5068 APInt NarrowConst = Case.getCaseValue()->getValue();
5069 APInt WideConst = (ExtType == Instruction::ZExt) ?
5070 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5071 Case.setValue(ConstantInt::get(Context, WideConst));
5072 }
5073
5074 return true;
5075}
5076
Quentin Colombetc32615d2014-10-31 17:52:53 +00005077namespace {
5078/// \brief Helper class to promote a scalar operation to a vector one.
5079/// This class is used to move downward extractelement transition.
5080/// E.g.,
5081/// a = vector_op <2 x i32>
5082/// b = extractelement <2 x i32> a, i32 0
5083/// c = scalar_op b
5084/// store c
5085///
5086/// =>
5087/// a = vector_op <2 x i32>
5088/// c = vector_op a (equivalent to scalar_op on the related lane)
5089/// * d = extractelement <2 x i32> c, i32 0
5090/// * store d
5091/// Assuming both extractelement and store can be combine, we get rid of the
5092/// transition.
5093class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005094 /// DataLayout associated with the current module.
5095 const DataLayout &DL;
5096
Quentin Colombetc32615d2014-10-31 17:52:53 +00005097 /// Used to perform some checks on the legality of vector operations.
5098 const TargetLowering &TLI;
5099
5100 /// Used to estimated the cost of the promoted chain.
5101 const TargetTransformInfo &TTI;
5102
5103 /// The transition being moved downwards.
5104 Instruction *Transition;
5105 /// The sequence of instructions to be promoted.
5106 SmallVector<Instruction *, 4> InstsToBePromoted;
5107 /// Cost of combining a store and an extract.
5108 unsigned StoreExtractCombineCost;
5109 /// Instruction that will be combined with the transition.
5110 Instruction *CombineInst;
5111
5112 /// \brief The instruction that represents the current end of the transition.
5113 /// Since we are faking the promotion until we reach the end of the chain
5114 /// of computation, we need a way to get the current end of the transition.
5115 Instruction *getEndOfTransition() const {
5116 if (InstsToBePromoted.empty())
5117 return Transition;
5118 return InstsToBePromoted.back();
5119 }
5120
5121 /// \brief Return the index of the original value in the transition.
5122 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5123 /// c, is at index 0.
5124 unsigned getTransitionOriginalValueIdx() const {
5125 assert(isa<ExtractElementInst>(Transition) &&
5126 "Other kind of transitions are not supported yet");
5127 return 0;
5128 }
5129
5130 /// \brief Return the index of the index in the transition.
5131 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5132 /// is at index 1.
5133 unsigned getTransitionIdx() const {
5134 assert(isa<ExtractElementInst>(Transition) &&
5135 "Other kind of transitions are not supported yet");
5136 return 1;
5137 }
5138
5139 /// \brief Get the type of the transition.
5140 /// This is the type of the original value.
5141 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5142 /// transition is <2 x i32>.
5143 Type *getTransitionType() const {
5144 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5145 }
5146
5147 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5148 /// I.e., we have the following sequence:
5149 /// Def = Transition <ty1> a to <ty2>
5150 /// b = ToBePromoted <ty2> Def, ...
5151 /// =>
5152 /// b = ToBePromoted <ty1> a, ...
5153 /// Def = Transition <ty1> ToBePromoted to <ty2>
5154 void promoteImpl(Instruction *ToBePromoted);
5155
5156 /// \brief Check whether or not it is profitable to promote all the
5157 /// instructions enqueued to be promoted.
5158 bool isProfitableToPromote() {
5159 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5160 unsigned Index = isa<ConstantInt>(ValIdx)
5161 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5162 : -1;
5163 Type *PromotedType = getTransitionType();
5164
5165 StoreInst *ST = cast<StoreInst>(CombineInst);
5166 unsigned AS = ST->getPointerAddressSpace();
5167 unsigned Align = ST->getAlignment();
5168 // Check if this store is supported.
5169 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005170 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5171 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005172 // If this is not supported, there is no way we can combine
5173 // the extract with the store.
5174 return false;
5175 }
5176
5177 // The scalar chain of computation has to pay for the transition
5178 // scalar to vector.
5179 // The vector chain has to account for the combining cost.
5180 uint64_t ScalarCost =
5181 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5182 uint64_t VectorCost = StoreExtractCombineCost;
5183 for (const auto &Inst : InstsToBePromoted) {
5184 // Compute the cost.
5185 // By construction, all instructions being promoted are arithmetic ones.
5186 // Moreover, one argument is a constant that can be viewed as a splat
5187 // constant.
5188 Value *Arg0 = Inst->getOperand(0);
5189 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5190 isa<ConstantFP>(Arg0);
5191 TargetTransformInfo::OperandValueKind Arg0OVK =
5192 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5193 : TargetTransformInfo::OK_AnyValue;
5194 TargetTransformInfo::OperandValueKind Arg1OVK =
5195 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5196 : TargetTransformInfo::OK_AnyValue;
5197 ScalarCost += TTI.getArithmeticInstrCost(
5198 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5199 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5200 Arg0OVK, Arg1OVK);
5201 }
5202 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5203 << ScalarCost << "\nVector: " << VectorCost << '\n');
5204 return ScalarCost > VectorCost;
5205 }
5206
5207 /// \brief Generate a constant vector with \p Val with the same
5208 /// number of elements as the transition.
5209 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005210 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005211 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5212 /// otherwise we generate a vector with as many undef as possible:
5213 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5214 /// used at the index of the extract.
5215 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5216 unsigned ExtractIdx = UINT_MAX;
5217 if (!UseSplat) {
5218 // If we cannot determine where the constant must be, we have to
5219 // use a splat constant.
5220 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5221 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5222 ExtractIdx = CstVal->getSExtValue();
5223 else
5224 UseSplat = true;
5225 }
5226
5227 unsigned End = getTransitionType()->getVectorNumElements();
5228 if (UseSplat)
5229 return ConstantVector::getSplat(End, Val);
5230
5231 SmallVector<Constant *, 4> ConstVec;
5232 UndefValue *UndefVal = UndefValue::get(Val->getType());
5233 for (unsigned Idx = 0; Idx != End; ++Idx) {
5234 if (Idx == ExtractIdx)
5235 ConstVec.push_back(Val);
5236 else
5237 ConstVec.push_back(UndefVal);
5238 }
5239 return ConstantVector::get(ConstVec);
5240 }
5241
5242 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5243 /// in \p Use can trigger undefined behavior.
5244 static bool canCauseUndefinedBehavior(const Instruction *Use,
5245 unsigned OperandIdx) {
5246 // This is not safe to introduce undef when the operand is on
5247 // the right hand side of a division-like instruction.
5248 if (OperandIdx != 1)
5249 return false;
5250 switch (Use->getOpcode()) {
5251 default:
5252 return false;
5253 case Instruction::SDiv:
5254 case Instruction::UDiv:
5255 case Instruction::SRem:
5256 case Instruction::URem:
5257 return true;
5258 case Instruction::FDiv:
5259 case Instruction::FRem:
5260 return !Use->hasNoNaNs();
5261 }
5262 llvm_unreachable(nullptr);
5263 }
5264
5265public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005266 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5267 const TargetTransformInfo &TTI, Instruction *Transition,
5268 unsigned CombineCost)
5269 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00005270 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5271 assert(Transition && "Do not know how to promote null");
5272 }
5273
5274 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5275 bool canPromote(const Instruction *ToBePromoted) const {
5276 // We could support CastInst too.
5277 return isa<BinaryOperator>(ToBePromoted);
5278 }
5279
5280 /// \brief Check if it is profitable to promote \p ToBePromoted
5281 /// by moving downward the transition through.
5282 bool shouldPromote(const Instruction *ToBePromoted) const {
5283 // Promote only if all the operands can be statically expanded.
5284 // Indeed, we do not want to introduce any new kind of transitions.
5285 for (const Use &U : ToBePromoted->operands()) {
5286 const Value *Val = U.get();
5287 if (Val == getEndOfTransition()) {
5288 // If the use is a division and the transition is on the rhs,
5289 // we cannot promote the operation, otherwise we may create a
5290 // division by zero.
5291 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5292 return false;
5293 continue;
5294 }
5295 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5296 !isa<ConstantFP>(Val))
5297 return false;
5298 }
5299 // Check that the resulting operation is legal.
5300 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5301 if (!ISDOpcode)
5302 return false;
5303 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005304 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005305 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005306 }
5307
5308 /// \brief Check whether or not \p Use can be combined
5309 /// with the transition.
5310 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5311 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5312
5313 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5314 void enqueueForPromotion(Instruction *ToBePromoted) {
5315 InstsToBePromoted.push_back(ToBePromoted);
5316 }
5317
5318 /// \brief Set the instruction that will be combined with the transition.
5319 void recordCombineInstruction(Instruction *ToBeCombined) {
5320 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5321 CombineInst = ToBeCombined;
5322 }
5323
5324 /// \brief Promote all the instructions enqueued for promotion if it is
5325 /// is profitable.
5326 /// \return True if the promotion happened, false otherwise.
5327 bool promote() {
5328 // Check if there is something to promote.
5329 // Right now, if we do not have anything to combine with,
5330 // we assume the promotion is not profitable.
5331 if (InstsToBePromoted.empty() || !CombineInst)
5332 return false;
5333
5334 // Check cost.
5335 if (!StressStoreExtract && !isProfitableToPromote())
5336 return false;
5337
5338 // Promote.
5339 for (auto &ToBePromoted : InstsToBePromoted)
5340 promoteImpl(ToBePromoted);
5341 InstsToBePromoted.clear();
5342 return true;
5343 }
5344};
5345} // End of anonymous namespace.
5346
5347void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5348 // At this point, we know that all the operands of ToBePromoted but Def
5349 // can be statically promoted.
5350 // For Def, we need to use its parameter in ToBePromoted:
5351 // b = ToBePromoted ty1 a
5352 // Def = Transition ty1 b to ty2
5353 // Move the transition down.
5354 // 1. Replace all uses of the promoted operation by the transition.
5355 // = ... b => = ... Def.
5356 assert(ToBePromoted->getType() == Transition->getType() &&
5357 "The type of the result of the transition does not match "
5358 "the final type");
5359 ToBePromoted->replaceAllUsesWith(Transition);
5360 // 2. Update the type of the uses.
5361 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5362 Type *TransitionTy = getTransitionType();
5363 ToBePromoted->mutateType(TransitionTy);
5364 // 3. Update all the operands of the promoted operation with promoted
5365 // operands.
5366 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5367 for (Use &U : ToBePromoted->operands()) {
5368 Value *Val = U.get();
5369 Value *NewVal = nullptr;
5370 if (Val == Transition)
5371 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5372 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5373 isa<ConstantFP>(Val)) {
5374 // Use a splat constant if it is not safe to use undef.
5375 NewVal = getConstantVector(
5376 cast<Constant>(Val),
5377 isa<UndefValue>(Val) ||
5378 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5379 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005380 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5381 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005382 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5383 }
5384 Transition->removeFromParent();
5385 Transition->insertAfter(ToBePromoted);
5386 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5387}
5388
5389/// Some targets can do store(extractelement) with one instruction.
5390/// Try to push the extractelement towards the stores when the target
5391/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005392bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005393 unsigned CombineCost = UINT_MAX;
5394 if (DisableStoreExtract || !TLI ||
5395 (!StressStoreExtract &&
5396 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5397 Inst->getOperand(1), CombineCost)))
5398 return false;
5399
5400 // At this point we know that Inst is a vector to scalar transition.
5401 // Try to move it down the def-use chain, until:
5402 // - We can combine the transition with its single use
5403 // => we got rid of the transition.
5404 // - We escape the current basic block
5405 // => we would need to check that we are moving it at a cheaper place and
5406 // we do not do that for now.
5407 BasicBlock *Parent = Inst->getParent();
5408 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005409 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005410 // If the transition has more than one use, assume this is not going to be
5411 // beneficial.
5412 while (Inst->hasOneUse()) {
5413 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5414 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5415
5416 if (ToBePromoted->getParent() != Parent) {
5417 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5418 << ToBePromoted->getParent()->getName()
5419 << ") than the transition (" << Parent->getName() << ").\n");
5420 return false;
5421 }
5422
5423 if (VPH.canCombine(ToBePromoted)) {
5424 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5425 << "will be combined with: " << *ToBePromoted << '\n');
5426 VPH.recordCombineInstruction(ToBePromoted);
5427 bool Changed = VPH.promote();
5428 NumStoreExtractExposed += Changed;
5429 return Changed;
5430 }
5431
5432 DEBUG(dbgs() << "Try promoting.\n");
5433 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5434 return false;
5435
5436 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5437
5438 VPH.enqueueForPromotion(ToBePromoted);
5439 Inst = ToBePromoted;
5440 }
5441 return false;
5442}
5443
Wei Mia2f0b592016-12-22 19:44:45 +00005444/// For the instruction sequence of store below, F and I values
5445/// are bundled together as an i64 value before being stored into memory.
5446/// Sometimes it is more efficent to generate separate stores for F and I,
5447/// which can remove the bitwise instructions or sink them to colder places.
5448///
5449/// (store (or (zext (bitcast F to i32) to i64),
5450/// (shl (zext I to i64), 32)), addr) -->
5451/// (store F, addr) and (store I, addr+4)
5452///
5453/// Similarly, splitting for other merged store can also be beneficial, like:
5454/// For pair of {i32, i32}, i64 store --> two i32 stores.
5455/// For pair of {i32, i16}, i64 store --> two i32 stores.
5456/// For pair of {i16, i16}, i32 store --> two i16 stores.
5457/// For pair of {i16, i8}, i32 store --> two i16 stores.
5458/// For pair of {i8, i8}, i16 store --> two i8 stores.
5459///
5460/// We allow each target to determine specifically which kind of splitting is
5461/// supported.
5462///
5463/// The store patterns are commonly seen from the simple code snippet below
5464/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
5465/// void goo(const std::pair<int, float> &);
5466/// hoo() {
5467/// ...
5468/// goo(std::make_pair(tmp, ftmp));
5469/// ...
5470/// }
5471///
5472/// Although we already have similar splitting in DAG Combine, we duplicate
5473/// it in CodeGenPrepare to catch the case in which pattern is across
5474/// multiple BBs. The logic in DAG Combine is kept to catch case generated
5475/// during code expansion.
5476static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
5477 const TargetLowering &TLI) {
5478 // Handle simple but common cases only.
5479 Type *StoreType = SI.getValueOperand()->getType();
5480 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
5481 DL.getTypeSizeInBits(StoreType) == 0)
5482 return false;
5483
5484 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
5485 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
5486 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
5487 DL.getTypeSizeInBits(SplitStoreType))
5488 return false;
5489
5490 // Match the following patterns:
5491 // (store (or (zext LValue to i64),
5492 // (shl (zext HValue to i64), 32)), HalfValBitSize)
5493 // or
5494 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
5495 // (zext LValue to i64),
5496 // Expect both operands of OR and the first operand of SHL have only
5497 // one use.
5498 Value *LValue, *HValue;
5499 if (!match(SI.getValueOperand(),
5500 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
5501 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
5502 m_SpecificInt(HalfValBitSize))))))
5503 return false;
5504
5505 // Check LValue and HValue are int with size less or equal than 32.
5506 if (!LValue->getType()->isIntegerTy() ||
5507 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
5508 !HValue->getType()->isIntegerTy() ||
5509 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
5510 return false;
5511
5512 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
5513 // as the input of target query.
5514 auto *LBC = dyn_cast<BitCastInst>(LValue);
5515 auto *HBC = dyn_cast<BitCastInst>(HValue);
5516 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
5517 : EVT::getEVT(LValue->getType());
5518 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
5519 : EVT::getEVT(HValue->getType());
5520 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
5521 return false;
5522
5523 // Start to split store.
5524 IRBuilder<> Builder(SI.getContext());
5525 Builder.SetInsertPoint(&SI);
5526
5527 // If LValue/HValue is a bitcast in another BB, create a new one in current
5528 // BB so it may be merged with the splitted stores by dag combiner.
5529 if (LBC && LBC->getParent() != SI.getParent())
5530 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
5531 if (HBC && HBC->getParent() != SI.getParent())
5532 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
5533
5534 auto CreateSplitStore = [&](Value *V, bool Upper) {
5535 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
5536 Value *Addr = Builder.CreateBitCast(
5537 SI.getOperand(1),
5538 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
5539 if (Upper)
5540 Addr = Builder.CreateGEP(
5541 SplitStoreType, Addr,
5542 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
5543 Builder.CreateAlignedStore(
5544 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
5545 };
5546
5547 CreateSplitStore(LValue, false);
5548 CreateSplitStore(HValue, true);
5549
5550 // Delete the old store.
5551 SI.eraseFromParent();
5552 return true;
5553}
5554
Sanjay Patelfc580a62015-09-21 23:03:16 +00005555bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005556 // Bail out if we inserted the instruction to prevent optimizations from
5557 // stepping on each other's toes.
5558 if (InsertedInsts.count(I))
5559 return false;
5560
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005561 if (PHINode *P = dyn_cast<PHINode>(I)) {
5562 // It is possible for very late stage optimizations (such as SimplifyCFG)
5563 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5564 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005565 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005566 P->replaceAllUsesWith(V);
5567 P->eraseFromParent();
5568 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005569 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005570 }
Chris Lattneree588de2011-01-15 07:29:01 +00005571 return false;
5572 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005573
Chris Lattneree588de2011-01-15 07:29:01 +00005574 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005575 // If the source of the cast is a constant, then this should have
5576 // already been constant folded. The only reason NOT to constant fold
5577 // it is if something (e.g. LSR) was careful to place the constant
5578 // evaluation in a block other than then one that uses it (e.g. to hoist
5579 // the address of globals out of a loop). If this is the case, we don't
5580 // want to forward-subst the cast.
5581 if (isa<Constant>(CI->getOperand(0)))
5582 return false;
5583
Mehdi Amini44ede332015-07-09 02:09:04 +00005584 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005585 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005586
Chris Lattneree588de2011-01-15 07:29:01 +00005587 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005588 /// Sink a zext or sext into its user blocks if the target type doesn't
5589 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005590 if (TLI &&
5591 TLI->getTypeAction(CI->getContext(),
5592 TLI->getValueType(*DL, CI->getType())) ==
5593 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005594 return SinkCast(CI);
5595 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005596 bool MadeChange = moveExtToFormExtLoad(I);
5597 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005598 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005599 }
Chris Lattneree588de2011-01-15 07:29:01 +00005600 return false;
5601 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005602
Chris Lattneree588de2011-01-15 07:29:01 +00005603 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005604 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00005605 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005606
Chris Lattneree588de2011-01-15 07:29:01 +00005607 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00005608 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005609 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005610 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005611 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005612 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5613 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005614 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005615 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005616 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005617
Chris Lattneree588de2011-01-15 07:29:01 +00005618 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00005619 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
5620 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00005621 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005622 if (TLI) {
5623 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005624 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005625 SI->getOperand(0)->getType(), AS);
5626 }
Chris Lattneree588de2011-01-15 07:29:01 +00005627 return false;
5628 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005629
Yi Jiangd069f632014-04-21 19:34:27 +00005630 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5631
Geoff Berry5d534b62017-02-21 18:53:14 +00005632 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
5633 EnableAndCmpSinking && TLI)
5634 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
5635
Yi Jiangd069f632014-04-21 19:34:27 +00005636 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5637 BinOp->getOpcode() == Instruction::LShr)) {
5638 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5639 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005640 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005641
5642 return false;
5643 }
5644
Chris Lattneree588de2011-01-15 07:29:01 +00005645 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005646 if (GEPI->hasAllZeroIndices()) {
5647 /// The GEP operand must be a pointer, so must its result -> BitCast
5648 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5649 GEPI->getName(), GEPI);
5650 GEPI->replaceAllUsesWith(NC);
5651 GEPI->eraseFromParent();
5652 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005653 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005654 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005655 }
Chris Lattneree588de2011-01-15 07:29:01 +00005656 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005657 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005658
Chris Lattneree588de2011-01-15 07:29:01 +00005659 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005660 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005661
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005662 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005663 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005664
Tim Northoveraeb8e062014-02-19 10:02:43 +00005665 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005666 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005667
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005668 if (auto *Switch = dyn_cast<SwitchInst>(I))
5669 return optimizeSwitchInst(Switch);
5670
Quentin Colombetc32615d2014-10-31 17:52:53 +00005671 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005672 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005673
Chris Lattneree588de2011-01-15 07:29:01 +00005674 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005675}
5676
James Molloyf01488e2016-01-15 09:20:19 +00005677/// Given an OR instruction, check to see if this is a bitreverse
5678/// idiom. If so, insert the new intrinsic and return true.
5679static bool makeBitReverse(Instruction &I, const DataLayout &DL,
5680 const TargetLowering &TLI) {
5681 if (!I.getType()->isIntegerTy() ||
5682 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
5683 TLI.getValueType(DL, I.getType(), true)))
5684 return false;
5685
5686 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00005687 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00005688 return false;
5689 Instruction *LastInst = Insts.back();
5690 I.replaceAllUsesWith(LastInst);
5691 RecursivelyDeleteTriviallyDeadInstructions(&I);
5692 return true;
5693}
5694
Chris Lattnerf2836d12007-03-31 04:06:36 +00005695// In this pass we look for GEP and cast instructions that are used
5696// across basic blocks and rewrite them to improve basic-block-at-a-time
5697// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005698bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005699 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005700 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005701
Chris Lattner7a277142011-01-15 07:14:54 +00005702 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005703 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005704 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005705 if (ModifiedDT)
5706 return true;
5707 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00005708
James Molloyf01488e2016-01-15 09:20:19 +00005709 bool MadeBitReverse = true;
5710 while (TLI && MadeBitReverse) {
5711 MadeBitReverse = false;
5712 for (auto &I : reverse(BB)) {
5713 if (makeBitReverse(I, *DL, *TLI)) {
5714 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00005715 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00005716 break;
5717 }
5718 }
5719 }
James Molloy3ef84c42016-01-15 10:36:01 +00005720 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00005721
Chris Lattnerf2836d12007-03-31 04:06:36 +00005722 return MadeChange;
5723}
Devang Patel53771ba2011-08-18 00:50:51 +00005724
5725// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005726// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005727// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005728bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005729 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005730 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005731 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005732 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005733 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005734 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005735 // Leave dbg.values that refer to an alloca alone. These
5736 // instrinsics describe the address of a variable (= the alloca)
5737 // being taken. They should not be moved next to the alloca
5738 // (and to the beginning of the scope), but rather stay close to
5739 // where said address is used.
5740 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005741 PrevNonDbgInst = Insn;
5742 continue;
5743 }
5744
5745 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5746 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00005747 // If VI is a phi in a block with an EHPad terminator, we can't insert
5748 // after it.
5749 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5750 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00005751 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5752 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00005753 if (isa<PHINode>(VI))
5754 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5755 else
5756 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00005757 MadeChange = true;
5758 ++NumDbgValueMoved;
5759 }
5760 }
5761 }
5762 return MadeChange;
5763}
Tim Northovercea0abb2014-03-29 08:22:29 +00005764
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005765/// \brief Scale down both weights to fit into uint32_t.
5766static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5767 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5768 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5769 NewTrue = NewTrue / Scale;
5770 NewFalse = NewFalse / Scale;
5771}
5772
5773/// \brief Some targets prefer to split a conditional branch like:
5774/// \code
5775/// %0 = icmp ne i32 %a, 0
5776/// %1 = icmp ne i32 %b, 0
5777/// %or.cond = or i1 %0, %1
5778/// br i1 %or.cond, label %TrueBB, label %FalseBB
5779/// \endcode
5780/// into multiple branch instructions like:
5781/// \code
5782/// bb1:
5783/// %0 = icmp ne i32 %a, 0
5784/// br i1 %0, label %TrueBB, label %bb2
5785/// bb2:
5786/// %1 = icmp ne i32 %b, 0
5787/// br i1 %1, label %TrueBB, label %FalseBB
5788/// \endcode
5789/// This usually allows instruction selection to do even further optimizations
5790/// and combine the compare with the branch instruction. Currently this is
5791/// applied for targets which have "cheap" jump instructions.
5792///
5793/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5794///
5795bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005796 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005797 return false;
5798
5799 bool MadeChange = false;
5800 for (auto &BB : F) {
5801 // Does this BB end with the following?
5802 // %cond1 = icmp|fcmp|binary instruction ...
5803 // %cond2 = icmp|fcmp|binary instruction ...
5804 // %cond.or = or|and i1 %cond1, cond2
5805 // br i1 %cond.or label %dest1, label %dest2"
5806 BinaryOperator *LogicOp;
5807 BasicBlock *TBB, *FBB;
5808 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5809 continue;
5810
Sanjay Patel42574202015-09-02 19:23:23 +00005811 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5812 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5813 continue;
5814
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005815 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005816 Value *Cond1, *Cond2;
5817 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5818 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005819 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005820 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5821 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005822 Opc = Instruction::Or;
5823 else
5824 continue;
5825
5826 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5827 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5828 continue;
5829
5830 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5831
5832 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00005833 auto TmpBB =
5834 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
5835 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005836
5837 // Update original basic block by using the first condition directly by the
5838 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005839 Br1->setCondition(Cond1);
5840 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005841
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005842 // Depending on the conditon we have to either replace the true or the false
5843 // successor of the original branch instruction.
5844 if (Opc == Instruction::And)
5845 Br1->setSuccessor(0, TmpBB);
5846 else
5847 Br1->setSuccessor(1, TmpBB);
5848
5849 // Fill in the new basic block.
5850 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005851 if (auto *I = dyn_cast<Instruction>(Cond2)) {
5852 I->removeFromParent();
5853 I->insertBefore(Br2);
5854 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005855
5856 // Update PHI nodes in both successors. The original BB needs to be
5857 // replaced in one succesor's PHI nodes, because the branch comes now from
5858 // the newly generated BB (NewBB). In the other successor we need to add one
5859 // incoming edge to the PHI nodes, because both branch instructions target
5860 // now the same successor. Depending on the original branch condition
5861 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00005862 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005863 // This doesn't change the successor order of the just created branch
5864 // instruction (or any other instruction).
5865 if (Opc == Instruction::Or)
5866 std::swap(TBB, FBB);
5867
5868 // Replace the old BB with the new BB.
5869 for (auto &I : *TBB) {
5870 PHINode *PN = dyn_cast<PHINode>(&I);
5871 if (!PN)
5872 break;
5873 int i;
5874 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5875 PN->setIncomingBlock(i, TmpBB);
5876 }
5877
5878 // Add another incoming edge form the new BB.
5879 for (auto &I : *FBB) {
5880 PHINode *PN = dyn_cast<PHINode>(&I);
5881 if (!PN)
5882 break;
5883 auto *Val = PN->getIncomingValueForBlock(&BB);
5884 PN->addIncoming(Val, TmpBB);
5885 }
5886
5887 // Update the branch weights (from SelectionDAGBuilder::
5888 // FindMergedConditions).
5889 if (Opc == Instruction::Or) {
5890 // Codegen X | Y as:
5891 // BB1:
5892 // jmp_if_X TBB
5893 // jmp TmpBB
5894 // TmpBB:
5895 // jmp_if_Y TBB
5896 // jmp FBB
5897 //
5898
5899 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5900 // The requirement is that
5901 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5902 // = TrueProb for orignal BB.
5903 // Assuming the orignal weights are A and B, one choice is to set BB1's
5904 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5905 // assumes that
5906 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5907 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5908 // TmpBB, but the math is more complicated.
5909 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005910 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005911 uint64_t NewTrueWeight = TrueWeight;
5912 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5913 scaleWeights(NewTrueWeight, NewFalseWeight);
5914 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5915 .createBranchWeights(TrueWeight, FalseWeight));
5916
5917 NewTrueWeight = TrueWeight;
5918 NewFalseWeight = 2 * FalseWeight;
5919 scaleWeights(NewTrueWeight, NewFalseWeight);
5920 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5921 .createBranchWeights(TrueWeight, FalseWeight));
5922 }
5923 } else {
5924 // Codegen X & Y as:
5925 // BB1:
5926 // jmp_if_X TmpBB
5927 // jmp FBB
5928 // TmpBB:
5929 // jmp_if_Y TBB
5930 // jmp FBB
5931 //
5932 // This requires creation of TmpBB after CurBB.
5933
5934 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5935 // The requirement is that
5936 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5937 // = FalseProb for orignal BB.
5938 // Assuming the orignal weights are A and B, one choice is to set BB1's
5939 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5940 // assumes that
5941 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5942 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005943 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005944 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5945 uint64_t NewFalseWeight = FalseWeight;
5946 scaleWeights(NewTrueWeight, NewFalseWeight);
5947 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5948 .createBranchWeights(TrueWeight, FalseWeight));
5949
5950 NewTrueWeight = 2 * TrueWeight;
5951 NewFalseWeight = FalseWeight;
5952 scaleWeights(NewTrueWeight, NewFalseWeight);
5953 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5954 .createBranchWeights(TrueWeight, FalseWeight));
5955 }
5956 }
5957
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005958 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00005959 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005960 ModifiedDT = true;
5961
5962 MadeChange = true;
5963
5964 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5965 TmpBB->dump());
5966 }
5967 return MadeChange;
5968}