blob: aff4e9519e12b3e8aa895c45e42e491b8209759f [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 Lim82f55c52016-11-21 16:47:28 +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");
Tim Northovercea0abb2014-03-29 08:22:29 +000080STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000081STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000082
Cameron Zwarich338d3622011-03-11 21:52:04 +000083static cl::opt<bool> DisableBranchOpts(
84 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
85 cl::desc("Disable branch optimizations in CodeGenPrepare"));
86
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000087static cl::opt<bool>
88 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
89 cl::desc("Disable GC optimizations in CodeGenPrepare"));
90
Benjamin Kramer3d38c172012-05-06 14:25:16 +000091static cl::opt<bool> DisableSelectToBranch(
92 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
93 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000094
Hal Finkelc3998302014-04-12 00:59:48 +000095static cl::opt<bool> AddrSinkUsingGEPs(
96 "addr-sink-using-gep", cl::Hidden, cl::init(false),
97 cl::desc("Address sinking in CGP using GEPs."));
98
Tim Northovercea0abb2014-03-29 08:22:29 +000099static cl::opt<bool> EnableAndCmpSinking(
100 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
101 cl::desc("Enable sinkinig and/cmp into branches."));
102
Quentin Colombetc32615d2014-10-31 17:52:53 +0000103static cl::opt<bool> DisableStoreExtract(
104 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
105 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
106
107static cl::opt<bool> StressStoreExtract(
108 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
109 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
110
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000111static cl::opt<bool> DisableExtLdPromotion(
112 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
113 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
114 "CodeGenPrepare"));
115
116static cl::opt<bool> StressExtLdPromotion(
117 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
118 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
119 "optimization in CodeGenPrepare"));
120
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000121static cl::opt<bool> DisablePreheaderProtect(
122 "disable-preheader-prot", cl::Hidden, cl::init(false),
123 cl::desc("Disable protection against removing loop preheaders"));
124
Dehao Chen302b69c2016-10-18 20:42:47 +0000125static cl::opt<bool> ProfileGuidedSectionPrefix(
126 "profile-guided-section-prefix", cl::Hidden, cl::init(true),
127 cl::desc("Use profile info to add section prefix for hot/cold functions"));
128
Jun Bum Lim82f55c52016-11-21 16:47:28 +0000129static cl::opt<unsigned> FreqRatioToSkipMerge(
130 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
131 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
132 "(frequency of destination block) is greater than this ratio"));
133
Eric Christopherc1ea1492008-09-24 05:32:41 +0000134namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000135typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000136typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000137typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000138class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000139
Chris Lattner2dd09db2009-09-02 06:11:42 +0000140 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000141 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000142 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000143 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000144 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000145 const LoopInfo *LI;
Jun Bum Lim82f55c52016-11-21 16:47:28 +0000146 std::unique_ptr<BlockFrequencyInfo> BFI;
147 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000148
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000149 /// As we scan instructions optimizing them, this is the next instruction
150 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000151 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000152
Evan Cheng0663f232011-03-21 01:19:09 +0000153 /// Keeps track of non-local addresses that have been sunk into a block.
154 /// This allows us to avoid inserting duplicate code for blocks with
155 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000156 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000157
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000158 /// Keeps track of all instructions inserted for the current function.
159 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000160 /// Keeps track of the type of the related instruction before their
161 /// promotion for the current function.
162 InstrToOrigTy PromotedInsts;
163
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000164 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000165 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000166
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000167 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000168 bool OptSize;
169
Mehdi Amini4fe37982015-07-07 18:45:17 +0000170 /// DataLayout for the Function being processed.
171 const DataLayout *DL;
172
Chris Lattnerf2836d12007-03-31 04:06:36 +0000173 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000174 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000175 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000176 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000177 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
178 }
Craig Topper4584cd52014-03-07 09:26:03 +0000179 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000180
Mehdi Amini117296c2016-10-01 02:56:57 +0000181 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000182
Craig Topper4584cd52014-03-07 09:26:03 +0000183 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000184 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000185 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000186 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000187 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000188 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000189 }
190
Chris Lattnerf2836d12007-03-31 04:06:36 +0000191 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000192 bool eliminateFallThrough(Function &F);
193 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim82f55c52016-11-21 16:47:28 +0000194 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000195 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
196 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim82f55c52016-11-21 16:47:28 +0000197 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
198 bool isPreheader);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000199 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
200 bool optimizeInst(Instruction *I, bool& ModifiedDT);
201 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000202 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000203 bool optimizeInlineAsmInst(CallInst *CS);
204 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
205 bool moveExtToFormExtLoad(Instruction *&I);
206 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000207 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000208 bool optimizeSelectInst(SelectInst *SI);
209 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000210 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000211 bool optimizeExtractElementInst(Instruction *Inst);
212 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
213 bool placeDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000214 bool sinkAndCmp(Function &F);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000215 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000216 Instruction *&Inst,
217 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000218 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000219 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000220 bool simplifyOffsetableRelocate(Instruction &I);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +0000221 void stripInvariantGroupMetadata(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000222 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000223}
Devang Patel09f162c2007-05-01 21:15:47 +0000224
Devang Patel8c78a0b2007-05-03 01:11:54 +0000225char CodeGenPrepare::ID = 0;
Dehao Chen302b69c2016-10-18 20:42:47 +0000226INITIALIZE_TM_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
227 "Optimize for code generation", false, false)
228INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
229INITIALIZE_TM_PASS_END(CodeGenPrepare, "codegenprepare",
230 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000231
Bill Wendling7a639ea2013-06-19 21:07:11 +0000232FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
233 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000234}
235
Chris Lattnerf2836d12007-03-31 04:06:36 +0000236bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000237 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000238 return false;
239
Mehdi Amini4fe37982015-07-07 18:45:17 +0000240 DL = &F.getParent()->getDataLayout();
241
Chris Lattnerf2836d12007-03-31 04:06:36 +0000242 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000243 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000244 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000245 PromotedInsts.clear();
Jun Bum Lim82f55c52016-11-21 16:47:28 +0000246 BFI.reset();
247 BPI.reset();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000248
Devang Patel8f606d72011-03-24 15:35:25 +0000249 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000250 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000251 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000252 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000253 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000254 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000255 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000256
Dehao Chen302b69c2016-10-18 20:42:47 +0000257 if (ProfileGuidedSectionPrefix) {
258 ProfileSummaryInfo *PSI =
259 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
260 if (PSI->isFunctionEntryHot(&F))
261 F.setSectionPrefix(".hot");
262 else if (PSI->isFunctionEntryCold(&F))
263 F.setSectionPrefix(".cold");
264 }
265
Preston Gurdcdf540d2012-09-04 18:22:17 +0000266 /// This optimization identifies DIV instructions that can be
267 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000268 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000269 const DenseMap<unsigned int, unsigned int> &BypassWidths =
270 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000271 BasicBlock* BB = &*F.begin();
272 while (BB != nullptr) {
273 // bypassSlowDivision may create new BBs, but we don't want to reapply the
274 // optimization to those blocks.
275 BasicBlock* Next = BB->getNextNode();
276 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
277 BB = Next;
278 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000279 }
280
281 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000282 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000283 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000284
Devang Patel53771ba2011-08-18 00:50:51 +0000285 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000286 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000287 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000288 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000289
Tim Northovercea0abb2014-03-29 08:22:29 +0000290 // If there is a mask, compare against zero, and branch that can be combined
291 // into a single target instruction, push the mask and compare into branch
292 // users. Do this before OptimizeBlock -> OptimizeInst ->
293 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000294 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000295 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000296 EverMadeChange |= splitBranchCondition(F);
297 }
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 Lim82f55c52016-11-21 16:47:28 +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 Lim82f55c52016-11-21 16:47:28 +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 Lim82f55c52016-11-21 16:47:28 +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 if (!BFI) {
505 BPI.reset(new BranchProbabilityInfo(*BB->getParent(), *LI));
506 BFI.reset(new BlockFrequencyInfo(*BB->getParent(), *BPI, *LI));
507 }
508
509 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
510 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
511 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
512
513 // Find all other incoming blocks from which incoming values of all PHIs in
514 // DestBB are the same as the ones from BB.
515 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
516 ++PI) {
517 BasicBlock *DestBBPred = *PI;
518 if (DestBBPred == BB)
519 continue;
520
521 bool HasAllSameValue = true;
522 BasicBlock::const_iterator DestBBI = DestBB->begin();
523 while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) {
524 if (DestPN->getIncomingValueForBlock(BB) !=
525 DestPN->getIncomingValueForBlock(DestBBPred)) {
526 HasAllSameValue = false;
527 break;
528 }
529 }
530 if (HasAllSameValue)
531 SameIncomingValueBBs.insert(DestBBPred);
532 }
533
534 // See if all BB's incoming values are same as the value from Pred. In this
535 // case, no reason to skip merging because COPYs are expected to be place in
536 // Pred already.
537 if (SameIncomingValueBBs.count(Pred))
538 return true;
539
540 for (auto SameValueBB : SameIncomingValueBBs)
541 if (SameValueBB->getUniquePredecessor() == Pred &&
542 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
543 BBFreq += BFI->getBlockFreq(SameValueBB);
544
545 return PredFreq.getFrequency() <=
546 BBFreq.getFrequency() * FreqRatioToSkipMerge;
547}
548
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000549/// Return true if we can merge BB into DestBB if there is a single
550/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000551/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000552bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000553 const BasicBlock *DestBB) const {
554 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
555 // the successor. If there are more complex condition (e.g. preheaders),
556 // don't mess around with them.
557 BasicBlock::const_iterator BBI = BB->begin();
558 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000559 for (const User *U : PN->users()) {
560 const Instruction *UI = cast<Instruction>(U);
561 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000562 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000563 // If User is inside DestBB block and it is a PHINode then check
564 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000565 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000566 if (UI->getParent() == DestBB) {
567 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000568 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
569 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
570 if (Insn && Insn->getParent() == BB &&
571 Insn->getParent() != UPN->getIncomingBlock(I))
572 return false;
573 }
574 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000575 }
576 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000577
Chris Lattnerc3748562007-04-02 01:35:34 +0000578 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
579 // and DestBB may have conflicting incoming values for the block. If so, we
580 // can't merge the block.
581 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
582 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000583
Chris Lattnerc3748562007-04-02 01:35:34 +0000584 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000585 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000586 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
587 // It is faster to get preds from a PHI than with pred_iterator.
588 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
589 BBPreds.insert(BBPN->getIncomingBlock(i));
590 } else {
591 BBPreds.insert(pred_begin(BB), pred_end(BB));
592 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000593
Chris Lattnerc3748562007-04-02 01:35:34 +0000594 // Walk the preds of DestBB.
595 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
596 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
597 if (BBPreds.count(Pred)) { // Common predecessor?
598 BBI = DestBB->begin();
599 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
600 const Value *V1 = PN->getIncomingValueForBlock(Pred);
601 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000602
Chris Lattnerc3748562007-04-02 01:35:34 +0000603 // If V2 is a phi node in BB, look up what the mapped value will be.
604 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
605 if (V2PN->getParent() == BB)
606 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000607
Chris Lattnerc3748562007-04-02 01:35:34 +0000608 // If there is a conflict, bail out.
609 if (V1 != V2) return false;
610 }
611 }
612 }
613
614 return true;
615}
616
617
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000618/// Eliminate a basic block that has only phi's and an unconditional branch in
619/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000620void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000621 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
622 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000623
David Greene74e2d492010-01-05 01:27:11 +0000624 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000625
Chris Lattnerc3748562007-04-02 01:35:34 +0000626 // If the destination block has a single pred, then this is a trivial edge,
627 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000628 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000629 if (SinglePred != DestBB) {
630 // Remember if SinglePred was the entry block of the function. If so, we
631 // will need to move BB back to the entry position.
632 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000633 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000634
Chris Lattner8a172da2008-11-28 19:54:49 +0000635 if (isEntry && BB != &BB->getParent()->getEntryBlock())
636 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000637
David Greene74e2d492010-01-05 01:27:11 +0000638 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000639 return;
640 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000641 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000642
Chris Lattnerc3748562007-04-02 01:35:34 +0000643 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
644 // to handle the new incoming edges it is about to have.
645 PHINode *PN;
646 for (BasicBlock::iterator BBI = DestBB->begin();
647 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
648 // Remove the incoming value for BB, and remember it.
649 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000650
Chris Lattnerc3748562007-04-02 01:35:34 +0000651 // Two options: either the InVal is a phi node defined in BB or it is some
652 // value that dominates BB.
653 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
654 if (InValPhi && InValPhi->getParent() == BB) {
655 // Add all of the input values of the input PHI as inputs of this phi.
656 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
657 PN->addIncoming(InValPhi->getIncomingValue(i),
658 InValPhi->getIncomingBlock(i));
659 } else {
660 // Otherwise, add one instance of the dominating value for each edge that
661 // we will be adding.
662 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
663 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
664 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
665 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000666 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
667 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000668 }
669 }
670 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000671
Chris Lattnerc3748562007-04-02 01:35:34 +0000672 // The PHIs are now updated, change everything that refers to BB to use
673 // DestBB and remove BB.
674 BB->replaceAllUsesWith(DestBB);
675 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000676 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000677
David Greene74e2d492010-01-05 01:27:11 +0000678 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000679}
680
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000681// Computes a map of base pointer relocation instructions to corresponding
682// derived pointer relocation instructions given a vector of all relocate calls
683static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000684 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
685 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
686 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000687 // Collect information in two maps: one primarily for locating the base object
688 // while filling the second map; the second map is the final structure holding
689 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000690 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
691 for (auto *ThisRelocate : AllRelocateCalls) {
692 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
693 ThisRelocate->getDerivedPtrIndex());
694 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000695 }
696 for (auto &Item : RelocateIdxMap) {
697 std::pair<unsigned, unsigned> Key = Item.first;
698 if (Key.first == Key.second)
699 // Base relocation: nothing to insert
700 continue;
701
Manuel Jacob83eefa62016-01-05 04:03:00 +0000702 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000703 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000704
705 // We're iterating over RelocateIdxMap so we cannot modify it.
706 auto MaybeBase = RelocateIdxMap.find(BaseKey);
707 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000708 // TODO: We might want to insert a new base object relocate and gep off
709 // that, if there are enough derived object relocates.
710 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000711
712 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000713 }
714}
715
716// Accepts a GEP and extracts the operands into a vector provided they're all
717// small integer constants
718static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
719 SmallVectorImpl<Value *> &OffsetV) {
720 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
721 // Only accept small constant integer operands
722 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
723 if (!Op || Op->getZExtValue() > 20)
724 return false;
725 }
726
727 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
728 OffsetV.push_back(GEP->getOperand(i));
729 return true;
730}
731
732// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
733// replace, computes a replacement, and affects it.
734static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000735simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
736 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000737 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000738 for (GCRelocateInst *ToReplace : Targets) {
739 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000740 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000741 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000742 // A duplicate relocate call. TODO: coalesce duplicates.
743 continue;
744 }
745
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000746 if (RelocatedBase->getParent() != ToReplace->getParent()) {
747 // Base and derived relocates are in different basic blocks.
748 // In this case transform is only valid when base dominates derived
749 // relocate. However it would be too expensive to check dominance
750 // for each such relocate, so we skip the whole transformation.
751 continue;
752 }
753
Manuel Jacob83eefa62016-01-05 04:03:00 +0000754 Value *Base = ToReplace->getBasePtr();
755 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000756 if (!Derived || Derived->getPointerOperand() != Base)
757 continue;
758
759 SmallVector<Value *, 2> OffsetV;
760 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
761 continue;
762
763 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000764 assert(RelocatedBase->getNextNode() &&
765 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000766
767 // Insert after RelocatedBase
768 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000769 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000770
771 // If gc_relocate does not match the actual type, cast it to the right type.
772 // In theory, there must be a bitcast after gc_relocate if the type does not
773 // match, and we should reuse it to get the derived pointer. But it could be
774 // cases like this:
775 // bb1:
776 // ...
777 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
778 // br label %merge
779 //
780 // bb2:
781 // ...
782 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
783 // br label %merge
784 //
785 // merge:
786 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
787 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
788 //
789 // In this case, we can not find the bitcast any more. So we insert a new bitcast
790 // no matter there is already one or not. In this way, we can handle all cases, and
791 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000792 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000793 if (RelocatedBase->getType() != Base->getType()) {
794 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000795 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000796 }
David Blaikie68d535c2015-03-24 22:38:16 +0000797 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000798 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000799 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000800 // If the newly generated derived pointer's type does not match the original derived
801 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000802 Value *ActualReplacement = Replacement;
803 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000804 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000805 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000806 }
807 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000808 ToReplace->eraseFromParent();
809
810 MadeChange = true;
811 }
812 return MadeChange;
813}
814
815// Turns this:
816//
817// %base = ...
818// %ptr = gep %base + 15
819// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
820// %base' = relocate(%tok, i32 4, i32 4)
821// %ptr' = relocate(%tok, i32 4, i32 5)
822// %val = load %ptr'
823//
824// into this:
825//
826// %base = ...
827// %ptr = gep %base + 15
828// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
829// %base' = gc.relocate(%tok, i32 4, i32 4)
830// %ptr' = gep %base' + 15
831// %val = load %ptr'
832bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
833 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000834 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000835
836 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000837 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000838 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000839 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000840
841 // We need atleast one base pointer relocation + one derived pointer
842 // relocation to mangle
843 if (AllRelocateCalls.size() < 2)
844 return false;
845
846 // RelocateInstMap is a mapping from the base relocate instruction to the
847 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +0000848 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000849 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
850 if (RelocateInstMap.empty())
851 return false;
852
853 for (auto &Item : RelocateInstMap)
854 // Item.first is the RelocatedBase to offset against
855 // Item.second is the vector of Targets to replace
856 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
857 return MadeChange;
858}
859
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000860/// SinkCast - Sink the specified cast instruction into its user blocks
861static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000862 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000863
Chris Lattnerf2836d12007-03-31 04:06:36 +0000864 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000865 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000866
Chris Lattnerf2836d12007-03-31 04:06:36 +0000867 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000868 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000869 UI != E; ) {
870 Use &TheUse = UI.getUse();
871 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000872
Chris Lattnerf2836d12007-03-31 04:06:36 +0000873 // Figure out which BB this cast is used in. For PHI's this is the
874 // appropriate predecessor block.
875 BasicBlock *UserBB = User->getParent();
876 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000877 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000878 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000879
Chris Lattnerf2836d12007-03-31 04:06:36 +0000880 // Preincrement use iterator so we don't invalidate it.
881 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000882
David Majnemer0c80e2e2016-04-27 19:36:38 +0000883 // The first insertion point of a block containing an EH pad is after the
884 // pad. If the pad is the user, we cannot sink the cast past the pad.
885 if (User->isEHPad())
886 continue;
887
Andrew Kaylord0430e82015-11-23 19:16:15 +0000888 // If the block selected to receive the cast is an EH pad that does not
889 // allow non-PHI instructions before the terminator, we can't sink the
890 // cast.
891 if (UserBB->getTerminator()->isEHPad())
892 continue;
893
Chris Lattnerf2836d12007-03-31 04:06:36 +0000894 // If this user is in the same block as the cast, don't change the cast.
895 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000896
Chris Lattnerf2836d12007-03-31 04:06:36 +0000897 // If we have already inserted a cast into this block, use it.
898 CastInst *&InsertedCast = InsertedCasts[UserBB];
899
900 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000901 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000902 assert(InsertPt != UserBB->end());
903 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
904 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000905 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000906
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000907 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000908 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000909 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000910 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000911 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000912
Chris Lattnerf2836d12007-03-31 04:06:36 +0000913 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000914 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000915 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000916 MadeChange = true;
917 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000918
Chris Lattnerf2836d12007-03-31 04:06:36 +0000919 return MadeChange;
920}
921
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000922/// If the specified cast instruction is a noop copy (e.g. it's casting from
923/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
924/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000925///
926/// Return true if any changes are made.
927///
Mehdi Amini44ede332015-07-09 02:09:04 +0000928static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
929 const DataLayout &DL) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000930 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000931 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
932 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000933
934 // This is an fp<->int conversion?
935 if (SrcVT.isInteger() != DstVT.isInteger())
936 return false;
937
938 // If this is an extension, it will be a zero or sign extension, which
939 // isn't a noop.
940 if (SrcVT.bitsLT(DstVT)) return false;
941
942 // If these values will be promoted, find out what they will be promoted
943 // to. This helps us consider truncates on PPC as noop copies when they
944 // are.
945 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
946 TargetLowering::TypePromoteInteger)
947 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
948 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
949 TargetLowering::TypePromoteInteger)
950 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
951
952 // If, after promotion, these are the same types, this is a noop copy.
953 if (SrcVT != DstVT)
954 return false;
955
956 return SinkCast(CI);
957}
958
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000959/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
960/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000961///
962/// Return true if any changes were made.
963static bool CombineUAddWithOverflow(CmpInst *CI) {
964 Value *A, *B;
965 Instruction *AddI;
966 if (!match(CI,
967 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
968 return false;
969
970 Type *Ty = AddI->getType();
971 if (!isa<IntegerType>(Ty))
972 return false;
973
974 // We don't want to move around uses of condition values this late, so we we
975 // check if it is legal to create the call to the intrinsic in the basic
976 // block containing the icmp:
977
978 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
979 return false;
980
981#ifndef NDEBUG
982 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
983 // for now:
984 if (AddI->hasOneUse())
985 assert(*AddI->user_begin() == CI && "expected!");
986#endif
987
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000988 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000989 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
990
991 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
992
993 auto *UAddWithOverflow =
994 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
995 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
996 auto *Overflow =
997 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
998
999 CI->replaceAllUsesWith(Overflow);
1000 AddI->replaceAllUsesWith(UAdd);
1001 CI->eraseFromParent();
1002 AddI->eraseFromParent();
1003 return true;
1004}
1005
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001006/// Sink the given CmpInst into user blocks to reduce the number of virtual
1007/// registers that must be created and coalesced. This is a clear win except on
1008/// targets with multiple condition code registers (PowerPC), where it might
1009/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001010///
1011/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001012static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001013 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001014
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001015 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001016 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001017 return false;
1018
1019 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001020 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001021
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001022 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001023 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001024 UI != E; ) {
1025 Use &TheUse = UI.getUse();
1026 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001027
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001028 // Preincrement use iterator so we don't invalidate it.
1029 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001030
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001031 // Don't bother for PHI nodes.
1032 if (isa<PHINode>(User))
1033 continue;
1034
1035 // Figure out which BB this cmp is used in.
1036 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001037
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001038 // If this user is in the same block as the cmp, don't change the cmp.
1039 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001040
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001041 // If we have already inserted a cmp into this block, use it.
1042 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1043
1044 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001045 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001046 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001047 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001048 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1049 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001050 // Propagate the debug info.
1051 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001052 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001053
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001054 // Replace a use of the cmp with a use of the new cmp.
1055 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001056 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001057 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001058 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001059
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001060 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001061 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001062 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001063 MadeChange = true;
1064 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001065
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001066 return MadeChange;
1067}
1068
Peter Zotovf87e5502016-04-03 17:11:53 +00001069static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001070 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001071 return true;
1072
1073 if (CombineUAddWithOverflow(CI))
1074 return true;
1075
1076 return false;
1077}
1078
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001079/// Check if the candidates could be combined with a shift instruction, which
1080/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001081/// 1. Truncate instruction
1082/// 2. And instruction and the imm is a mask of the low bits:
1083/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001084static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001085 if (!isa<TruncInst>(User)) {
1086 if (User->getOpcode() != Instruction::And ||
1087 !isa<ConstantInt>(User->getOperand(1)))
1088 return false;
1089
Quentin Colombetd4f44692014-04-22 01:20:34 +00001090 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001091
Quentin Colombetd4f44692014-04-22 01:20:34 +00001092 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001093 return false;
1094 }
1095 return true;
1096}
1097
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001098/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001099static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001100SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1101 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001102 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001103 BasicBlock *UserBB = User->getParent();
1104 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1105 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1106 bool MadeChange = false;
1107
1108 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1109 TruncE = TruncI->user_end();
1110 TruncUI != TruncE;) {
1111
1112 Use &TruncTheUse = TruncUI.getUse();
1113 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1114 // Preincrement use iterator so we don't invalidate it.
1115
1116 ++TruncUI;
1117
1118 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1119 if (!ISDOpcode)
1120 continue;
1121
Tim Northovere2239ff2014-07-29 10:20:22 +00001122 // If the use is actually a legal node, there will not be an
1123 // implicit truncate.
1124 // FIXME: always querying the result type is just an
1125 // approximation; some nodes' legality is determined by the
1126 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001127 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001128 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001129 continue;
1130
1131 // Don't bother for PHI nodes.
1132 if (isa<PHINode>(TruncUser))
1133 continue;
1134
1135 BasicBlock *TruncUserBB = TruncUser->getParent();
1136
1137 if (UserBB == TruncUserBB)
1138 continue;
1139
1140 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1141 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1142
1143 if (!InsertedShift && !InsertedTrunc) {
1144 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001145 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001146 // Sink the shift
1147 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001148 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1149 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001150 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001151 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1152 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001153
1154 // Sink the trunc
1155 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1156 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001157 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001158
1159 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001160 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001161
1162 MadeChange = true;
1163
1164 TruncTheUse = InsertedTrunc;
1165 }
1166 }
1167 return MadeChange;
1168}
1169
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001170/// Sink the shift *right* instruction into user blocks if the uses could
1171/// potentially be combined with this shift instruction and generate BitExtract
1172/// instruction. It will only be applied if the architecture supports BitExtract
1173/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001174/// BB1:
1175/// %x.extract.shift = lshr i64 %arg1, 32
1176/// BB2:
1177/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1178/// ==>
1179///
1180/// BB2:
1181/// %x.extract.shift.1 = lshr i64 %arg1, 32
1182/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1183///
1184/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1185/// instruction.
1186/// Return true if any changes are made.
1187static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001188 const TargetLowering &TLI,
1189 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001190 BasicBlock *DefBB = ShiftI->getParent();
1191
1192 /// Only insert instructions in each block once.
1193 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1194
Mehdi Amini44ede332015-07-09 02:09:04 +00001195 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001196
1197 bool MadeChange = false;
1198 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1199 UI != E;) {
1200 Use &TheUse = UI.getUse();
1201 Instruction *User = cast<Instruction>(*UI);
1202 // Preincrement use iterator so we don't invalidate it.
1203 ++UI;
1204
1205 // Don't bother for PHI nodes.
1206 if (isa<PHINode>(User))
1207 continue;
1208
1209 if (!isExtractBitsCandidateUse(User))
1210 continue;
1211
1212 BasicBlock *UserBB = User->getParent();
1213
1214 if (UserBB == DefBB) {
1215 // If the shift and truncate instruction are in the same BB. The use of
1216 // the truncate(TruncUse) may still introduce another truncate if not
1217 // legal. In this case, we would like to sink both shift and truncate
1218 // instruction to the BB of TruncUse.
1219 // for example:
1220 // BB1:
1221 // i64 shift.result = lshr i64 opnd, imm
1222 // trunc.result = trunc shift.result to i16
1223 //
1224 // BB2:
1225 // ----> We will have an implicit truncate here if the architecture does
1226 // not have i16 compare.
1227 // cmp i16 trunc.result, opnd2
1228 //
1229 if (isa<TruncInst>(User) && shiftIsLegal
1230 // If the type of the truncate is legal, no trucate will be
1231 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001232 &&
1233 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001234 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001235 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001236
1237 continue;
1238 }
1239 // If we have already inserted a shift into this block, use it.
1240 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1241
1242 if (!InsertedShift) {
1243 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001244 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001245
1246 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001247 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1248 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001249 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001250 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1251 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001252
1253 MadeChange = true;
1254 }
1255
1256 // Replace a use of the shift with a use of the new shift.
1257 TheUse = InsertedShift;
1258 }
1259
1260 // If we removed all uses, nuke the shift.
1261 if (ShiftI->use_empty())
1262 ShiftI->eraseFromParent();
1263
1264 return MadeChange;
1265}
1266
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001267// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001268// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1269// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001270// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001271// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001272//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001273// %1 = bitcast i8* %addr to i32*
1274// %2 = extractelement <16 x i1> %mask, i32 0
1275// %3 = icmp eq i1 %2, true
1276// br i1 %3, label %cond.load, label %else
1277//
1278//cond.load: ; preds = %0
1279// %4 = getelementptr i32* %1, i32 0
1280// %5 = load i32* %4
1281// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1282// br label %else
1283//
1284//else: ; preds = %0, %cond.load
1285// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1286// %7 = extractelement <16 x i1> %mask, i32 1
1287// %8 = icmp eq i1 %7, true
1288// br i1 %8, label %cond.load1, label %else2
1289//
1290//cond.load1: ; preds = %else
1291// %9 = getelementptr i32* %1, i32 1
1292// %10 = load i32* %9
1293// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1294// br label %else2
1295//
1296//else2: ; preds = %else, %cond.load1
1297// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1298// %12 = extractelement <16 x i1> %mask, i32 2
1299// %13 = icmp eq i1 %12, true
1300// br i1 %13, label %cond.load4, label %else5
1301//
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001302static void scalarizeMaskedLoad(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001303 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001304 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001305 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001306 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001307
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001308 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1309 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001310 assert(VecType && "Unexpected return type of masked load intrinsic");
1311
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001312 Type *EltTy = CI->getType()->getVectorElementType();
1313
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001314 IRBuilder<> Builder(CI->getContext());
1315 Instruction *InsertPt = CI;
1316 BasicBlock *IfBlock = CI->getParent();
1317 BasicBlock *CondBlock = nullptr;
1318 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001319
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001320 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001321 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1322
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001323 // Short-cut if the mask is all-true.
1324 bool IsAllOnesMask = isa<Constant>(Mask) &&
1325 cast<Constant>(Mask)->isAllOnesValue();
1326
1327 if (IsAllOnesMask) {
1328 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1329 CI->replaceAllUsesWith(NewI);
1330 CI->eraseFromParent();
1331 return;
1332 }
1333
1334 // Adjust alignment for the scalar instruction.
1335 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001336 // Bitcast %addr fron i8* to EltTy*
1337 Type *NewPtrType =
1338 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1339 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001340 unsigned VectorWidth = VecType->getNumElements();
1341
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001342 Value *UndefVal = UndefValue::get(VecType);
1343
1344 // The result vector
1345 Value *VResult = UndefVal;
1346
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001347 if (isa<ConstantVector>(Mask)) {
1348 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1349 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1350 continue;
1351 Value *Gep =
1352 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1353 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1354 VResult = Builder.CreateInsertElement(VResult, Load,
1355 Builder.getInt32(Idx));
1356 }
1357 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1358 CI->replaceAllUsesWith(NewI);
1359 CI->eraseFromParent();
1360 return;
1361 }
1362
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001363 PHINode *Phi = nullptr;
1364 Value *PrevPhi = UndefVal;
1365
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001366 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1367
1368 // Fill the "else" block, created in the previous iteration
1369 //
1370 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1371 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1372 // %to_load = icmp eq i1 %mask_1, true
1373 // br i1 %to_load, label %cond.load, label %else
1374 //
1375 if (Idx > 0) {
1376 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1377 Phi->addIncoming(VResult, CondBlock);
1378 Phi->addIncoming(PrevPhi, PrevIfBlock);
1379 PrevPhi = Phi;
1380 VResult = Phi;
1381 }
1382
1383 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1384 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1385 ConstantInt::get(Predicate->getType(), 1));
1386
1387 // Create "cond" block
1388 //
1389 // %EltAddr = getelementptr i32* %1, i32 0
1390 // %Elt = load i32* %EltAddr
1391 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1392 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001393 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001394 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001395
1396 Value *Gep =
1397 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001398 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001399 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1400
1401 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001402 BasicBlock *NewIfBlock =
1403 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001404 Builder.SetInsertPoint(InsertPt);
1405 Instruction *OldBr = IfBlock->getTerminator();
1406 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1407 OldBr->eraseFromParent();
1408 PrevIfBlock = IfBlock;
1409 IfBlock = NewIfBlock;
1410 }
1411
1412 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1413 Phi->addIncoming(VResult, CondBlock);
1414 Phi->addIncoming(PrevPhi, PrevIfBlock);
1415 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1416 CI->replaceAllUsesWith(NewI);
1417 CI->eraseFromParent();
1418}
1419
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001420// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001421// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1422// <16 x i1> %mask)
1423// to a chain of basic blocks, that stores element one-by-one if
1424// the appropriate mask bit is set
1425//
1426// %1 = bitcast i8* %addr to i32*
1427// %2 = extractelement <16 x i1> %mask, i32 0
1428// %3 = icmp eq i1 %2, true
1429// br i1 %3, label %cond.store, label %else
1430//
1431// cond.store: ; preds = %0
1432// %4 = extractelement <16 x i32> %val, i32 0
1433// %5 = getelementptr i32* %1, i32 0
1434// store i32 %4, i32* %5
1435// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001436//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001437// else: ; preds = %0, %cond.store
1438// %6 = extractelement <16 x i1> %mask, i32 1
1439// %7 = icmp eq i1 %6, true
1440// br i1 %7, label %cond.store1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001441//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001442// cond.store1: ; preds = %else
1443// %8 = extractelement <16 x i32> %val, i32 1
1444// %9 = getelementptr i32* %1, i32 1
1445// store i32 %8, i32* %9
1446// br label %else2
1447// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001448static void scalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001449 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001450 Value *Ptr = CI->getArgOperand(1);
1451 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001452 Value *Mask = CI->getArgOperand(3);
1453
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001454 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001455 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001456 assert(VecType && "Unexpected data type in masked store intrinsic");
1457
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001458 Type *EltTy = VecType->getElementType();
1459
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001460 IRBuilder<> Builder(CI->getContext());
1461 Instruction *InsertPt = CI;
1462 BasicBlock *IfBlock = CI->getParent();
1463 Builder.SetInsertPoint(InsertPt);
1464 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1465
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001466 // Short-cut if the mask is all-true.
1467 bool IsAllOnesMask = isa<Constant>(Mask) &&
1468 cast<Constant>(Mask)->isAllOnesValue();
1469
1470 if (IsAllOnesMask) {
1471 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1472 CI->eraseFromParent();
1473 return;
1474 }
1475
1476 // Adjust alignment for the scalar instruction.
1477 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001478 // Bitcast %addr fron i8* to EltTy*
1479 Type *NewPtrType =
1480 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1481 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001482 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001483
1484 if (isa<ConstantVector>(Mask)) {
1485 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1486 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1487 continue;
1488 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1489 Value *Gep =
1490 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1491 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1492 }
1493 CI->eraseFromParent();
1494 return;
1495 }
1496
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001497 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1498
1499 // Fill the "else" block, created in the previous iteration
1500 //
1501 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1502 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001503 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001504 //
1505 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1506 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1507 ConstantInt::get(Predicate->getType(), 1));
1508
1509 // Create "cond" block
1510 //
1511 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1512 // %EltAddr = getelementptr i32* %1, i32 0
1513 // %store i32 %OneElt, i32* %EltAddr
1514 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001515 BasicBlock *CondBlock =
1516 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001517 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001518
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001519 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001520 Value *Gep =
1521 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001522 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001523
1524 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001525 BasicBlock *NewIfBlock =
1526 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001527 Builder.SetInsertPoint(InsertPt);
1528 Instruction *OldBr = IfBlock->getTerminator();
1529 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1530 OldBr->eraseFromParent();
1531 IfBlock = NewIfBlock;
1532 }
1533 CI->eraseFromParent();
1534}
1535
Elena Demikhovsky09285852015-10-25 15:37:55 +00001536// Translate a masked gather intrinsic like
1537// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1538// <16 x i1> %Mask, <16 x i32> %Src)
1539// to a chain of basic blocks, with loading element one-by-one if
1540// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001541//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001542// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1543// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1544// % ToLoad0 = icmp eq i1 % Mask0, true
1545// br i1 % ToLoad0, label %cond.load, label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001546//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001547// cond.load:
1548// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1549// % Load0 = load i32, i32* % Ptr0, align 4
1550// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1551// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001552//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001553// else:
1554// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1555// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1556// % ToLoad1 = icmp eq i1 % Mask1, true
1557// br i1 % ToLoad1, label %cond.load1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001558//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001559// cond.load1:
1560// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1561// % Load1 = load i32, i32* % Ptr1, align 4
1562// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1563// br label %else2
1564// . . .
1565// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1566// ret <16 x i32> %Result
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001567static void scalarizeMaskedGather(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001568 Value *Ptrs = CI->getArgOperand(0);
1569 Value *Alignment = CI->getArgOperand(1);
1570 Value *Mask = CI->getArgOperand(2);
1571 Value *Src0 = CI->getArgOperand(3);
1572
1573 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1574
1575 assert(VecType && "Unexpected return type of masked load intrinsic");
1576
1577 IRBuilder<> Builder(CI->getContext());
1578 Instruction *InsertPt = CI;
1579 BasicBlock *IfBlock = CI->getParent();
1580 BasicBlock *CondBlock = nullptr;
1581 BasicBlock *PrevIfBlock = CI->getParent();
1582 Builder.SetInsertPoint(InsertPt);
1583 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1584
1585 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1586
1587 Value *UndefVal = UndefValue::get(VecType);
1588
1589 // The result vector
1590 Value *VResult = UndefVal;
1591 unsigned VectorWidth = VecType->getNumElements();
1592
1593 // Shorten the way if the mask is a vector of constants.
1594 bool IsConstMask = isa<ConstantVector>(Mask);
1595
1596 if (IsConstMask) {
1597 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1598 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1599 continue;
1600 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1601 "Ptr" + Twine(Idx));
1602 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1603 "Load" + Twine(Idx));
1604 VResult = Builder.CreateInsertElement(VResult, Load,
1605 Builder.getInt32(Idx),
1606 "Res" + Twine(Idx));
1607 }
1608 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1609 CI->replaceAllUsesWith(NewI);
1610 CI->eraseFromParent();
1611 return;
1612 }
1613
1614 PHINode *Phi = nullptr;
1615 Value *PrevPhi = UndefVal;
1616
1617 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1618
1619 // Fill the "else" block, created in the previous iteration
1620 //
1621 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1622 // %ToLoad1 = icmp eq i1 %Mask1, true
1623 // br i1 %ToLoad1, label %cond.load, label %else
1624 //
1625 if (Idx > 0) {
1626 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1627 Phi->addIncoming(VResult, CondBlock);
1628 Phi->addIncoming(PrevPhi, PrevIfBlock);
1629 PrevPhi = Phi;
1630 VResult = Phi;
1631 }
1632
1633 Value *Predicate = Builder.CreateExtractElement(Mask,
1634 Builder.getInt32(Idx),
1635 "Mask" + Twine(Idx));
1636 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1637 ConstantInt::get(Predicate->getType(), 1),
1638 "ToLoad" + Twine(Idx));
1639
1640 // Create "cond" block
1641 //
1642 // %EltAddr = getelementptr i32* %1, i32 0
1643 // %Elt = load i32* %EltAddr
1644 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1645 //
1646 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1647 Builder.SetInsertPoint(InsertPt);
1648
1649 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1650 "Ptr" + Twine(Idx));
1651 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1652 "Load" + Twine(Idx));
1653 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1654 "Res" + Twine(Idx));
1655
1656 // Create "else" block, fill it in the next iteration
1657 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1658 Builder.SetInsertPoint(InsertPt);
1659 Instruction *OldBr = IfBlock->getTerminator();
1660 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1661 OldBr->eraseFromParent();
1662 PrevIfBlock = IfBlock;
1663 IfBlock = NewIfBlock;
1664 }
1665
1666 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1667 Phi->addIncoming(VResult, CondBlock);
1668 Phi->addIncoming(PrevPhi, PrevIfBlock);
1669 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1670 CI->replaceAllUsesWith(NewI);
1671 CI->eraseFromParent();
1672}
1673
1674// Translate a masked scatter intrinsic, like
1675// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1676// <16 x i1> %Mask)
1677// to a chain of basic blocks, that stores element one-by-one if
1678// the appropriate mask bit is set.
1679//
1680// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1681// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1682// % ToStore0 = icmp eq i1 % Mask0, true
1683// br i1 %ToStore0, label %cond.store, label %else
1684//
1685// cond.store:
1686// % Elt0 = extractelement <16 x i32> %Src, i32 0
1687// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1688// store i32 %Elt0, i32* % Ptr0, align 4
1689// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001690//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001691// else:
1692// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1693// % ToStore1 = icmp eq i1 % Mask1, true
1694// br i1 % ToStore1, label %cond.store1, label %else2
1695//
1696// cond.store1:
1697// % Elt1 = extractelement <16 x i32> %Src, i32 1
1698// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1699// store i32 % Elt1, i32* % Ptr1, align 4
1700// br label %else2
1701// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001702static void scalarizeMaskedScatter(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001703 Value *Src = CI->getArgOperand(0);
1704 Value *Ptrs = CI->getArgOperand(1);
1705 Value *Alignment = CI->getArgOperand(2);
1706 Value *Mask = CI->getArgOperand(3);
1707
1708 assert(isa<VectorType>(Src->getType()) &&
1709 "Unexpected data type in masked scatter intrinsic");
1710 assert(isa<VectorType>(Ptrs->getType()) &&
1711 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1712 "Vector of pointers is expected in masked scatter intrinsic");
1713
1714 IRBuilder<> Builder(CI->getContext());
1715 Instruction *InsertPt = CI;
1716 BasicBlock *IfBlock = CI->getParent();
1717 Builder.SetInsertPoint(InsertPt);
1718 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1719
1720 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1721 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1722
1723 // Shorten the way if the mask is a vector of constants.
1724 bool IsConstMask = isa<ConstantVector>(Mask);
1725
1726 if (IsConstMask) {
1727 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1728 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1729 continue;
1730 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1731 "Elt" + Twine(Idx));
1732 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1733 "Ptr" + Twine(Idx));
1734 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1735 }
1736 CI->eraseFromParent();
1737 return;
1738 }
1739 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1740 // Fill the "else" block, created in the previous iteration
1741 //
1742 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1743 // % ToStore = icmp eq i1 % Mask1, true
1744 // br i1 % ToStore, label %cond.store, label %else
1745 //
1746 Value *Predicate = Builder.CreateExtractElement(Mask,
1747 Builder.getInt32(Idx),
1748 "Mask" + Twine(Idx));
1749 Value *Cmp =
1750 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1751 ConstantInt::get(Predicate->getType(), 1),
1752 "ToStore" + Twine(Idx));
1753
1754 // Create "cond" block
1755 //
1756 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1757 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1758 // %store i32 % Elt1, i32* % Ptr1
1759 //
1760 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1761 Builder.SetInsertPoint(InsertPt);
1762
1763 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1764 "Elt" + Twine(Idx));
1765 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1766 "Ptr" + Twine(Idx));
1767 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1768
1769 // Create "else" block, fill it in the next iteration
1770 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1771 Builder.SetInsertPoint(InsertPt);
1772 Instruction *OldBr = IfBlock->getTerminator();
1773 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1774 OldBr->eraseFromParent();
1775 IfBlock = NewIfBlock;
1776 }
1777 CI->eraseFromParent();
1778}
1779
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001780/// If counting leading or trailing zeros is an expensive operation and a zero
1781/// input is defined, add a check for zero to avoid calling the intrinsic.
1782///
1783/// We want to transform:
1784/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1785///
1786/// into:
1787/// entry:
1788/// %cmpz = icmp eq i64 %A, 0
1789/// br i1 %cmpz, label %cond.end, label %cond.false
1790/// cond.false:
1791/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1792/// br label %cond.end
1793/// cond.end:
1794/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1795///
1796/// If the transform is performed, return true and set ModifiedDT to true.
1797static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1798 const TargetLowering *TLI,
1799 const DataLayout *DL,
1800 bool &ModifiedDT) {
1801 if (!TLI || !DL)
1802 return false;
1803
1804 // If a zero input is undefined, it doesn't make sense to despeculate that.
1805 if (match(CountZeros->getOperand(1), m_One()))
1806 return false;
1807
1808 // If it's cheap to speculate, there's nothing to do.
1809 auto IntrinsicID = CountZeros->getIntrinsicID();
1810 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1811 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1812 return false;
1813
1814 // Only handle legal scalar cases. Anything else requires too much work.
1815 Type *Ty = CountZeros->getType();
1816 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001817 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001818 return false;
1819
1820 // The intrinsic will be sunk behind a compare against zero and branch.
1821 BasicBlock *StartBlock = CountZeros->getParent();
1822 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1823
1824 // Create another block after the count zero intrinsic. A PHI will be added
1825 // in this block to select the result of the intrinsic or the bit-width
1826 // constant if the input to the intrinsic is zero.
1827 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1828 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1829
1830 // Set up a builder to create a compare, conditional branch, and PHI.
1831 IRBuilder<> Builder(CountZeros->getContext());
1832 Builder.SetInsertPoint(StartBlock->getTerminator());
1833 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1834
1835 // Replace the unconditional branch that was created by the first split with
1836 // a compare against zero and a conditional branch.
1837 Value *Zero = Constant::getNullValue(Ty);
1838 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1839 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1840 StartBlock->getTerminator()->eraseFromParent();
1841
1842 // Create a PHI in the end block to select either the output of the intrinsic
1843 // or the bit width of the operand.
1844 Builder.SetInsertPoint(&EndBlock->front());
1845 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1846 CountZeros->replaceAllUsesWith(PN);
1847 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1848 PN->addIncoming(BitWidth, StartBlock);
1849 PN->addIncoming(CountZeros, CallBlock);
1850
1851 // We are explicitly handling the zero case, so we can set the intrinsic's
1852 // undefined zero argument to 'true'. This will also prevent reprocessing the
1853 // intrinsic; we only despeculate when a zero input is defined.
1854 CountZeros->setArgOperand(1, Builder.getTrue());
1855 ModifiedDT = true;
1856 return true;
1857}
1858
Sanjay Patelfc580a62015-09-21 23:03:16 +00001859bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001860 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001861
Chris Lattner7a277142011-01-15 07:14:54 +00001862 // Lower inline assembly if we can.
1863 // If we found an inline asm expession, and if the target knows how to
1864 // lower it to normal LLVM code, do so now.
1865 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1866 if (TLI->ExpandInlineAsm(CI)) {
1867 // Avoid invalidating the iterator.
1868 CurInstIterator = BB->begin();
1869 // Avoid processing instructions out of order, which could cause
1870 // reuse before a value is defined.
1871 SunkAddrs.clear();
1872 return true;
1873 }
1874 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001875 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001876 return true;
1877 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001878
John Brawn0dbcd652015-03-18 12:01:59 +00001879 // Align the pointer arguments to this call if the target thinks it's a good
1880 // idea
1881 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001882 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001883 for (auto &Arg : CI->arg_operands()) {
1884 // We want to align both objects whose address is used directly and
1885 // objects whose address is used in casts and GEPs, though it only makes
1886 // sense for GEPs if the offset is a multiple of the desired alignment and
1887 // if size - offset meets the size threshold.
1888 if (!Arg->getType()->isPointerTy())
1889 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001890 APInt Offset(DL->getPointerSizeInBits(
1891 cast<PointerType>(Arg->getType())->getAddressSpace()),
1892 0);
1893 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001894 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001895 if ((Offset2 & (PrefAlign-1)) != 0)
1896 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001897 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001898 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1899 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001900 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001901 // Global variables can only be aligned if they are defined in this
1902 // object (i.e. they are uniquely initialized in this object), and
1903 // over-aligning global variables that have an explicit section is
1904 // forbidden.
1905 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001906 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001907 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001908 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001909 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001910 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001911 }
1912 // If this is a memcpy (or similar) then we may be able to improve the
1913 // alignment
1914 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001915 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001916 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001917 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001918 if (Align > MI->getAlignment())
1919 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001920 }
1921 }
1922
Philip Reamesac115ed2016-03-09 23:13:12 +00001923 // If we have a cold call site, try to sink addressing computation into the
1924 // cold block. This interacts with our handling for loads and stores to
1925 // ensure that we can fold all uses of a potential addressing computation
1926 // into their uses. TODO: generalize this to work over profiling data
1927 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1928 for (auto &Arg : CI->arg_operands()) {
1929 if (!Arg->getType()->isPointerTy())
1930 continue;
1931 unsigned AS = Arg->getType()->getPointerAddressSpace();
1932 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1933 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001934
Eric Christopher4b7948e2010-03-11 02:41:03 +00001935 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001936 if (II) {
1937 switch (II->getIntrinsicID()) {
1938 default: break;
1939 case Intrinsic::objectsize: {
1940 // Lower all uses of llvm.objectsize.*
Petar Jovanovic644b8c12016-04-13 12:25:25 +00001941 uint64_t Size;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001942 Type *ReturnTy = CI->getType();
Petar Jovanovic644b8c12016-04-13 12:25:25 +00001943 Constant *RetVal = nullptr;
1944 ConstantInt *Op1 = cast<ConstantInt>(II->getArgOperand(1));
1945 ObjSizeMode Mode = Op1->isZero() ? ObjSizeMode::Max : ObjSizeMode::Min;
1946 if (getObjectSize(II->getArgOperand(0),
1947 Size, *DL, TLInfo, false, Mode)) {
1948 RetVal = ConstantInt::get(ReturnTy, Size);
1949 } else {
1950 RetVal = ConstantInt::get(ReturnTy,
1951 Mode == ObjSizeMode::Min ? 0 : -1ULL);
1952 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001953 // Substituting this can cause recursive simplifications, which can
1954 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1955 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001956 Value *CurValue = &*CurInstIterator;
1957 WeakVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001958
Sanjay Patel545a4562016-01-20 18:59:16 +00001959 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001960
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001961 // If the iterator instruction was recursively deleted, start over at the
1962 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001963 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001964 CurInstIterator = BB->begin();
1965 SunkAddrs.clear();
1966 }
1967 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001968 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001969 case Intrinsic::masked_load: {
1970 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001971 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001972 scalarizeMaskedLoad(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001973 ModifiedDT = true;
1974 return true;
1975 }
1976 return false;
1977 }
1978 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001979 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001980 scalarizeMaskedStore(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001981 ModifiedDT = true;
1982 return true;
1983 }
1984 return false;
1985 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00001986 case Intrinsic::masked_gather: {
1987 if (!TTI->isLegalMaskedGather(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001988 scalarizeMaskedGather(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001989 ModifiedDT = true;
1990 return true;
1991 }
1992 return false;
1993 }
1994 case Intrinsic::masked_scatter: {
1995 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001996 scalarizeMaskedScatter(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001997 ModifiedDT = true;
1998 return true;
1999 }
2000 return false;
2001 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002002 case Intrinsic::aarch64_stlxr:
2003 case Intrinsic::aarch64_stxr: {
2004 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2005 if (!ExtVal || !ExtVal->hasOneUse() ||
2006 ExtVal->getParent() == CI->getParent())
2007 return false;
2008 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2009 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002010 // Mark this instruction as "inserted by CGP", so that other
2011 // optimizations don't touch it.
2012 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002013 return true;
2014 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00002015 case Intrinsic::invariant_group_barrier:
2016 II->replaceAllUsesWith(II->getArgOperand(0));
2017 II->eraseFromParent();
2018 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00002019
2020 case Intrinsic::cttz:
2021 case Intrinsic::ctlz:
2022 // If counting zeros is expensive, try to avoid it.
2023 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002024 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00002025
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002026 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002027 // Unknown address space.
2028 // TODO: Target hook to pick which address space the intrinsic cares
2029 // about?
2030 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002031 SmallVector<Value*, 2> PtrOps;
2032 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002033 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002034 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00002035 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002036 return true;
2037 }
Pete Cooper615fd892012-03-13 20:59:56 +00002038 }
2039
Eric Christopher4b7948e2010-03-11 02:41:03 +00002040 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00002041 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00002042
Benjamin Kramer7b88a492010-03-12 09:27:41 +00002043 // Lower all default uses of _chk calls. This is very similar
2044 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002045 // to fortified library functions (e.g. __memcpy_chk) that have the default
2046 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002047 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002048 if (Value *V = Simplifier.optimizeCall(CI)) {
2049 CI->replaceAllUsesWith(V);
2050 CI->eraseFromParent();
2051 return true;
2052 }
2053 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00002054}
Chris Lattner1b93be52011-01-15 07:25:29 +00002055
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002056/// Look for opportunities to duplicate return instructions to the predecessor
2057/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002058/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002059/// bb0:
2060/// %tmp0 = tail call i32 @f0()
2061/// br label %return
2062/// bb1:
2063/// %tmp1 = tail call i32 @f1()
2064/// br label %return
2065/// bb2:
2066/// %tmp2 = tail call i32 @f2()
2067/// br label %return
2068/// return:
2069/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2070/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002071/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00002072///
2073/// =>
2074///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002075/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002076/// bb0:
2077/// %tmp0 = tail call i32 @f0()
2078/// ret i32 %tmp0
2079/// bb1:
2080/// %tmp1 = tail call i32 @f1()
2081/// ret i32 %tmp1
2082/// bb2:
2083/// %tmp2 = tail call i32 @f2()
2084/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002085/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00002086bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00002087 if (!TLI)
2088 return false;
2089
Michael Kuperstein71321562016-09-07 20:29:49 +00002090 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2091 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00002092 return false;
2093
Craig Topperc0196b12014-04-14 00:51:57 +00002094 PHINode *PN = nullptr;
2095 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00002096 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00002097 if (V) {
2098 BCI = dyn_cast<BitCastInst>(V);
2099 if (BCI)
2100 V = BCI->getOperand(0);
2101
2102 PN = dyn_cast<PHINode>(V);
2103 if (!PN)
2104 return false;
2105 }
Evan Cheng0663f232011-03-21 01:19:09 +00002106
Cameron Zwarich4649f172011-03-24 04:52:10 +00002107 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002108 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00002109
Cameron Zwarich4649f172011-03-24 04:52:10 +00002110 // Make sure there are no instructions between the PHI and return, or that the
2111 // return is the first instruction in the block.
2112 if (PN) {
2113 BasicBlock::iterator BI = BB->begin();
2114 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00002115 if (&*BI == BCI)
2116 // Also skip over the bitcast.
2117 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002118 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002119 return false;
2120 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002121 BasicBlock::iterator BI = BB->begin();
2122 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002123 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002124 return false;
2125 }
Evan Cheng0663f232011-03-21 01:19:09 +00002126
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002127 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2128 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002129 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002130 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00002131 if (PN) {
2132 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2133 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2134 // Make sure the phi value is indeed produced by the tail call.
2135 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002136 TLI->mayBeEmittedAsTailCall(CI) &&
2137 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002138 TailCalls.push_back(CI);
2139 }
2140 } else {
2141 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002142 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002143 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002144 continue;
2145
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002146 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002147 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2148 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002149 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2150 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002151 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002152
Cameron Zwarich4649f172011-03-24 04:52:10 +00002153 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002154 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2155 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002156 TailCalls.push_back(CI);
2157 }
Evan Cheng0663f232011-03-21 01:19:09 +00002158 }
2159
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002160 bool Changed = false;
2161 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2162 CallInst *CI = TailCalls[i];
2163 CallSite CS(CI);
2164
2165 // Conservatively require the attributes of the call to match those of the
2166 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00002167 AttributeSet CalleeAttrs = CS.getAttributes();
2168 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002169 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00002170 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002171 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002172 continue;
2173
2174 // Make sure the call instruction is followed by an unconditional branch to
2175 // the return block.
2176 BasicBlock *CallBB = CI->getParent();
2177 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2178 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2179 continue;
2180
2181 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002182 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002183 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002184 ++NumRetsDup;
2185 }
2186
2187 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002188 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002189 BB->eraseFromParent();
2190
2191 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002192}
2193
Chris Lattner728f9022008-11-25 07:09:13 +00002194//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002195// Memory Optimization
2196//===----------------------------------------------------------------------===//
2197
Chandler Carruthc8925912013-01-05 02:09:22 +00002198namespace {
2199
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002200/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002201/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002202struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002203 Value *BaseReg;
2204 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002205 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002206 void print(raw_ostream &OS) const;
2207 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002208
Chandler Carruthc8925912013-01-05 02:09:22 +00002209 bool operator==(const ExtAddrMode& O) const {
2210 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2211 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2212 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2213 }
2214};
2215
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002216#ifndef NDEBUG
2217static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2218 AM.print(OS);
2219 return OS;
2220}
2221#endif
2222
Chandler Carruthc8925912013-01-05 02:09:22 +00002223void ExtAddrMode::print(raw_ostream &OS) const {
2224 bool NeedPlus = false;
2225 OS << "[";
2226 if (BaseGV) {
2227 OS << (NeedPlus ? " + " : "")
2228 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002229 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002230 NeedPlus = true;
2231 }
2232
Richard Trieuc0f91212014-05-30 03:15:17 +00002233 if (BaseOffs) {
2234 OS << (NeedPlus ? " + " : "")
2235 << BaseOffs;
2236 NeedPlus = true;
2237 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002238
2239 if (BaseReg) {
2240 OS << (NeedPlus ? " + " : "")
2241 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002242 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002243 NeedPlus = true;
2244 }
2245 if (Scale) {
2246 OS << (NeedPlus ? " + " : "")
2247 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002248 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002249 }
2250
2251 OS << ']';
2252}
2253
2254#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002255LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002256 print(dbgs());
2257 dbgs() << '\n';
2258}
2259#endif
2260
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002261/// \brief This class provides transaction based operation on the IR.
2262/// Every change made through this class is recorded in the internal state and
2263/// can be undone (rollback) until commit is called.
2264class TypePromotionTransaction {
2265
2266 /// \brief This represents the common interface of the individual transaction.
2267 /// Each class implements the logic for doing one specific modification on
2268 /// the IR via the TypePromotionTransaction.
2269 class TypePromotionAction {
2270 protected:
2271 /// The Instruction modified.
2272 Instruction *Inst;
2273
2274 public:
2275 /// \brief Constructor of the action.
2276 /// The constructor performs the related action on the IR.
2277 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2278
2279 virtual ~TypePromotionAction() {}
2280
2281 /// \brief Undo the modification done by this action.
2282 /// When this method is called, the IR must be in the same state as it was
2283 /// before this action was applied.
2284 /// \pre Undoing the action works if and only if the IR is in the exact same
2285 /// state as it was directly after this action was applied.
2286 virtual void undo() = 0;
2287
2288 /// \brief Advocate every change made by this action.
2289 /// When the results on the IR of the action are to be kept, it is important
2290 /// to call this function, otherwise hidden information may be kept forever.
2291 virtual void commit() {
2292 // Nothing to be done, this action is not doing anything.
2293 }
2294 };
2295
2296 /// \brief Utility to remember the position of an instruction.
2297 class InsertionHandler {
2298 /// Position of an instruction.
2299 /// Either an instruction:
2300 /// - Is the first in a basic block: BB is used.
2301 /// - Has a previous instructon: PrevInst is used.
2302 union {
2303 Instruction *PrevInst;
2304 BasicBlock *BB;
2305 } Point;
2306 /// Remember whether or not the instruction had a previous instruction.
2307 bool HasPrevInstruction;
2308
2309 public:
2310 /// \brief Record the position of \p Inst.
2311 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002312 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002313 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2314 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002315 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002316 else
2317 Point.BB = Inst->getParent();
2318 }
2319
2320 /// \brief Insert \p Inst at the recorded position.
2321 void insert(Instruction *Inst) {
2322 if (HasPrevInstruction) {
2323 if (Inst->getParent())
2324 Inst->removeFromParent();
2325 Inst->insertAfter(Point.PrevInst);
2326 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002327 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002328 if (Inst->getParent())
2329 Inst->moveBefore(Position);
2330 else
2331 Inst->insertBefore(Position);
2332 }
2333 }
2334 };
2335
2336 /// \brief Move an instruction before another.
2337 class InstructionMoveBefore : public TypePromotionAction {
2338 /// Original position of the instruction.
2339 InsertionHandler Position;
2340
2341 public:
2342 /// \brief Move \p Inst before \p Before.
2343 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2344 : TypePromotionAction(Inst), Position(Inst) {
2345 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2346 Inst->moveBefore(Before);
2347 }
2348
2349 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002350 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002351 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2352 Position.insert(Inst);
2353 }
2354 };
2355
2356 /// \brief Set the operand of an instruction with a new value.
2357 class OperandSetter : public TypePromotionAction {
2358 /// Original operand of the instruction.
2359 Value *Origin;
2360 /// Index of the modified instruction.
2361 unsigned Idx;
2362
2363 public:
2364 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2365 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2366 : TypePromotionAction(Inst), Idx(Idx) {
2367 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2368 << "for:" << *Inst << "\n"
2369 << "with:" << *NewVal << "\n");
2370 Origin = Inst->getOperand(Idx);
2371 Inst->setOperand(Idx, NewVal);
2372 }
2373
2374 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002375 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002376 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2377 << "for: " << *Inst << "\n"
2378 << "with: " << *Origin << "\n");
2379 Inst->setOperand(Idx, Origin);
2380 }
2381 };
2382
2383 /// \brief Hide the operands of an instruction.
2384 /// Do as if this instruction was not using any of its operands.
2385 class OperandsHider : public TypePromotionAction {
2386 /// The list of original operands.
2387 SmallVector<Value *, 4> OriginalValues;
2388
2389 public:
2390 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2391 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2392 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2393 unsigned NumOpnds = Inst->getNumOperands();
2394 OriginalValues.reserve(NumOpnds);
2395 for (unsigned It = 0; It < NumOpnds; ++It) {
2396 // Save the current operand.
2397 Value *Val = Inst->getOperand(It);
2398 OriginalValues.push_back(Val);
2399 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002400 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002401 // that we are not willing to pay.
2402 Inst->setOperand(It, UndefValue::get(Val->getType()));
2403 }
2404 }
2405
2406 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002407 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002408 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2409 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2410 Inst->setOperand(It, OriginalValues[It]);
2411 }
2412 };
2413
2414 /// \brief Build a truncate instruction.
2415 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002416 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002417 public:
2418 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2419 /// result.
2420 /// trunc Opnd to Ty.
2421 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2422 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002423 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2424 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002425 }
2426
Quentin Colombetac55b152014-09-16 22:36:07 +00002427 /// \brief Get the built value.
2428 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002429
2430 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002431 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002432 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2433 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2434 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002435 }
2436 };
2437
2438 /// \brief Build a sign extension instruction.
2439 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002440 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002441 public:
2442 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2443 /// result.
2444 /// sext Opnd to Ty.
2445 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002446 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002447 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002448 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2449 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002450 }
2451
Quentin Colombetac55b152014-09-16 22:36:07 +00002452 /// \brief Get the built value.
2453 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002454
2455 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002456 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002457 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2458 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2459 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002460 }
2461 };
2462
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002463 /// \brief Build a zero extension instruction.
2464 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002465 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002466 public:
2467 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2468 /// result.
2469 /// zext Opnd to Ty.
2470 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002471 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002472 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002473 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2474 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002475 }
2476
Quentin Colombetac55b152014-09-16 22:36:07 +00002477 /// \brief Get the built value.
2478 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002479
2480 /// \brief Remove the built instruction.
2481 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002482 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2483 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2484 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002485 }
2486 };
2487
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002488 /// \brief Mutate an instruction to another type.
2489 class TypeMutator : public TypePromotionAction {
2490 /// Record the original type.
2491 Type *OrigTy;
2492
2493 public:
2494 /// \brief Mutate the type of \p Inst into \p NewTy.
2495 TypeMutator(Instruction *Inst, Type *NewTy)
2496 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2497 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2498 << "\n");
2499 Inst->mutateType(NewTy);
2500 }
2501
2502 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002503 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002504 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2505 << "\n");
2506 Inst->mutateType(OrigTy);
2507 }
2508 };
2509
2510 /// \brief Replace the uses of an instruction by another instruction.
2511 class UsesReplacer : public TypePromotionAction {
2512 /// Helper structure to keep track of the replaced uses.
2513 struct InstructionAndIdx {
2514 /// The instruction using the instruction.
2515 Instruction *Inst;
2516 /// The index where this instruction is used for Inst.
2517 unsigned Idx;
2518 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2519 : Inst(Inst), Idx(Idx) {}
2520 };
2521
2522 /// Keep track of the original uses (pair Instruction, Index).
2523 SmallVector<InstructionAndIdx, 4> OriginalUses;
2524 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2525
2526 public:
2527 /// \brief Replace all the use of \p Inst by \p New.
2528 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2529 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2530 << "\n");
2531 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002532 for (Use &U : Inst->uses()) {
2533 Instruction *UserI = cast<Instruction>(U.getUser());
2534 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002535 }
2536 // Now, we can replace the uses.
2537 Inst->replaceAllUsesWith(New);
2538 }
2539
2540 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002541 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002542 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2543 for (use_iterator UseIt = OriginalUses.begin(),
2544 EndIt = OriginalUses.end();
2545 UseIt != EndIt; ++UseIt) {
2546 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2547 }
2548 }
2549 };
2550
2551 /// \brief Remove an instruction from the IR.
2552 class InstructionRemover : public TypePromotionAction {
2553 /// Original position of the instruction.
2554 InsertionHandler Inserter;
2555 /// Helper structure to hide all the link to the instruction. In other
2556 /// words, this helps to do as if the instruction was removed.
2557 OperandsHider Hider;
2558 /// Keep track of the uses replaced, if any.
2559 UsesReplacer *Replacer;
2560
2561 public:
2562 /// \brief Remove all reference of \p Inst and optinally replace all its
2563 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002564 /// \pre If !Inst->use_empty(), then New != nullptr
2565 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002566 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002567 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002568 if (New)
2569 Replacer = new UsesReplacer(Inst, New);
2570 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2571 Inst->removeFromParent();
2572 }
2573
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002574 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002575
2576 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002577 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002578
2579 /// \brief Resurrect the instruction and reassign it to the proper uses if
2580 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002581 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002582 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2583 Inserter.insert(Inst);
2584 if (Replacer)
2585 Replacer->undo();
2586 Hider.undo();
2587 }
2588 };
2589
2590public:
2591 /// Restoration point.
2592 /// The restoration point is a pointer to an action instead of an iterator
2593 /// because the iterator may be invalidated but not the pointer.
2594 typedef const TypePromotionAction *ConstRestorationPt;
2595 /// Advocate every changes made in that transaction.
2596 void commit();
2597 /// Undo all the changes made after the given point.
2598 void rollback(ConstRestorationPt Point);
2599 /// Get the current restoration point.
2600 ConstRestorationPt getRestorationPoint() const;
2601
2602 /// \name API for IR modification with state keeping to support rollback.
2603 /// @{
2604 /// Same as Instruction::setOperand.
2605 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2606 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002607 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002608 /// Same as Value::replaceAllUsesWith.
2609 void replaceAllUsesWith(Instruction *Inst, Value *New);
2610 /// Same as Value::mutateType.
2611 void mutateType(Instruction *Inst, Type *NewTy);
2612 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002613 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002614 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002615 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002616 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002617 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002618 /// Same as Instruction::moveBefore.
2619 void moveBefore(Instruction *Inst, Instruction *Before);
2620 /// @}
2621
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002622private:
2623 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002624 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2625 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002626};
2627
2628void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2629 Value *NewVal) {
2630 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002631 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002632}
2633
2634void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2635 Value *NewVal) {
2636 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002637 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002638}
2639
2640void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2641 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002642 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002643}
2644
2645void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002646 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002647}
2648
Quentin Colombetac55b152014-09-16 22:36:07 +00002649Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2650 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002651 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002652 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002653 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002654 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002655}
2656
Quentin Colombetac55b152014-09-16 22:36:07 +00002657Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2658 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002659 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002660 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002661 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002662 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002663}
2664
Quentin Colombetac55b152014-09-16 22:36:07 +00002665Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2666 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002667 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002668 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002669 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002670 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002671}
2672
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002673void TypePromotionTransaction::moveBefore(Instruction *Inst,
2674 Instruction *Before) {
2675 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002676 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002677}
2678
2679TypePromotionTransaction::ConstRestorationPt
2680TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002681 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002682}
2683
2684void TypePromotionTransaction::commit() {
2685 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002686 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002687 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002688 Actions.clear();
2689}
2690
2691void TypePromotionTransaction::rollback(
2692 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002693 while (!Actions.empty() && Point != Actions.back().get()) {
2694 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002695 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002696 }
2697}
2698
Chandler Carruthc8925912013-01-05 02:09:22 +00002699/// \brief A helper class for matching addressing modes.
2700///
2701/// This encapsulates the logic for matching the target-legal addressing modes.
2702class AddressingModeMatcher {
2703 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002704 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002705 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002706 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002707
2708 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2709 /// the memory instruction that we're computing this address for.
2710 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002711 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002712 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002713
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002714 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002715 /// part of the return value of this addressing mode matching stuff.
2716 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002717
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002718 /// The instructions inserted by other CodeGenPrepare optimizations.
2719 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002720 /// A map from the instructions to their type before promotion.
2721 InstrToOrigTy &PromotedInsts;
2722 /// The ongoing transaction where every action should be registered.
2723 TypePromotionTransaction &TPT;
2724
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002725 /// This is set to true when we should not do profitability checks.
2726 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002727 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002728
Eric Christopherd75c00c2015-02-26 22:38:34 +00002729 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002730 const TargetMachine &TM, Type *AT, unsigned AS,
2731 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002732 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002733 InstrToOrigTy &PromotedInsts,
2734 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002735 : AddrModeInsts(AMI), TM(TM),
2736 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2737 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002738 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2739 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2740 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002741 IgnoreProfitability = false;
2742 }
2743public:
Stephen Lin837bba12013-07-15 17:55:02 +00002744
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002745 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002746 /// give an access type of AccessTy. This returns a list of involved
2747 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002748 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002749 /// optimizations.
2750 /// \p PromotedInsts maps the instructions to their type before promotion.
2751 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002752 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002753 Instruction *MemoryInst,
2754 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002755 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002756 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002757 InstrToOrigTy &PromotedInsts,
2758 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002759 ExtAddrMode Result;
2760
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002761 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002762 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002763 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002764 (void)Success; assert(Success && "Couldn't select *anything*?");
2765 return Result;
2766 }
2767private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002768 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2769 bool matchAddr(Value *V, unsigned Depth);
2770 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002771 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002772 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002773 ExtAddrMode &AMBefore,
2774 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002775 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2776 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002777 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002778};
2779
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002780/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002781/// Return true and update AddrMode if this addr mode is legal for the target,
2782/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002783bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002784 unsigned Depth) {
2785 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2786 // mode. Just process that directly.
2787 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002788 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002789
Chandler Carruthc8925912013-01-05 02:09:22 +00002790 // If the scale is 0, it takes nothing to add this.
2791 if (Scale == 0)
2792 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002793
Chandler Carruthc8925912013-01-05 02:09:22 +00002794 // If we already have a scale of this value, we can add to it, otherwise, we
2795 // need an available scale field.
2796 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2797 return false;
2798
2799 ExtAddrMode TestAddrMode = AddrMode;
2800
2801 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2802 // [A+B + A*7] -> [B+A*8].
2803 TestAddrMode.Scale += Scale;
2804 TestAddrMode.ScaledReg = ScaleReg;
2805
2806 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002807 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002808 return false;
2809
2810 // It was legal, so commit it.
2811 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002812
Chandler Carruthc8925912013-01-05 02:09:22 +00002813 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2814 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2815 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002816 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002817 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2818 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2819 TestAddrMode.ScaledReg = AddLHS;
2820 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002821
Chandler Carruthc8925912013-01-05 02:09:22 +00002822 // If this addressing mode is legal, commit it and remember that we folded
2823 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002824 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002825 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2826 AddrMode = TestAddrMode;
2827 return true;
2828 }
2829 }
2830
2831 // Otherwise, not (x+c)*scale, just return what we have.
2832 return true;
2833}
2834
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002835/// This is a little filter, which returns true if an addressing computation
2836/// involving I might be folded into a load/store accessing it.
2837/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002838/// the set of instructions that MatchOperationAddr can.
2839static bool MightBeFoldableInst(Instruction *I) {
2840 switch (I->getOpcode()) {
2841 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002842 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002843 // Don't touch identity bitcasts.
2844 if (I->getType() == I->getOperand(0)->getType())
2845 return false;
2846 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2847 case Instruction::PtrToInt:
2848 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2849 return true;
2850 case Instruction::IntToPtr:
2851 // We know the input is intptr_t, so this is foldable.
2852 return true;
2853 case Instruction::Add:
2854 return true;
2855 case Instruction::Mul:
2856 case Instruction::Shl:
2857 // Can only handle X*C and X << C.
2858 return isa<ConstantInt>(I->getOperand(1));
2859 case Instruction::GetElementPtr:
2860 return true;
2861 default:
2862 return false;
2863 }
2864}
2865
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002866/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2867/// \note \p Val is assumed to be the product of some type promotion.
2868/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2869/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002870static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2871 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002872 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2873 if (!PromotedInst)
2874 return false;
2875 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2876 // If the ISDOpcode is undefined, it was undefined before the promotion.
2877 if (!ISDOpcode)
2878 return true;
2879 // Otherwise, check if the promoted instruction is legal or not.
2880 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002881 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002882}
2883
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002884/// \brief Hepler class to perform type promotion.
2885class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002886 /// \brief Utility function to check whether or not a sign or zero extension
2887 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2888 /// either using the operands of \p Inst or promoting \p Inst.
2889 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002890 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002891 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002892 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002893 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002894 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002895 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002896 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002897 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2898 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002899
2900 /// \brief Utility function to determine if \p OpIdx should be promoted when
2901 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002902 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00002903 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002904 }
2905
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002906 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002907 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002908 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002909 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002910 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002911 /// Newly added extensions are inserted in \p Exts.
2912 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002913 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002914 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002915 static Value *promoteOperandForTruncAndAnyExt(
2916 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002917 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002918 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002919 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002920
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002921 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002922 /// operand is promotable and is not a supported trunc or sext.
2923 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002924 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002925 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002926 /// Newly added extensions are inserted in \p Exts.
2927 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002928 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002929 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002930 static Value *promoteOperandForOther(Instruction *Ext,
2931 TypePromotionTransaction &TPT,
2932 InstrToOrigTy &PromotedInsts,
2933 unsigned &CreatedInstsCost,
2934 SmallVectorImpl<Instruction *> *Exts,
2935 SmallVectorImpl<Instruction *> *Truncs,
2936 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002937
2938 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002939 static Value *signExtendOperandForOther(
2940 Instruction *Ext, TypePromotionTransaction &TPT,
2941 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2942 SmallVectorImpl<Instruction *> *Exts,
2943 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2944 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2945 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002946 }
2947
2948 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002949 static Value *zeroExtendOperandForOther(
2950 Instruction *Ext, TypePromotionTransaction &TPT,
2951 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2952 SmallVectorImpl<Instruction *> *Exts,
2953 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2954 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2955 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002956 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002957
2958public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002959 /// Type for the utility function that promotes the operand of Ext.
2960 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002961 InstrToOrigTy &PromotedInsts,
2962 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002963 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002964 SmallVectorImpl<Instruction *> *Truncs,
2965 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002966 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2967 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002968 /// \return NULL if no promotable action is possible with the current
2969 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002970 /// \p InsertedInsts keeps track of all the instructions inserted by the
2971 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002972 /// because we do not want to promote these instructions as CodeGenPrepare
2973 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2974 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002975 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002976 const TargetLowering &TLI,
2977 const InstrToOrigTy &PromotedInsts);
2978};
2979
2980bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002981 Type *ConsideredExtType,
2982 const InstrToOrigTy &PromotedInsts,
2983 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002984 // The promotion helper does not know how to deal with vector types yet.
2985 // To be able to fix that, we would need to fix the places where we
2986 // statically extend, e.g., constants and such.
2987 if (Inst->getType()->isVectorTy())
2988 return false;
2989
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002990 // We can always get through zext.
2991 if (isa<ZExtInst>(Inst))
2992 return true;
2993
2994 // sext(sext) is ok too.
2995 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002996 return true;
2997
2998 // We can get through binary operator, if it is legal. In other words, the
2999 // binary operator must have a nuw or nsw flag.
3000 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3001 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003002 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3003 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003004 return true;
3005
3006 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003007 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003008 if (!isa<TruncInst>(Inst))
3009 return false;
3010
3011 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003012 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003013 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003014 if (!OpndVal->getType()->isIntegerTy() ||
3015 OpndVal->getType()->getIntegerBitWidth() >
3016 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003017 return false;
3018
3019 // If the operand of the truncate is not an instruction, we will not have
3020 // any information on the dropped bits.
3021 // (Actually we could for constant but it is not worth the extra logic).
3022 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3023 if (!Opnd)
3024 return false;
3025
3026 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003027 // I.e., check that trunc just drops extended bits of the same kind of
3028 // the extension.
3029 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003030 const Type *OpndType;
3031 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003032 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3033 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003034 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3035 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003036 else
3037 return false;
3038
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003039 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003040 return Inst->getType()->getIntegerBitWidth() >=
3041 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003042}
3043
3044TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003045 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003046 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003047 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3048 "Unexpected instruction type");
3049 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3050 Type *ExtTy = Ext->getType();
3051 bool IsSExt = isa<SExtInst>(Ext);
3052 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003053 // get through.
3054 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003055 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003056 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003057
3058 // Do not promote if the operand has been added by codegenprepare.
3059 // Otherwise, it means we are undoing an optimization that is likely to be
3060 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003061 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003062 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003063
3064 // SExt or Trunc instructions.
3065 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003066 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3067 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003068 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003069
3070 // Regular instruction.
3071 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003072 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003073 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003074 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003075}
3076
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003077Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003078 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003079 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003080 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003081 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003082 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3083 // get through it and this method should not be called.
3084 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003085 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003086 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003087 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003088 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003089 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003090 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003091 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003092 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3093 TPT.replaceAllUsesWith(SExt, ZExt);
3094 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003095 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003096 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003097 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3098 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003099 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3100 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003101 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003102
3103 // Remove dead code.
3104 if (SExtOpnd->use_empty())
3105 TPT.eraseInstruction(SExtOpnd);
3106
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003107 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003108 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003109 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003110 if (ExtInst) {
3111 if (Exts)
3112 Exts->push_back(ExtInst);
3113 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3114 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003115 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003116 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003117
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003118 // At this point we have: ext ty opnd to ty.
3119 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3120 Value *NextVal = ExtInst->getOperand(0);
3121 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003122 return NextVal;
3123}
3124
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003125Value *TypePromotionHelper::promoteOperandForOther(
3126 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003127 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003128 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003129 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3130 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003131 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003132 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003133 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003134 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003135 if (!ExtOpnd->hasOneUse()) {
3136 // ExtOpnd will be promoted.
3137 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003138 // promoted version.
3139 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003140 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003141 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3142 ITrunc->removeFromParent();
3143 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003144 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003145 if (Truncs)
3146 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003147 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003148
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003149 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003150 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003151 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003152 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003153 }
3154
3155 // Get through the Instruction:
3156 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003157 // 2. Replace the uses of Ext by Inst.
3158 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003159
3160 // Remember the original type of the instruction before promotion.
3161 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003162 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3163 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003164 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003165 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003166 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003167 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003168 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003169 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003170
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003171 DEBUG(dbgs() << "Propagate Ext to operands\n");
3172 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003173 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003174 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3175 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3176 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003177 DEBUG(dbgs() << "No need to propagate\n");
3178 continue;
3179 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003180 // Check if we can statically extend the operand.
3181 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003182 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003183 DEBUG(dbgs() << "Statically extend\n");
3184 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3185 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3186 : Cst->getValue().zext(BitWidth);
3187 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003188 continue;
3189 }
3190 // UndefValue are typed, so we have to statically sign extend them.
3191 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003192 DEBUG(dbgs() << "Statically extend\n");
3193 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003194 continue;
3195 }
3196
3197 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003198 // Check if Ext was reused to extend an operand.
3199 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003200 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003201 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003202 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3203 : TPT.createZExt(Ext, Opnd, Ext->getType());
3204 if (!isa<Instruction>(ValForExtOpnd)) {
3205 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3206 continue;
3207 }
3208 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003209 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003210 if (Exts)
3211 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003212 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003213
3214 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003215 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3216 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003217 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003218 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003219 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003220 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003221 if (ExtForOpnd == Ext) {
3222 DEBUG(dbgs() << "Extension is useless now\n");
3223 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003224 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003225 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003226}
3227
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003228/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003229/// \p NewCost gives the cost of extension instructions created by the
3230/// promotion.
3231/// \p OldCost gives the cost of extension instructions before the promotion
3232/// plus the number of instructions that have been
3233/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003234/// \p PromotedOperand is the value that has been promoted.
3235/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003236bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003237 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3238 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3239 // The cost of the new extensions is greater than the cost of the
3240 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003241 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003242 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003243 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003244 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003245 return true;
3246 // The promotion is neutral but it may help folding the sign extension in
3247 // loads for instance.
3248 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003249 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003250}
3251
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003252/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003253/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003254/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003255/// If \p MovedAway is not NULL, it contains the information of whether or
3256/// not AddrInst has to be folded into the addressing mode on success.
3257/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3258/// because it has been moved away.
3259/// Thus AddrInst must not be added in the matched instructions.
3260/// This state can happen when AddrInst is a sext, since it may be moved away.
3261/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3262/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003263bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003264 unsigned Depth,
3265 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003266 // Avoid exponential behavior on extremely deep expression trees.
3267 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003268
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003269 // By default, all matched instructions stay in place.
3270 if (MovedAway)
3271 *MovedAway = false;
3272
Chandler Carruthc8925912013-01-05 02:09:22 +00003273 switch (Opcode) {
3274 case Instruction::PtrToInt:
3275 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003276 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003277 case Instruction::IntToPtr: {
3278 auto AS = AddrInst->getType()->getPointerAddressSpace();
3279 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003280 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003281 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003282 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003283 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003284 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003285 case Instruction::BitCast:
3286 // BitCast is always a noop, and we can handle it as long as it is
3287 // int->int or pointer->pointer (we don't want int<->fp or something).
3288 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3289 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3290 // Don't touch identity bitcasts. These were probably put here by LSR,
3291 // and we don't want to mess around with them. Assume it knows what it
3292 // is doing.
3293 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003294 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003295 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003296 case Instruction::AddrSpaceCast: {
3297 unsigned SrcAS
3298 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3299 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3300 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003301 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003302 return false;
3303 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003304 case Instruction::Add: {
3305 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3306 ExtAddrMode BackupAddrMode = AddrMode;
3307 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003308 // Start a transaction at this point.
3309 // The LHS may match but not the RHS.
3310 // Therefore, we need a higher level restoration point to undo partially
3311 // matched operation.
3312 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3313 TPT.getRestorationPoint();
3314
Sanjay Patelfc580a62015-09-21 23:03:16 +00003315 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3316 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003317 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003318
Chandler Carruthc8925912013-01-05 02:09:22 +00003319 // Restore the old addr mode info.
3320 AddrMode = BackupAddrMode;
3321 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003322 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003323
Chandler Carruthc8925912013-01-05 02:09:22 +00003324 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003325 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3326 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003327 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003328
Chandler Carruthc8925912013-01-05 02:09:22 +00003329 // Otherwise we definitely can't merge the ADD in.
3330 AddrMode = BackupAddrMode;
3331 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003332 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003333 break;
3334 }
3335 //case Instruction::Or:
3336 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3337 //break;
3338 case Instruction::Mul:
3339 case Instruction::Shl: {
3340 // Can only handle X*C and X << C.
3341 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003342 if (!RHS)
3343 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003344 int64_t Scale = RHS->getSExtValue();
3345 if (Opcode == Instruction::Shl)
3346 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003347
Sanjay Patelfc580a62015-09-21 23:03:16 +00003348 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003349 }
3350 case Instruction::GetElementPtr: {
3351 // Scan the GEP. We check it if it contains constant offsets and at most
3352 // one variable offset.
3353 int VariableOperand = -1;
3354 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003355
Chandler Carruthc8925912013-01-05 02:09:22 +00003356 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003357 gep_type_iterator GTI = gep_type_begin(AddrInst);
3358 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3359 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003360 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003361 unsigned Idx =
3362 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3363 ConstantOffset += SL->getElementOffset(Idx);
3364 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003365 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003366 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3367 ConstantOffset += CI->getSExtValue()*TypeSize;
3368 } else if (TypeSize) { // Scales of zero don't do anything.
3369 // We only allow one variable index at the moment.
3370 if (VariableOperand != -1)
3371 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003372
Chandler Carruthc8925912013-01-05 02:09:22 +00003373 // Remember the variable index.
3374 VariableOperand = i;
3375 VariableScale = TypeSize;
3376 }
3377 }
3378 }
Stephen Lin837bba12013-07-15 17:55:02 +00003379
Chandler Carruthc8925912013-01-05 02:09:22 +00003380 // A common case is for the GEP to only do a constant offset. In this case,
3381 // just add it to the disp field and check validity.
3382 if (VariableOperand == -1) {
3383 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003384 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003385 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003386 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003387 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003388 return true;
3389 }
3390 AddrMode.BaseOffs -= ConstantOffset;
3391 return false;
3392 }
3393
3394 // Save the valid addressing mode in case we can't match.
3395 ExtAddrMode BackupAddrMode = AddrMode;
3396 unsigned OldSize = AddrModeInsts.size();
3397
3398 // See if the scale and offset amount is valid for this target.
3399 AddrMode.BaseOffs += ConstantOffset;
3400
3401 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003402 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003403 // If it couldn't be matched, just stuff the value in a register.
3404 if (AddrMode.HasBaseReg) {
3405 AddrMode = BackupAddrMode;
3406 AddrModeInsts.resize(OldSize);
3407 return false;
3408 }
3409 AddrMode.HasBaseReg = true;
3410 AddrMode.BaseReg = AddrInst->getOperand(0);
3411 }
3412
3413 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003414 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003415 Depth)) {
3416 // If it couldn't be matched, try stuffing the base into a register
3417 // instead of matching it, and retrying the match of the scale.
3418 AddrMode = BackupAddrMode;
3419 AddrModeInsts.resize(OldSize);
3420 if (AddrMode.HasBaseReg)
3421 return false;
3422 AddrMode.HasBaseReg = true;
3423 AddrMode.BaseReg = AddrInst->getOperand(0);
3424 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003425 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003426 VariableScale, Depth)) {
3427 // If even that didn't work, bail.
3428 AddrMode = BackupAddrMode;
3429 AddrModeInsts.resize(OldSize);
3430 return false;
3431 }
3432 }
3433
3434 return true;
3435 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003436 case Instruction::SExt:
3437 case Instruction::ZExt: {
3438 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3439 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003440 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003441
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003442 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003443 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003444 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003445 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003446 if (!TPH)
3447 return false;
3448
3449 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3450 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003451 unsigned CreatedInstsCost = 0;
3452 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003453 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003454 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003455 // SExt has been moved away.
3456 // Thus either it will be rematched later in the recursive calls or it is
3457 // gone. Anyway, we must not fold it into the addressing mode at this point.
3458 // E.g.,
3459 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003460 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003461 // addr = gep base, idx
3462 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003463 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003464 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3465 // addr = gep base, op <- match
3466 if (MovedAway)
3467 *MovedAway = true;
3468
3469 assert(PromotedOperand &&
3470 "TypePromotionHelper should have filtered out those cases");
3471
3472 ExtAddrMode BackupAddrMode = AddrMode;
3473 unsigned OldSize = AddrModeInsts.size();
3474
Sanjay Patelfc580a62015-09-21 23:03:16 +00003475 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003476 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003477 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003478 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003479 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003480 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003481 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003482 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003483 AddrMode = BackupAddrMode;
3484 AddrModeInsts.resize(OldSize);
3485 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3486 TPT.rollback(LastKnownGood);
3487 return false;
3488 }
3489 return true;
3490 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003491 }
3492 return false;
3493}
3494
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003495/// If we can, try to add the value of 'Addr' into the current addressing mode.
3496/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3497/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3498/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003499///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003500bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003501 // Start a transaction at this point that we will rollback if the matching
3502 // fails.
3503 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3504 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003505 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3506 // Fold in immediates if legal for the target.
3507 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003508 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003509 return true;
3510 AddrMode.BaseOffs -= CI->getSExtValue();
3511 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3512 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003513 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003514 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003515 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003516 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003517 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003518 }
3519 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3520 ExtAddrMode BackupAddrMode = AddrMode;
3521 unsigned OldSize = AddrModeInsts.size();
3522
3523 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003524 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003525 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003526 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003527 // to check here.
3528 if (MovedAway)
3529 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003530 // Okay, it's possible to fold this. Check to see if it is actually
3531 // *profitable* to do so. We use a simple cost model to avoid increasing
3532 // register pressure too much.
3533 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003534 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003535 AddrModeInsts.push_back(I);
3536 return true;
3537 }
Stephen Lin837bba12013-07-15 17:55:02 +00003538
Chandler Carruthc8925912013-01-05 02:09:22 +00003539 // It isn't profitable to do this, roll back.
3540 //cerr << "NOT FOLDING: " << *I;
3541 AddrMode = BackupAddrMode;
3542 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003543 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003544 }
3545 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003546 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003547 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003548 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003549 } else if (isa<ConstantPointerNull>(Addr)) {
3550 // Null pointer gets folded without affecting the addressing mode.
3551 return true;
3552 }
3553
3554 // Worse case, the target should support [reg] addressing modes. :)
3555 if (!AddrMode.HasBaseReg) {
3556 AddrMode.HasBaseReg = true;
3557 AddrMode.BaseReg = Addr;
3558 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003559 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003560 return true;
3561 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003562 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003563 }
3564
3565 // If the base register is already taken, see if we can do [r+r].
3566 if (AddrMode.Scale == 0) {
3567 AddrMode.Scale = 1;
3568 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003569 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003570 return true;
3571 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003572 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003573 }
3574 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003575 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003576 return false;
3577}
3578
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003579/// Check to see if all uses of OpVal by the specified inline asm call are due
3580/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003581static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00003582 const TargetMachine &TM) {
3583 const Function *F = CI->getParent()->getParent();
3584 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
3585 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003586 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003587 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
3588 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00003589 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3590 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003591
Chandler Carruthc8925912013-01-05 02:09:22 +00003592 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003593 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003594
3595 // If this asm operand is our Value*, and if it isn't an indirect memory
3596 // operand, we can't fold it!
3597 if (OpInfo.CallOperandVal == OpVal &&
3598 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3599 !OpInfo.isIndirect))
3600 return false;
3601 }
3602
3603 return true;
3604}
3605
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003606/// Recursively walk all the uses of I until we find a memory use.
3607/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003608/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003609static bool FindAllMemoryUses(
3610 Instruction *I,
3611 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3612 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003613 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003614 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003615 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003616
Chandler Carruthc8925912013-01-05 02:09:22 +00003617 // If this is an obviously unfoldable instruction, bail out.
3618 if (!MightBeFoldableInst(I))
3619 return true;
3620
Philip Reamesac115ed2016-03-09 23:13:12 +00003621 const bool OptSize = I->getFunction()->optForSize();
3622
Chandler Carruthc8925912013-01-05 02:09:22 +00003623 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003624 for (Use &U : I->uses()) {
3625 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003626
Chandler Carruthcdf47882014-03-09 03:16:01 +00003627 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3628 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003629 continue;
3630 }
Stephen Lin837bba12013-07-15 17:55:02 +00003631
Chandler Carruthcdf47882014-03-09 03:16:01 +00003632 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3633 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003634 if (opNo == 0) return true; // Storing addr, not into addr.
3635 MemoryUses.push_back(std::make_pair(SI, opNo));
3636 continue;
3637 }
Stephen Lin837bba12013-07-15 17:55:02 +00003638
Chandler Carruthcdf47882014-03-09 03:16:01 +00003639 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00003640 // If this is a cold call, we can sink the addressing calculation into
3641 // the cold path. See optimizeCallInst
3642 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3643 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00003644
Chandler Carruthc8925912013-01-05 02:09:22 +00003645 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3646 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003647
Chandler Carruthc8925912013-01-05 02:09:22 +00003648 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003649 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003650 return true;
3651 continue;
3652 }
Stephen Lin837bba12013-07-15 17:55:02 +00003653
Eric Christopher11e4df72015-02-26 22:38:43 +00003654 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003655 return true;
3656 }
3657
3658 return false;
3659}
3660
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003661/// Return true if Val is already known to be live at the use site that we're
3662/// folding it into. If so, there is no cost to include it in the addressing
3663/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3664/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003665bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003666 Value *KnownLive2) {
3667 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003668 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003669 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003670
Chandler Carruthc8925912013-01-05 02:09:22 +00003671 // All values other than instructions and arguments (e.g. constants) are live.
3672 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003673
Chandler Carruthc8925912013-01-05 02:09:22 +00003674 // If Val is a constant sized alloca in the entry block, it is live, this is
3675 // true because it is just a reference to the stack/frame pointer, which is
3676 // live for the whole function.
3677 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3678 if (AI->isStaticAlloca())
3679 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003680
Chandler Carruthc8925912013-01-05 02:09:22 +00003681 // Check to see if this value is already used in the memory instruction's
3682 // block. If so, it's already live into the block at the very least, so we
3683 // can reasonably fold it.
3684 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3685}
3686
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003687/// It is possible for the addressing mode of the machine to fold the specified
3688/// instruction into a load or store that ultimately uses it.
3689/// However, the specified instruction has multiple uses.
3690/// Given this, it may actually increase register pressure to fold it
3691/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003692///
3693/// X = ...
3694/// Y = X+1
3695/// use(Y) -> nonload/store
3696/// Z = Y+1
3697/// load Z
3698///
3699/// In this case, Y has multiple uses, and can be folded into the load of Z
3700/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3701/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3702/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3703/// number of computations either.
3704///
3705/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3706/// X was live across 'load Z' for other reasons, we actually *would* want to
3707/// fold the addressing mode in the Z case. This would make Y die earlier.
3708bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003709isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003710 ExtAddrMode &AMAfter) {
3711 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003712
Chandler Carruthc8925912013-01-05 02:09:22 +00003713 // AMBefore is the addressing mode before this instruction was folded into it,
3714 // and AMAfter is the addressing mode after the instruction was folded. Get
3715 // the set of registers referenced by AMAfter and subtract out those
3716 // referenced by AMBefore: this is the set of values which folding in this
3717 // address extends the lifetime of.
3718 //
3719 // Note that there are only two potential values being referenced here,
3720 // BaseReg and ScaleReg (global addresses are always available, as are any
3721 // folded immediates).
3722 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003723
Chandler Carruthc8925912013-01-05 02:09:22 +00003724 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3725 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003726 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003727 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003728 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003729 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003730
3731 // If folding this instruction (and it's subexprs) didn't extend any live
3732 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003733 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003734 return true;
3735
Philip Reamesac115ed2016-03-09 23:13:12 +00003736 // If all uses of this instruction can have the address mode sunk into them,
3737 // we can remove the addressing mode and effectively trade one live register
3738 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00003739 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00003740 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3741 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003742 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003743 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003744
Chandler Carruthc8925912013-01-05 02:09:22 +00003745 // Now that we know that all uses of this instruction are part of a chain of
3746 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00003747 // into a memory use, loop over each of these memory operation uses and see
3748 // if they could *actually* fold the instruction. The assumption is that
3749 // addressing modes are cheap and that duplicating the computation involved
3750 // many times is worthwhile, even on a fastpath. For sinking candidates
3751 // (i.e. cold call sites), this serves as a way to prevent excessive code
3752 // growth since most architectures have some reasonable small and fast way to
3753 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00003754 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3755 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3756 Instruction *User = MemoryUses[i].first;
3757 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003758
Chandler Carruthc8925912013-01-05 02:09:22 +00003759 // Get the access type of this use. If the use isn't a pointer, we don't
3760 // know what it accesses.
3761 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003762 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3763 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003764 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003765 Type *AddressAccessTy = AddrTy->getElementType();
3766 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003767
Chandler Carruthc8925912013-01-05 02:09:22 +00003768 // Do a match against the root of this address, ignoring profitability. This
3769 // will tell us if the addressing mode for the memory operation will
3770 // *actually* cover the shared instruction.
3771 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003772 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3773 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003774 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003775 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003776 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003777 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003778 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003779 (void)Success; assert(Success && "Couldn't select *anything*?");
3780
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003781 // The match was to check the profitability, the changes made are not
3782 // part of the original matcher. Therefore, they should be dropped
3783 // otherwise the original matcher will not present the right state.
3784 TPT.rollback(LastKnownGood);
3785
Chandler Carruthc8925912013-01-05 02:09:22 +00003786 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00003787 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00003788 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003789
Chandler Carruthc8925912013-01-05 02:09:22 +00003790 MatchedAddrModeInsts.clear();
3791 }
Stephen Lin837bba12013-07-15 17:55:02 +00003792
Chandler Carruthc8925912013-01-05 02:09:22 +00003793 return true;
3794}
3795
3796} // end anonymous namespace
3797
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003798/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003799/// different basic block than BB.
3800static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3801 if (Instruction *I = dyn_cast<Instruction>(V))
3802 return I->getParent() != BB;
3803 return false;
3804}
3805
Philip Reamesac115ed2016-03-09 23:13:12 +00003806/// Sink addressing mode computation immediate before MemoryInst if doing so
3807/// can be done without increasing register pressure. The need for the
3808/// register pressure constraint means this can end up being an all or nothing
3809/// decision for all uses of the same addressing computation.
3810///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003811/// Load and Store Instructions often have addressing modes that can do
3812/// significant amounts of computation. As such, instruction selection will try
3813/// to get the load or store to do as much computation as possible for the
3814/// program. The problem is that isel can only see within a single block. As
3815/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003816///
3817/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00003818/// operands. It's also used to sink addressing computations feeding into cold
3819/// call sites into their (cold) basic block.
3820///
3821/// The motivation for handling sinking into cold blocks is that doing so can
3822/// both enable other address mode sinking (by satisfying the register pressure
3823/// constraint above), and reduce register pressure globally (by removing the
3824/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00003825bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003826 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003827 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003828
3829 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003830 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003831 SmallVector<Value*, 8> worklist;
3832 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003833 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003834
Owen Anderson8ba5f392010-11-27 08:15:55 +00003835 // Use a worklist to iteratively look through PHI nodes, and ensure that
3836 // the addressing mode obtained from the non-PHI roots of the graph
3837 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003838 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003839 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003840 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003841 SmallVector<Instruction*, 16> AddrModeInsts;
3842 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003843 TypePromotionTransaction TPT;
3844 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3845 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003846 while (!worklist.empty()) {
3847 Value *V = worklist.back();
3848 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003849
Owen Anderson8ba5f392010-11-27 08:15:55 +00003850 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003851 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003852 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003853 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003854 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003855
Owen Anderson8ba5f392010-11-27 08:15:55 +00003856 // For a PHI node, push all of its incoming values.
3857 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003858 for (Value *IncValue : P->incoming_values())
3859 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003860 continue;
3861 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003862
Philip Reamesac115ed2016-03-09 23:13:12 +00003863 // For non-PHIs, determine the addressing mode being computed. Note that
3864 // the result may differ depending on what other uses our candidate
3865 // addressing instructions might have.
Owen Anderson8ba5f392010-11-27 08:15:55 +00003866 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003867 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003868 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003869 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003870
3871 // This check is broken into two cases with very similar code to avoid using
3872 // getNumUses() as much as possible. Some values have a lot of uses, so
3873 // calling getNumUses() unconditionally caused a significant compile-time
3874 // regression.
3875 if (!Consensus) {
3876 Consensus = V;
3877 AddrMode = NewAddrMode;
3878 AddrModeInsts = NewAddrModeInsts;
3879 continue;
3880 } else if (NewAddrMode == AddrMode) {
3881 if (!IsNumUsesConsensusValid) {
3882 NumUsesConsensus = Consensus->getNumUses();
3883 IsNumUsesConsensusValid = true;
3884 }
3885
3886 // Ensure that the obtained addressing mode is equivalent to that obtained
3887 // for all other roots of the PHI traversal. Also, when choosing one
3888 // such root as representative, select the one with the most uses in order
3889 // to keep the cost modeling heuristics in AddressingModeMatcher
3890 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003891 unsigned NumUses = V->getNumUses();
3892 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003893 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003894 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003895 AddrModeInsts = NewAddrModeInsts;
3896 }
3897 continue;
3898 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003899
Craig Topperc0196b12014-04-14 00:51:57 +00003900 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003901 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003902 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003903
Owen Anderson8ba5f392010-11-27 08:15:55 +00003904 // If the addressing mode couldn't be determined, or if multiple different
3905 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003906 if (!Consensus) {
3907 TPT.rollback(LastKnownGood);
3908 return false;
3909 }
3910 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003911
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003912 // Check to see if any of the instructions supersumed by this addr mode are
3913 // non-local to I's BB.
3914 bool AnyNonLocal = false;
3915 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003916 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003917 AnyNonLocal = true;
3918 break;
3919 }
3920 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003921
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003922 // If all the instructions matched are already in this BB, don't do anything.
3923 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003924 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003925 return false;
3926 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003927
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003928 // Insert this computation right after this user. Since our caller is
3929 // scanning from the top of the BB to the bottom, reuse of the expr are
3930 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003931 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003932
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003933 // Now that we determined the addressing expression we want to use and know
3934 // that we have to sink it into this block. Check to see if we have already
3935 // done this for some other load/store instr in this block. If so, reuse the
3936 // computation.
3937 Value *&SunkAddr = SunkAddrs[Addr];
3938 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003939 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003940 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003941 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003942 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003943 } else if (AddrSinkUsingGEPs ||
3944 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003945 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3946 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003947 // By default, we use the GEP-based method when AA is used later. This
3948 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3949 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003950 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003951 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003952 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003953
3954 // First, find the pointer.
3955 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3956 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003957 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003958 }
3959
3960 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3961 // We can't add more than one pointer together, nor can we scale a
3962 // pointer (both of which seem meaningless).
3963 if (ResultPtr || AddrMode.Scale != 1)
3964 return false;
3965
3966 ResultPtr = AddrMode.ScaledReg;
3967 AddrMode.Scale = 0;
3968 }
3969
3970 if (AddrMode.BaseGV) {
3971 if (ResultPtr)
3972 return false;
3973
3974 ResultPtr = AddrMode.BaseGV;
3975 }
3976
3977 // If the real base value actually came from an inttoptr, then the matcher
3978 // will look through it and provide only the integer value. In that case,
3979 // use it here.
3980 if (!ResultPtr && AddrMode.BaseReg) {
3981 ResultPtr =
3982 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003983 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003984 } else if (!ResultPtr && AddrMode.Scale == 1) {
3985 ResultPtr =
3986 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3987 AddrMode.Scale = 0;
3988 }
3989
3990 if (!ResultPtr &&
3991 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3992 SunkAddr = Constant::getNullValue(Addr->getType());
3993 } else if (!ResultPtr) {
3994 return false;
3995 } else {
3996 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003997 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3998 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003999
4000 // Start with the base register. Do this first so that subsequent address
4001 // matching finds it last, which will prevent it from trying to match it
4002 // as the scaled value in case it happens to be a mul. That would be
4003 // problematic if we've sunk a different mul for the scale, because then
4004 // we'd end up sinking both muls.
4005 if (AddrMode.BaseReg) {
4006 Value *V = AddrMode.BaseReg;
4007 if (V->getType() != IntPtrTy)
4008 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4009
4010 ResultIndex = V;
4011 }
4012
4013 // Add the scale value.
4014 if (AddrMode.Scale) {
4015 Value *V = AddrMode.ScaledReg;
4016 if (V->getType() == IntPtrTy) {
4017 // done.
4018 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4019 cast<IntegerType>(V->getType())->getBitWidth()) {
4020 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4021 } else {
4022 // It is only safe to sign extend the BaseReg if we know that the math
4023 // required to create it did not overflow before we extend it. Since
4024 // the original IR value was tossed in favor of a constant back when
4025 // the AddrMode was created we need to bail out gracefully if widths
4026 // do not match instead of extending it.
4027 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
4028 if (I && (ResultIndex != AddrMode.BaseReg))
4029 I->eraseFromParent();
4030 return false;
4031 }
4032
4033 if (AddrMode.Scale != 1)
4034 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4035 "sunkaddr");
4036 if (ResultIndex)
4037 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4038 else
4039 ResultIndex = V;
4040 }
4041
4042 // Add in the Base Offset if present.
4043 if (AddrMode.BaseOffs) {
4044 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4045 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004046 // We need to add this separately from the scale above to help with
4047 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004048 if (ResultPtr->getType() != I8PtrTy)
4049 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004050 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004051 }
4052
4053 ResultIndex = V;
4054 }
4055
4056 if (!ResultIndex) {
4057 SunkAddr = ResultPtr;
4058 } else {
4059 if (ResultPtr->getType() != I8PtrTy)
4060 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004061 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004062 }
4063
4064 if (SunkAddr->getType() != Addr->getType())
4065 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
4066 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004067 } else {
David Greene74e2d492010-01-05 01:27:11 +00004068 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004069 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004070 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004071 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004072
4073 // Start with the base register. Do this first so that subsequent address
4074 // matching finds it last, which will prevent it from trying to match it
4075 // as the scaled value in case it happens to be a mul. That would be
4076 // problematic if we've sunk a different mul for the scale, because then
4077 // we'd end up sinking both muls.
4078 if (AddrMode.BaseReg) {
4079 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004080 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004081 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004082 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004083 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004084 Result = V;
4085 }
4086
4087 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004088 if (AddrMode.Scale) {
4089 Value *V = AddrMode.ScaledReg;
4090 if (V->getType() == IntPtrTy) {
4091 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004092 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004093 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004094 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4095 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004096 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004097 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004098 // It is only safe to sign extend the BaseReg if we know that the math
4099 // required to create it did not overflow before we extend it. Since
4100 // the original IR value was tossed in favor of a constant back when
4101 // the AddrMode was created we need to bail out gracefully if widths
4102 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004103 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004104 if (I && (Result != AddrMode.BaseReg))
4105 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004106 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004107 }
4108 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004109 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4110 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004111 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004112 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004113 else
4114 Result = V;
4115 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004116
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004117 // Add in the BaseGV if present.
4118 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004119 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004120 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004121 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004122 else
4123 Result = V;
4124 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004125
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004126 // Add in the Base Offset if present.
4127 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004128 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004129 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004130 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004131 else
4132 Result = V;
4133 }
4134
Craig Topperc0196b12014-04-14 00:51:57 +00004135 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004136 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004137 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004138 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004139 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004140
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004141 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004142
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004143 // If we have no uses, recursively delete the value and all dead instructions
4144 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004145 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004146 // This can cause recursive deletion, which can invalidate our iterator.
4147 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004148 Value *CurValue = &*CurInstIterator;
4149 WeakVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004150 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004151
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004152 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004153
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004154 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004155 // If the iterator instruction was recursively deleted, start over at the
4156 // start of the block.
4157 CurInstIterator = BB->begin();
4158 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004159 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004160 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004161 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004162 return true;
4163}
4164
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004165/// If there are any memory operands, use OptimizeMemoryInst to sink their
4166/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004167bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004168 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004169
Eric Christopher11e4df72015-02-26 22:38:43 +00004170 const TargetRegisterInfo *TRI =
4171 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004172 TargetLowering::AsmOperandInfoVector TargetConstraints =
4173 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004174 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004175 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4176 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004177
Evan Cheng1da25002008-02-26 02:42:37 +00004178 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004179 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004180
Eli Friedman666bbe32008-02-26 18:37:49 +00004181 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4182 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004183 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004184 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004185 } else if (OpInfo.Type == InlineAsm::isInput)
4186 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004187 }
4188
4189 return MadeChange;
4190}
4191
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004192/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
4193/// sign extensions.
4194static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
4195 assert(!Inst->use_empty() && "Input must have at least one use");
4196 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
4197 bool IsSExt = isa<SExtInst>(FirstUser);
4198 Type *ExtTy = FirstUser->getType();
4199 for (const User *U : Inst->users()) {
4200 const Instruction *UI = cast<Instruction>(U);
4201 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4202 return false;
4203 Type *CurTy = UI->getType();
4204 // Same input and output types: Same instruction after CSE.
4205 if (CurTy == ExtTy)
4206 continue;
4207
4208 // If IsSExt is true, we are in this situation:
4209 // a = Inst
4210 // b = sext ty1 a to ty2
4211 // c = sext ty1 a to ty3
4212 // Assuming ty2 is shorter than ty3, this could be turned into:
4213 // a = Inst
4214 // b = sext ty1 a to ty2
4215 // c = sext ty2 b to ty3
4216 // However, the last sext is not free.
4217 if (IsSExt)
4218 return false;
4219
4220 // This is a ZExt, maybe this is free to extend from one type to another.
4221 // In that case, we would not account for a different use.
4222 Type *NarrowTy;
4223 Type *LargeTy;
4224 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4225 CurTy->getScalarType()->getIntegerBitWidth()) {
4226 NarrowTy = CurTy;
4227 LargeTy = ExtTy;
4228 } else {
4229 NarrowTy = ExtTy;
4230 LargeTy = CurTy;
4231 }
4232
4233 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4234 return false;
4235 }
4236 // All uses are the same or can be derived from one another for free.
4237 return true;
4238}
4239
4240/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4241/// load instruction.
4242/// If an ext(load) can be formed, it is returned via \p LI for the load
4243/// and \p Inst for the extension.
4244/// Otherwise LI == nullptr and Inst == nullptr.
4245/// When some promotion happened, \p TPT contains the proper state to
4246/// revert them.
4247///
4248/// \return true when promoting was necessary to expose the ext(load)
4249/// opportunity, false otherwise.
4250///
4251/// Example:
4252/// \code
4253/// %ld = load i32* %addr
4254/// %add = add nuw i32 %ld, 4
4255/// %zext = zext i32 %add to i64
4256/// \endcode
4257/// =>
4258/// \code
4259/// %ld = load i32* %addr
4260/// %zext = zext i32 %ld to i64
4261/// %add = add nuw i64 %zext, 4
4262/// \encode
4263/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004264bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004265 LoadInst *&LI, Instruction *&Inst,
4266 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004267 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004268 // Iterate over all the extensions to see if one form an ext(load).
4269 for (auto I : Exts) {
4270 // Check if we directly have ext(load).
4271 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4272 Inst = I;
4273 // No promotion happened here.
4274 return false;
4275 }
4276 // Check whether or not we want to do any promotion.
4277 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4278 continue;
4279 // Get the action to perform the promotion.
4280 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004281 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004282 // Check if we can promote.
4283 if (!TPH)
4284 continue;
4285 // Save the current state.
4286 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4287 TPT.getRestorationPoint();
4288 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004289 unsigned NewCreatedInstsCost = 0;
4290 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004291 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004292 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4293 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004294 assert(PromotedVal &&
4295 "TypePromotionHelper should have filtered out those cases");
4296
4297 // We would be able to merge only one extension in a load.
4298 // Therefore, if we have more than 1 new extension we heuristically
4299 // cut this search path, because it means we degrade the code quality.
4300 // With exactly 2, the transformation is neutral, because we will merge
4301 // one extension but leave one. However, we optimistically keep going,
4302 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004303 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4304 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004305 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004306 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004307 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004308 // The promotion is not profitable, rollback to the previous state.
4309 TPT.rollback(LastKnownGood);
4310 continue;
4311 }
4312 // The promotion is profitable.
4313 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004314 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004315 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004316 // If we have created a new extension, i.e., now we have two
4317 // extensions. We must make sure one of them is merged with
4318 // the load, otherwise we may degrade the code quality.
4319 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4320 // Promotion happened.
4321 return true;
4322 // If this does not help to expose an ext(load) then, rollback.
4323 TPT.rollback(LastKnownGood);
4324 }
4325 // None of the extension can form an ext(load).
4326 LI = nullptr;
4327 Inst = nullptr;
4328 return false;
4329}
4330
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004331/// Move a zext or sext fed by a load into the same basic block as the load,
4332/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4333/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004334/// \p I[in/out] the extension may be modified during the process if some
4335/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004336///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004337bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Chandler Carruth0f139b42016-11-04 06:54:00 +00004338 // ExtLoad formation infrastructure requires TLI to be effective.
4339 if (!TLI)
4340 return false;
4341
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004342 // Try to promote a chain of computation if it allows to form
4343 // an extended load.
4344 TypePromotionTransaction TPT;
4345 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4346 TPT.getRestorationPoint();
4347 SmallVector<Instruction *, 1> Exts;
4348 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004349 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004350 LoadInst *LI = nullptr;
4351 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004352 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004353 if (!LI || !I) {
4354 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4355 "the code must remain the same");
4356 I = OldExt;
4357 return false;
4358 }
Dan Gohman99429a02009-10-16 20:59:35 +00004359
4360 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004361 // Make the cheap checks first if we did not promote.
4362 // If we promoted, we need to check if it is indeed profitable.
4363 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004364 return false;
4365
Mehdi Amini44ede332015-07-09 02:09:04 +00004366 EVT VT = TLI->getValueType(*DL, I->getType());
4367 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004368
Dan Gohman99429a02009-10-16 20:59:35 +00004369 // If the load has other users and the truncate is not free, this probably
4370 // isn't worthwhile.
Chandler Carruth0f139b42016-11-04 06:54:00 +00004371 if (!LI->hasOneUse() &&
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004372 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004373 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4374 I = OldExt;
4375 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004376 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004377 }
Dan Gohman99429a02009-10-16 20:59:35 +00004378
4379 // Check whether the target supports casts folded into loads.
4380 unsigned LType;
4381 if (isa<ZExtInst>(I))
4382 LType = ISD::ZEXTLOAD;
4383 else {
4384 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4385 LType = ISD::SEXTLOAD;
4386 }
Chandler Carruth0f139b42016-11-04 06:54:00 +00004387 if (!TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004388 I = OldExt;
4389 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004390 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004391 }
Dan Gohman99429a02009-10-16 20:59:35 +00004392
4393 // Move the extend into the same block as the load, so that SelectionDAG
4394 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004395 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004396 I->removeFromParent();
4397 I->insertAfter(LI);
Andrea Di Biagiofa90c692016-10-17 11:32:26 +00004398 // CGP does not check if the zext would be speculatively executed when moved
4399 // to the same basic block as the load. Preserving its original location would
4400 // pessimize the debugging experience, as well as negatively impact the
4401 // quality of sample pgo. We don't want to use "line 0" as that has a
4402 // size cost in the line-table section and logically the zext can be seen as
4403 // part of the load. Therefore we conservatively reuse the same debug location
4404 // for the load and the zext.
4405 I->setDebugLoc(LI->getDebugLoc());
Cameron Zwarichced753f2011-01-05 17:27:27 +00004406 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004407 return true;
4408}
4409
Sanjay Patelfc580a62015-09-21 23:03:16 +00004410bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004411 BasicBlock *DefBB = I->getParent();
4412
Bob Wilsonff714f92010-09-21 21:44:14 +00004413 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004414 // other uses of the source with result of extension.
4415 Value *Src = I->getOperand(0);
4416 if (Src->hasOneUse())
4417 return false;
4418
Evan Cheng2011df42007-12-13 07:50:36 +00004419 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004420 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004421 return false;
4422
Evan Cheng7bc89422007-12-12 00:51:06 +00004423 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004424 // this block.
4425 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004426 return false;
4427
Evan Chengd3d80172007-12-05 23:58:20 +00004428 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004429 for (User *U : I->users()) {
4430 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004431
4432 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004433 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004434 if (UserBB == DefBB) continue;
4435 DefIsLiveOut = true;
4436 break;
4437 }
4438 if (!DefIsLiveOut)
4439 return false;
4440
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004441 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004442 for (User *U : Src->users()) {
4443 Instruction *UI = cast<Instruction>(U);
4444 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004445 if (UserBB == DefBB) continue;
4446 // Be conservative. We don't want this xform to end up introducing
4447 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004448 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004449 return false;
4450 }
4451
Evan Chengd3d80172007-12-05 23:58:20 +00004452 // InsertedTruncs - Only insert one trunc in each block once.
4453 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4454
4455 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004456 for (Use &U : Src->uses()) {
4457 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004458
4459 // Figure out which BB this ext is used in.
4460 BasicBlock *UserBB = User->getParent();
4461 if (UserBB == DefBB) continue;
4462
4463 // Both src and def are live in this block. Rewrite the use.
4464 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4465
4466 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004467 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004468 assert(InsertPt != UserBB->end());
4469 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004470 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004471 }
4472
4473 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004474 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004475 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004476 MadeChange = true;
4477 }
4478
4479 return MadeChange;
4480}
4481
Geoff Berry5256fca2015-11-20 22:34:39 +00004482// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4483// just after the load if the target can fold this into one extload instruction,
4484// with the hope of eliminating some of the other later "and" instructions using
4485// the loaded value. "and"s that are made trivially redundant by the insertion
4486// of the new "and" are removed by this function, while others (e.g. those whose
4487// path from the load goes through a phi) are left for isel to potentially
4488// remove.
4489//
4490// For example:
4491//
4492// b0:
4493// x = load i32
4494// ...
4495// b1:
4496// y = and x, 0xff
4497// z = use y
4498//
4499// becomes:
4500//
4501// b0:
4502// x = load i32
4503// x' = and x, 0xff
4504// ...
4505// b1:
4506// z = use x'
4507//
4508// whereas:
4509//
4510// b0:
4511// x1 = load i32
4512// ...
4513// b1:
4514// x2 = load i32
4515// ...
4516// b2:
4517// x = phi x1, x2
4518// y = and x, 0xff
4519//
4520// becomes (after a call to optimizeLoadExt for each load):
4521//
4522// b0:
4523// x1 = load i32
4524// x1' = and x1, 0xff
4525// ...
4526// b1:
4527// x2 = load i32
4528// x2' = and x2, 0xff
4529// ...
4530// b2:
4531// x = phi x1', x2'
4532// y = and x, 0xff
4533//
4534
4535bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4536
4537 if (!Load->isSimple() ||
4538 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4539 return false;
4540
4541 // Skip loads we've already transformed or have no reason to transform.
4542 if (Load->hasOneUse()) {
4543 User *LoadUser = *Load->user_begin();
4544 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
4545 !dyn_cast<PHINode>(LoadUser))
4546 return false;
4547 }
4548
4549 // Look at all uses of Load, looking through phis, to determine how many bits
4550 // of the loaded value are needed.
4551 SmallVector<Instruction *, 8> WorkList;
4552 SmallPtrSet<Instruction *, 16> Visited;
4553 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4554 for (auto *U : Load->users())
4555 WorkList.push_back(cast<Instruction>(U));
4556
4557 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4558 unsigned BitWidth = LoadResultVT.getSizeInBits();
4559 APInt DemandBits(BitWidth, 0);
4560 APInt WidestAndBits(BitWidth, 0);
4561
4562 while (!WorkList.empty()) {
4563 Instruction *I = WorkList.back();
4564 WorkList.pop_back();
4565
4566 // Break use-def graph loops.
4567 if (!Visited.insert(I).second)
4568 continue;
4569
4570 // For a PHI node, push all of its users.
4571 if (auto *Phi = dyn_cast<PHINode>(I)) {
4572 for (auto *U : Phi->users())
4573 WorkList.push_back(cast<Instruction>(U));
4574 continue;
4575 }
4576
4577 switch (I->getOpcode()) {
4578 case llvm::Instruction::And: {
4579 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4580 if (!AndC)
4581 return false;
4582 APInt AndBits = AndC->getValue();
4583 DemandBits |= AndBits;
4584 // Keep track of the widest and mask we see.
4585 if (AndBits.ugt(WidestAndBits))
4586 WidestAndBits = AndBits;
4587 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4588 AndsToMaybeRemove.push_back(I);
4589 break;
4590 }
4591
4592 case llvm::Instruction::Shl: {
4593 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4594 if (!ShlC)
4595 return false;
4596 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4597 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4598 DemandBits |= ShlDemandBits;
4599 break;
4600 }
4601
4602 case llvm::Instruction::Trunc: {
4603 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4604 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4605 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4606 DemandBits |= TruncBits;
4607 break;
4608 }
4609
4610 default:
4611 return false;
4612 }
4613 }
4614
4615 uint32_t ActiveBits = DemandBits.getActiveBits();
4616 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4617 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4618 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4619 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4620 // followed by an AND.
4621 // TODO: Look into removing this restriction by fixing backends to either
4622 // return false for isLoadExtLegal for i1 or have them select this pattern to
4623 // a single instruction.
4624 //
4625 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4626 // mask, since these are the only ands that will be removed by isel.
4627 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4628 WidestAndBits != DemandBits)
4629 return false;
4630
4631 LLVMContext &Ctx = Load->getType()->getContext();
4632 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4633 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4634
4635 // Reject cases that won't be matched as extloads.
4636 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4637 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4638 return false;
4639
4640 IRBuilder<> Builder(Load->getNextNode());
4641 auto *NewAnd = dyn_cast<Instruction>(
4642 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
4643
4644 // Replace all uses of load with new and (except for the use of load in the
4645 // new and itself).
4646 Load->replaceAllUsesWith(NewAnd);
4647 NewAnd->setOperand(0, Load);
4648
4649 // Remove any and instructions that are now redundant.
4650 for (auto *And : AndsToMaybeRemove)
4651 // Check that the and mask is the same as the one we decided to put on the
4652 // new and.
4653 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4654 And->replaceAllUsesWith(NewAnd);
4655 if (&*CurInstIterator == And)
4656 CurInstIterator = std::next(And->getIterator());
4657 And->eraseFromParent();
4658 ++NumAndUses;
4659 }
4660
4661 ++NumAndsAdded;
4662 return true;
4663}
4664
Sanjay Patel69a50a12015-10-19 21:59:12 +00004665/// Check if V (an operand of a select instruction) is an expensive instruction
4666/// that is only used once.
4667static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4668 auto *I = dyn_cast<Instruction>(V);
4669 // If it's safe to speculatively execute, then it should not have side
4670 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004671 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4672 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004673}
4674
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004675/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004676static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00004677 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00004678 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00004679 // If even a predictable select is cheap, then a branch can't be cheaper.
4680 if (!TLI->isPredictableSelectExpensive())
4681 return false;
4682
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004683 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00004684 // whether a select is better represented as a branch.
4685
4686 // If metadata tells us that the select condition is obviously predictable,
4687 // then we want to replace the select with a branch.
4688 uint64_t TrueWeight, FalseWeight;
4689 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
4690 uint64_t Max = std::max(TrueWeight, FalseWeight);
4691 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00004692 if (Sum != 0) {
4693 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
4694 if (Probability > TLI->getPredictableBranchThreshold())
4695 return true;
4696 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00004697 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004698
4699 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4700
Sanjay Patel4e652762015-09-28 22:14:51 +00004701 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4702 // comparison condition. If the compare has more than one use, there's
4703 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004704 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004705 return false;
4706
Sanjay Patel69a50a12015-10-19 21:59:12 +00004707 // If either operand of the select is expensive and only needed on one side
4708 // of the select, we should form a branch.
4709 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4710 sinkSelectOperand(TTI, SI->getFalseValue()))
4711 return true;
4712
4713 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004714}
4715
Dehao Chen9bbb9412016-09-12 20:23:28 +00004716/// If \p isTrue is true, return the true value of \p SI, otherwise return
4717/// false value of \p SI. If the true/false value of \p SI is defined by any
4718/// select instructions in \p Selects, look through the defining select
4719/// instruction until the true/false value is not defined in \p Selects.
4720static Value *getTrueOrFalseValue(
4721 SelectInst *SI, bool isTrue,
4722 const SmallPtrSet<const Instruction *, 2> &Selects) {
4723 Value *V;
4724
4725 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
4726 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00004727 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00004728 "The condition of DefSI does not match with SI");
4729 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
4730 }
4731 return V;
4732}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004733
Nadav Rotem9d832022012-09-02 12:10:19 +00004734/// If we have a SelectInst that will likely profit from branch prediction,
4735/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004736bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00004737 // Find all consecutive select instructions that share the same condition.
4738 SmallVector<SelectInst *, 2> ASI;
4739 ASI.push_back(SI);
4740 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
4741 It != SI->getParent()->end(); ++It) {
4742 SelectInst *I = dyn_cast<SelectInst>(&*It);
4743 if (I && SI->getCondition() == I->getCondition()) {
4744 ASI.push_back(I);
4745 } else {
4746 break;
4747 }
4748 }
4749
4750 SelectInst *LastSI = ASI.back();
4751 // Increment the current iterator to skip all the rest of select instructions
4752 // because they will be either "not lowered" or "all lowered" to branch.
4753 CurInstIterator = std::next(LastSI->getIterator());
4754
Nadav Rotem9d832022012-09-02 12:10:19 +00004755 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4756
4757 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00004758 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
4759 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004760 return false;
4761
Nadav Rotem9d832022012-09-02 12:10:19 +00004762 TargetLowering::SelectSupportKind SelectKind;
4763 if (VectorCond)
4764 SelectKind = TargetLowering::VectorMaskSelect;
4765 else if (SI->getType()->isVectorTy())
4766 SelectKind = TargetLowering::ScalarCondVectorVal;
4767 else
4768 SelectKind = TargetLowering::ScalarValSelect;
4769
Sanjay Pateld66607b2016-04-26 17:11:17 +00004770 if (TLI->isSelectSupported(SelectKind) &&
4771 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
4772 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004773
4774 ModifiedDT = true;
4775
Sanjay Patel69a50a12015-10-19 21:59:12 +00004776 // Transform a sequence like this:
4777 // start:
4778 // %cmp = cmp uge i32 %a, %b
4779 // %sel = select i1 %cmp, i32 %c, i32 %d
4780 //
4781 // Into:
4782 // start:
4783 // %cmp = cmp uge i32 %a, %b
4784 // br i1 %cmp, label %select.true, label %select.false
4785 // select.true:
4786 // br label %select.end
4787 // select.false:
4788 // br label %select.end
4789 // select.end:
4790 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4791 //
4792 // In addition, we may sink instructions that produce %c or %d from
4793 // the entry block into the destination(s) of the new branch.
4794 // If the true or false blocks do not contain a sunken instruction, that
4795 // block and its branch may be optimized away. In that case, one side of the
4796 // first branch will point directly to select.end, and the corresponding PHI
4797 // predecessor block will be the start block.
4798
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004799 // First, we split the block containing the select into 2 blocks.
4800 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00004801 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004802 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004803
Sanjay Patel69a50a12015-10-19 21:59:12 +00004804 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004805 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004806
4807 // These are the new basic blocks for the conditional branch.
4808 // At least one will become an actual new basic block.
4809 BasicBlock *TrueBlock = nullptr;
4810 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00004811 BranchInst *TrueBranch = nullptr;
4812 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004813
4814 // Sink expensive instructions into the conditional blocks to avoid executing
4815 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00004816 for (SelectInst *SI : ASI) {
4817 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4818 if (TrueBlock == nullptr) {
4819 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4820 EndBlock->getParent(), EndBlock);
4821 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4822 }
4823 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4824 TrueInst->moveBefore(TrueBranch);
4825 }
4826 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4827 if (FalseBlock == nullptr) {
4828 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4829 EndBlock->getParent(), EndBlock);
4830 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4831 }
4832 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4833 FalseInst->moveBefore(FalseBranch);
4834 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00004835 }
4836
4837 // If there was nothing to sink, then arbitrarily choose the 'false' side
4838 // for a new input value to the PHI.
4839 if (TrueBlock == FalseBlock) {
4840 assert(TrueBlock == nullptr &&
4841 "Unexpected basic block transform while optimizing select");
4842
4843 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4844 EndBlock->getParent(), EndBlock);
4845 BranchInst::Create(EndBlock, FalseBlock);
4846 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004847
4848 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004849 // If we did not create a new block for one of the 'true' or 'false' paths
4850 // of the condition, it means that side of the branch goes to the end block
4851 // directly and the path originates from the start block from the point of
4852 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00004853 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004854 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004855 TT = EndBlock;
4856 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004857 TrueBlock = StartBlock;
4858 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004859 TT = TrueBlock;
4860 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004861 FalseBlock = StartBlock;
4862 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004863 TT = TrueBlock;
4864 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004865 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00004866 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004867
Dehao Chen9bbb9412016-09-12 20:23:28 +00004868 SmallPtrSet<const Instruction *, 2> INS;
4869 INS.insert(ASI.begin(), ASI.end());
4870 // Use reverse iterator because later select may use the value of the
4871 // earlier select, and we need to propagate value through earlier select
4872 // to get the PHI operand.
4873 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
4874 SelectInst *SI = *It;
4875 // The select itself is replaced with a PHI Node.
4876 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
4877 PN->takeName(SI);
4878 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
4879 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004880
Dehao Chen9bbb9412016-09-12 20:23:28 +00004881 SI->replaceAllUsesWith(PN);
4882 SI->eraseFromParent();
4883 INS.erase(SI);
4884 ++NumSelectsExpanded;
4885 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004886
4887 // Instruct OptimizeBlock to skip to the next block.
4888 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004889 return true;
4890}
4891
Benjamin Kramer573ff362014-03-01 17:24:40 +00004892static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004893 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4894 int SplatElem = -1;
4895 for (unsigned i = 0; i < Mask.size(); ++i) {
4896 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4897 return false;
4898 SplatElem = Mask[i];
4899 }
4900
4901 return true;
4902}
4903
4904/// Some targets have expensive vector shifts if the lanes aren't all the same
4905/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4906/// it's often worth sinking a shufflevector splat down to its use so that
4907/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004908bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004909 BasicBlock *DefBB = SVI->getParent();
4910
4911 // Only do this xform if variable vector shifts are particularly expensive.
4912 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4913 return false;
4914
4915 // We only expect better codegen by sinking a shuffle if we can recognise a
4916 // constant splat.
4917 if (!isBroadcastShuffle(SVI))
4918 return false;
4919
4920 // InsertedShuffles - Only insert a shuffle in each block once.
4921 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4922
4923 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004924 for (User *U : SVI->users()) {
4925 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004926
4927 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004928 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004929 if (UserBB == DefBB) continue;
4930
4931 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004932 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004933
4934 // Everything checks out, sink the shuffle if the user's block doesn't
4935 // already have a copy.
4936 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4937
4938 if (!InsertedShuffle) {
4939 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004940 assert(InsertPt != UserBB->end());
4941 InsertedShuffle =
4942 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4943 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004944 }
4945
Chandler Carruthcdf47882014-03-09 03:16:01 +00004946 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004947 MadeChange = true;
4948 }
4949
4950 // If we removed all uses, nuke the shuffle.
4951 if (SVI->use_empty()) {
4952 SVI->eraseFromParent();
4953 MadeChange = true;
4954 }
4955
4956 return MadeChange;
4957}
4958
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00004959bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
4960 if (!TLI || !DL)
4961 return false;
4962
4963 Value *Cond = SI->getCondition();
4964 Type *OldType = Cond->getType();
4965 LLVMContext &Context = Cond->getContext();
4966 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
4967 unsigned RegWidth = RegType.getSizeInBits();
4968
4969 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
4970 return false;
4971
4972 // If the register width is greater than the type width, expand the condition
4973 // of the switch instruction and each case constant to the width of the
4974 // register. By widening the type of the switch condition, subsequent
4975 // comparisons (for case comparisons) will not need to be extended to the
4976 // preferred register width, so we will potentially eliminate N-1 extends,
4977 // where N is the number of cases in the switch.
4978 auto *NewType = Type::getIntNTy(Context, RegWidth);
4979
4980 // Zero-extend the switch condition and case constants unless the switch
4981 // condition is a function argument that is already being sign-extended.
4982 // In that case, we can avoid an unnecessary mask/extension by sign-extending
4983 // everything instead.
4984 Instruction::CastOps ExtType = Instruction::ZExt;
4985 if (auto *Arg = dyn_cast<Argument>(Cond))
4986 if (Arg->hasSExtAttr())
4987 ExtType = Instruction::SExt;
4988
4989 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
4990 ExtInst->insertBefore(SI);
4991 SI->setCondition(ExtInst);
4992 for (SwitchInst::CaseIt Case : SI->cases()) {
4993 APInt NarrowConst = Case.getCaseValue()->getValue();
4994 APInt WideConst = (ExtType == Instruction::ZExt) ?
4995 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
4996 Case.setValue(ConstantInt::get(Context, WideConst));
4997 }
4998
4999 return true;
5000}
5001
Quentin Colombetc32615d2014-10-31 17:52:53 +00005002namespace {
5003/// \brief Helper class to promote a scalar operation to a vector one.
5004/// This class is used to move downward extractelement transition.
5005/// E.g.,
5006/// a = vector_op <2 x i32>
5007/// b = extractelement <2 x i32> a, i32 0
5008/// c = scalar_op b
5009/// store c
5010///
5011/// =>
5012/// a = vector_op <2 x i32>
5013/// c = vector_op a (equivalent to scalar_op on the related lane)
5014/// * d = extractelement <2 x i32> c, i32 0
5015/// * store d
5016/// Assuming both extractelement and store can be combine, we get rid of the
5017/// transition.
5018class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005019 /// DataLayout associated with the current module.
5020 const DataLayout &DL;
5021
Quentin Colombetc32615d2014-10-31 17:52:53 +00005022 /// Used to perform some checks on the legality of vector operations.
5023 const TargetLowering &TLI;
5024
5025 /// Used to estimated the cost of the promoted chain.
5026 const TargetTransformInfo &TTI;
5027
5028 /// The transition being moved downwards.
5029 Instruction *Transition;
5030 /// The sequence of instructions to be promoted.
5031 SmallVector<Instruction *, 4> InstsToBePromoted;
5032 /// Cost of combining a store and an extract.
5033 unsigned StoreExtractCombineCost;
5034 /// Instruction that will be combined with the transition.
5035 Instruction *CombineInst;
5036
5037 /// \brief The instruction that represents the current end of the transition.
5038 /// Since we are faking the promotion until we reach the end of the chain
5039 /// of computation, we need a way to get the current end of the transition.
5040 Instruction *getEndOfTransition() const {
5041 if (InstsToBePromoted.empty())
5042 return Transition;
5043 return InstsToBePromoted.back();
5044 }
5045
5046 /// \brief Return the index of the original value in the transition.
5047 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5048 /// c, is at index 0.
5049 unsigned getTransitionOriginalValueIdx() const {
5050 assert(isa<ExtractElementInst>(Transition) &&
5051 "Other kind of transitions are not supported yet");
5052 return 0;
5053 }
5054
5055 /// \brief Return the index of the index in the transition.
5056 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5057 /// is at index 1.
5058 unsigned getTransitionIdx() const {
5059 assert(isa<ExtractElementInst>(Transition) &&
5060 "Other kind of transitions are not supported yet");
5061 return 1;
5062 }
5063
5064 /// \brief Get the type of the transition.
5065 /// This is the type of the original value.
5066 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5067 /// transition is <2 x i32>.
5068 Type *getTransitionType() const {
5069 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5070 }
5071
5072 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5073 /// I.e., we have the following sequence:
5074 /// Def = Transition <ty1> a to <ty2>
5075 /// b = ToBePromoted <ty2> Def, ...
5076 /// =>
5077 /// b = ToBePromoted <ty1> a, ...
5078 /// Def = Transition <ty1> ToBePromoted to <ty2>
5079 void promoteImpl(Instruction *ToBePromoted);
5080
5081 /// \brief Check whether or not it is profitable to promote all the
5082 /// instructions enqueued to be promoted.
5083 bool isProfitableToPromote() {
5084 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5085 unsigned Index = isa<ConstantInt>(ValIdx)
5086 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5087 : -1;
5088 Type *PromotedType = getTransitionType();
5089
5090 StoreInst *ST = cast<StoreInst>(CombineInst);
5091 unsigned AS = ST->getPointerAddressSpace();
5092 unsigned Align = ST->getAlignment();
5093 // Check if this store is supported.
5094 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005095 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5096 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005097 // If this is not supported, there is no way we can combine
5098 // the extract with the store.
5099 return false;
5100 }
5101
5102 // The scalar chain of computation has to pay for the transition
5103 // scalar to vector.
5104 // The vector chain has to account for the combining cost.
5105 uint64_t ScalarCost =
5106 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5107 uint64_t VectorCost = StoreExtractCombineCost;
5108 for (const auto &Inst : InstsToBePromoted) {
5109 // Compute the cost.
5110 // By construction, all instructions being promoted are arithmetic ones.
5111 // Moreover, one argument is a constant that can be viewed as a splat
5112 // constant.
5113 Value *Arg0 = Inst->getOperand(0);
5114 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5115 isa<ConstantFP>(Arg0);
5116 TargetTransformInfo::OperandValueKind Arg0OVK =
5117 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5118 : TargetTransformInfo::OK_AnyValue;
5119 TargetTransformInfo::OperandValueKind Arg1OVK =
5120 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5121 : TargetTransformInfo::OK_AnyValue;
5122 ScalarCost += TTI.getArithmeticInstrCost(
5123 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5124 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5125 Arg0OVK, Arg1OVK);
5126 }
5127 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5128 << ScalarCost << "\nVector: " << VectorCost << '\n');
5129 return ScalarCost > VectorCost;
5130 }
5131
5132 /// \brief Generate a constant vector with \p Val with the same
5133 /// number of elements as the transition.
5134 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005135 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005136 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5137 /// otherwise we generate a vector with as many undef as possible:
5138 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5139 /// used at the index of the extract.
5140 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5141 unsigned ExtractIdx = UINT_MAX;
5142 if (!UseSplat) {
5143 // If we cannot determine where the constant must be, we have to
5144 // use a splat constant.
5145 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5146 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5147 ExtractIdx = CstVal->getSExtValue();
5148 else
5149 UseSplat = true;
5150 }
5151
5152 unsigned End = getTransitionType()->getVectorNumElements();
5153 if (UseSplat)
5154 return ConstantVector::getSplat(End, Val);
5155
5156 SmallVector<Constant *, 4> ConstVec;
5157 UndefValue *UndefVal = UndefValue::get(Val->getType());
5158 for (unsigned Idx = 0; Idx != End; ++Idx) {
5159 if (Idx == ExtractIdx)
5160 ConstVec.push_back(Val);
5161 else
5162 ConstVec.push_back(UndefVal);
5163 }
5164 return ConstantVector::get(ConstVec);
5165 }
5166
5167 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5168 /// in \p Use can trigger undefined behavior.
5169 static bool canCauseUndefinedBehavior(const Instruction *Use,
5170 unsigned OperandIdx) {
5171 // This is not safe to introduce undef when the operand is on
5172 // the right hand side of a division-like instruction.
5173 if (OperandIdx != 1)
5174 return false;
5175 switch (Use->getOpcode()) {
5176 default:
5177 return false;
5178 case Instruction::SDiv:
5179 case Instruction::UDiv:
5180 case Instruction::SRem:
5181 case Instruction::URem:
5182 return true;
5183 case Instruction::FDiv:
5184 case Instruction::FRem:
5185 return !Use->hasNoNaNs();
5186 }
5187 llvm_unreachable(nullptr);
5188 }
5189
5190public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005191 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5192 const TargetTransformInfo &TTI, Instruction *Transition,
5193 unsigned CombineCost)
5194 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00005195 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5196 assert(Transition && "Do not know how to promote null");
5197 }
5198
5199 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5200 bool canPromote(const Instruction *ToBePromoted) const {
5201 // We could support CastInst too.
5202 return isa<BinaryOperator>(ToBePromoted);
5203 }
5204
5205 /// \brief Check if it is profitable to promote \p ToBePromoted
5206 /// by moving downward the transition through.
5207 bool shouldPromote(const Instruction *ToBePromoted) const {
5208 // Promote only if all the operands can be statically expanded.
5209 // Indeed, we do not want to introduce any new kind of transitions.
5210 for (const Use &U : ToBePromoted->operands()) {
5211 const Value *Val = U.get();
5212 if (Val == getEndOfTransition()) {
5213 // If the use is a division and the transition is on the rhs,
5214 // we cannot promote the operation, otherwise we may create a
5215 // division by zero.
5216 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5217 return false;
5218 continue;
5219 }
5220 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5221 !isa<ConstantFP>(Val))
5222 return false;
5223 }
5224 // Check that the resulting operation is legal.
5225 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5226 if (!ISDOpcode)
5227 return false;
5228 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005229 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005230 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005231 }
5232
5233 /// \brief Check whether or not \p Use can be combined
5234 /// with the transition.
5235 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5236 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5237
5238 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5239 void enqueueForPromotion(Instruction *ToBePromoted) {
5240 InstsToBePromoted.push_back(ToBePromoted);
5241 }
5242
5243 /// \brief Set the instruction that will be combined with the transition.
5244 void recordCombineInstruction(Instruction *ToBeCombined) {
5245 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5246 CombineInst = ToBeCombined;
5247 }
5248
5249 /// \brief Promote all the instructions enqueued for promotion if it is
5250 /// is profitable.
5251 /// \return True if the promotion happened, false otherwise.
5252 bool promote() {
5253 // Check if there is something to promote.
5254 // Right now, if we do not have anything to combine with,
5255 // we assume the promotion is not profitable.
5256 if (InstsToBePromoted.empty() || !CombineInst)
5257 return false;
5258
5259 // Check cost.
5260 if (!StressStoreExtract && !isProfitableToPromote())
5261 return false;
5262
5263 // Promote.
5264 for (auto &ToBePromoted : InstsToBePromoted)
5265 promoteImpl(ToBePromoted);
5266 InstsToBePromoted.clear();
5267 return true;
5268 }
5269};
5270} // End of anonymous namespace.
5271
5272void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5273 // At this point, we know that all the operands of ToBePromoted but Def
5274 // can be statically promoted.
5275 // For Def, we need to use its parameter in ToBePromoted:
5276 // b = ToBePromoted ty1 a
5277 // Def = Transition ty1 b to ty2
5278 // Move the transition down.
5279 // 1. Replace all uses of the promoted operation by the transition.
5280 // = ... b => = ... Def.
5281 assert(ToBePromoted->getType() == Transition->getType() &&
5282 "The type of the result of the transition does not match "
5283 "the final type");
5284 ToBePromoted->replaceAllUsesWith(Transition);
5285 // 2. Update the type of the uses.
5286 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5287 Type *TransitionTy = getTransitionType();
5288 ToBePromoted->mutateType(TransitionTy);
5289 // 3. Update all the operands of the promoted operation with promoted
5290 // operands.
5291 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5292 for (Use &U : ToBePromoted->operands()) {
5293 Value *Val = U.get();
5294 Value *NewVal = nullptr;
5295 if (Val == Transition)
5296 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5297 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5298 isa<ConstantFP>(Val)) {
5299 // Use a splat constant if it is not safe to use undef.
5300 NewVal = getConstantVector(
5301 cast<Constant>(Val),
5302 isa<UndefValue>(Val) ||
5303 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5304 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005305 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5306 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005307 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5308 }
5309 Transition->removeFromParent();
5310 Transition->insertAfter(ToBePromoted);
5311 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5312}
5313
5314/// Some targets can do store(extractelement) with one instruction.
5315/// Try to push the extractelement towards the stores when the target
5316/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005317bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005318 unsigned CombineCost = UINT_MAX;
5319 if (DisableStoreExtract || !TLI ||
5320 (!StressStoreExtract &&
5321 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5322 Inst->getOperand(1), CombineCost)))
5323 return false;
5324
5325 // At this point we know that Inst is a vector to scalar transition.
5326 // Try to move it down the def-use chain, until:
5327 // - We can combine the transition with its single use
5328 // => we got rid of the transition.
5329 // - We escape the current basic block
5330 // => we would need to check that we are moving it at a cheaper place and
5331 // we do not do that for now.
5332 BasicBlock *Parent = Inst->getParent();
5333 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005334 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005335 // If the transition has more than one use, assume this is not going to be
5336 // beneficial.
5337 while (Inst->hasOneUse()) {
5338 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5339 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5340
5341 if (ToBePromoted->getParent() != Parent) {
5342 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5343 << ToBePromoted->getParent()->getName()
5344 << ") than the transition (" << Parent->getName() << ").\n");
5345 return false;
5346 }
5347
5348 if (VPH.canCombine(ToBePromoted)) {
5349 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5350 << "will be combined with: " << *ToBePromoted << '\n');
5351 VPH.recordCombineInstruction(ToBePromoted);
5352 bool Changed = VPH.promote();
5353 NumStoreExtractExposed += Changed;
5354 return Changed;
5355 }
5356
5357 DEBUG(dbgs() << "Try promoting.\n");
5358 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5359 return false;
5360
5361 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5362
5363 VPH.enqueueForPromotion(ToBePromoted);
5364 Inst = ToBePromoted;
5365 }
5366 return false;
5367}
5368
Sanjay Patelfc580a62015-09-21 23:03:16 +00005369bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005370 // Bail out if we inserted the instruction to prevent optimizations from
5371 // stepping on each other's toes.
5372 if (InsertedInsts.count(I))
5373 return false;
5374
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005375 if (PHINode *P = dyn_cast<PHINode>(I)) {
5376 // It is possible for very late stage optimizations (such as SimplifyCFG)
5377 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5378 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005379 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005380 P->replaceAllUsesWith(V);
5381 P->eraseFromParent();
5382 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005383 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005384 }
Chris Lattneree588de2011-01-15 07:29:01 +00005385 return false;
5386 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005387
Chris Lattneree588de2011-01-15 07:29:01 +00005388 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005389 // If the source of the cast is a constant, then this should have
5390 // already been constant folded. The only reason NOT to constant fold
5391 // it is if something (e.g. LSR) was careful to place the constant
5392 // evaluation in a block other than then one that uses it (e.g. to hoist
5393 // the address of globals out of a loop). If this is the case, we don't
5394 // want to forward-subst the cast.
5395 if (isa<Constant>(CI->getOperand(0)))
5396 return false;
5397
Mehdi Amini44ede332015-07-09 02:09:04 +00005398 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005399 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005400
Chris Lattneree588de2011-01-15 07:29:01 +00005401 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005402 /// Sink a zext or sext into its user blocks if the target type doesn't
5403 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005404 if (TLI &&
5405 TLI->getTypeAction(CI->getContext(),
5406 TLI->getValueType(*DL, CI->getType())) ==
5407 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005408 return SinkCast(CI);
5409 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005410 bool MadeChange = moveExtToFormExtLoad(I);
5411 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005412 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005413 }
Chris Lattneree588de2011-01-15 07:29:01 +00005414 return false;
5415 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005416
Chris Lattneree588de2011-01-15 07:29:01 +00005417 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005418 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00005419 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005420
Chris Lattneree588de2011-01-15 07:29:01 +00005421 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005422 stripInvariantGroupMetadata(*LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005423 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005424 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005425 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005426 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5427 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005428 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005429 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005430 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005431
Chris Lattneree588de2011-01-15 07:29:01 +00005432 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005433 stripInvariantGroupMetadata(*SI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005434 if (TLI) {
5435 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005436 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005437 SI->getOperand(0)->getType(), AS);
5438 }
Chris Lattneree588de2011-01-15 07:29:01 +00005439 return false;
5440 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005441
Yi Jiangd069f632014-04-21 19:34:27 +00005442 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5443
5444 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5445 BinOp->getOpcode() == Instruction::LShr)) {
5446 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5447 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005448 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005449
5450 return false;
5451 }
5452
Chris Lattneree588de2011-01-15 07:29:01 +00005453 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005454 if (GEPI->hasAllZeroIndices()) {
5455 /// The GEP operand must be a pointer, so must its result -> BitCast
5456 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5457 GEPI->getName(), GEPI);
5458 GEPI->replaceAllUsesWith(NC);
5459 GEPI->eraseFromParent();
5460 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005461 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005462 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005463 }
Chris Lattneree588de2011-01-15 07:29:01 +00005464 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005465 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005466
Chris Lattneree588de2011-01-15 07:29:01 +00005467 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005468 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005469
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005470 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005471 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005472
Tim Northoveraeb8e062014-02-19 10:02:43 +00005473 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005474 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005475
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005476 if (auto *Switch = dyn_cast<SwitchInst>(I))
5477 return optimizeSwitchInst(Switch);
5478
Quentin Colombetc32615d2014-10-31 17:52:53 +00005479 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005480 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005481
Chris Lattneree588de2011-01-15 07:29:01 +00005482 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005483}
5484
James Molloyf01488e2016-01-15 09:20:19 +00005485/// Given an OR instruction, check to see if this is a bitreverse
5486/// idiom. If so, insert the new intrinsic and return true.
5487static bool makeBitReverse(Instruction &I, const DataLayout &DL,
5488 const TargetLowering &TLI) {
5489 if (!I.getType()->isIntegerTy() ||
5490 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
5491 TLI.getValueType(DL, I.getType(), true)))
5492 return false;
5493
5494 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00005495 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00005496 return false;
5497 Instruction *LastInst = Insts.back();
5498 I.replaceAllUsesWith(LastInst);
5499 RecursivelyDeleteTriviallyDeadInstructions(&I);
5500 return true;
5501}
5502
Chris Lattnerf2836d12007-03-31 04:06:36 +00005503// In this pass we look for GEP and cast instructions that are used
5504// across basic blocks and rewrite them to improve basic-block-at-a-time
5505// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005506bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005507 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005508 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005509
Chris Lattner7a277142011-01-15 07:14:54 +00005510 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005511 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005512 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005513 if (ModifiedDT)
5514 return true;
5515 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00005516
James Molloyf01488e2016-01-15 09:20:19 +00005517 bool MadeBitReverse = true;
5518 while (TLI && MadeBitReverse) {
5519 MadeBitReverse = false;
5520 for (auto &I : reverse(BB)) {
5521 if (makeBitReverse(I, *DL, *TLI)) {
5522 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00005523 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00005524 break;
5525 }
5526 }
5527 }
James Molloy3ef84c42016-01-15 10:36:01 +00005528 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00005529
Chris Lattnerf2836d12007-03-31 04:06:36 +00005530 return MadeChange;
5531}
Devang Patel53771ba2011-08-18 00:50:51 +00005532
5533// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005534// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005535// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005536bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005537 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005538 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005539 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005540 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005541 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005542 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005543 // Leave dbg.values that refer to an alloca alone. These
5544 // instrinsics describe the address of a variable (= the alloca)
5545 // being taken. They should not be moved next to the alloca
5546 // (and to the beginning of the scope), but rather stay close to
5547 // where said address is used.
5548 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005549 PrevNonDbgInst = Insn;
5550 continue;
5551 }
5552
5553 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5554 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00005555 // If VI is a phi in a block with an EHPad terminator, we can't insert
5556 // after it.
5557 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5558 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00005559 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5560 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00005561 if (isa<PHINode>(VI))
5562 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5563 else
5564 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00005565 MadeChange = true;
5566 ++NumDbgValueMoved;
5567 }
5568 }
5569 }
5570 return MadeChange;
5571}
Tim Northovercea0abb2014-03-29 08:22:29 +00005572
5573// If there is a sequence that branches based on comparing a single bit
5574// against zero that can be combined into a single instruction, and the
5575// target supports folding these into a single instruction, sink the
5576// mask and compare into the branch uses. Do this before OptimizeBlock ->
5577// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
5578// searched for.
5579bool CodeGenPrepare::sinkAndCmp(Function &F) {
5580 if (!EnableAndCmpSinking)
5581 return false;
5582 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
5583 return false;
5584 bool MadeChange = false;
Sanjay Patel892f1672016-04-11 20:13:44 +00005585 for (BasicBlock &BB : F) {
Tim Northovercea0abb2014-03-29 08:22:29 +00005586 // Does this BB end with the following?
5587 // %andVal = and %val, #single-bit-set
5588 // %icmpVal = icmp %andResult, 0
5589 // br i1 %cmpVal label %dest1, label %dest2"
Sanjay Patel892f1672016-04-11 20:13:44 +00005590 BranchInst *Brcc = dyn_cast<BranchInst>(BB.getTerminator());
Tim Northovercea0abb2014-03-29 08:22:29 +00005591 if (!Brcc || !Brcc->isConditional())
5592 continue;
5593 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
Sanjay Patel892f1672016-04-11 20:13:44 +00005594 if (!Cmp || Cmp->getParent() != &BB)
Tim Northovercea0abb2014-03-29 08:22:29 +00005595 continue;
5596 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
5597 if (!Zero || !Zero->isZero())
5598 continue;
5599 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
Sanjay Patel892f1672016-04-11 20:13:44 +00005600 if (!And || And->getOpcode() != Instruction::And || And->getParent() != &BB)
Tim Northovercea0abb2014-03-29 08:22:29 +00005601 continue;
5602 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
5603 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
5604 continue;
Sanjay Patel892f1672016-04-11 20:13:44 +00005605 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB.dump());
Tim Northovercea0abb2014-03-29 08:22:29 +00005606
5607 // Push the "and; icmp" for any users that are conditional branches.
5608 // Since there can only be one branch use per BB, we don't need to keep
5609 // track of which BBs we insert into.
Sanjay Patel892f1672016-04-11 20:13:44 +00005610 for (Use &TheUse : Cmp->uses()) {
Tim Northovercea0abb2014-03-29 08:22:29 +00005611 // Find brcc use.
Sanjay Patel892f1672016-04-11 20:13:44 +00005612 BranchInst *BrccUser = dyn_cast<BranchInst>(TheUse);
Tim Northovercea0abb2014-03-29 08:22:29 +00005613 if (!BrccUser || !BrccUser->isConditional())
5614 continue;
5615 BasicBlock *UserBB = BrccUser->getParent();
Sanjay Patel892f1672016-04-11 20:13:44 +00005616 if (UserBB == &BB) continue;
Tim Northovercea0abb2014-03-29 08:22:29 +00005617 DEBUG(dbgs() << "found Brcc use\n");
5618
5619 // Sink the "and; icmp" to use.
5620 MadeChange = true;
5621 BinaryOperator *NewAnd =
5622 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
5623 BrccUser);
5624 CmpInst *NewCmp =
5625 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
5626 "", BrccUser);
5627 TheUse = NewCmp;
5628 ++NumAndCmpsMoved;
5629 DEBUG(BrccUser->getParent()->dump());
5630 }
5631 }
5632 return MadeChange;
5633}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005634
5635/// \brief Scale down both weights to fit into uint32_t.
5636static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5637 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5638 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5639 NewTrue = NewTrue / Scale;
5640 NewFalse = NewFalse / Scale;
5641}
5642
5643/// \brief Some targets prefer to split a conditional branch like:
5644/// \code
5645/// %0 = icmp ne i32 %a, 0
5646/// %1 = icmp ne i32 %b, 0
5647/// %or.cond = or i1 %0, %1
5648/// br i1 %or.cond, label %TrueBB, label %FalseBB
5649/// \endcode
5650/// into multiple branch instructions like:
5651/// \code
5652/// bb1:
5653/// %0 = icmp ne i32 %a, 0
5654/// br i1 %0, label %TrueBB, label %bb2
5655/// bb2:
5656/// %1 = icmp ne i32 %b, 0
5657/// br i1 %1, label %TrueBB, label %FalseBB
5658/// \endcode
5659/// This usually allows instruction selection to do even further optimizations
5660/// and combine the compare with the branch instruction. Currently this is
5661/// applied for targets which have "cheap" jump instructions.
5662///
5663/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5664///
5665bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005666 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005667 return false;
5668
5669 bool MadeChange = false;
5670 for (auto &BB : F) {
5671 // Does this BB end with the following?
5672 // %cond1 = icmp|fcmp|binary instruction ...
5673 // %cond2 = icmp|fcmp|binary instruction ...
5674 // %cond.or = or|and i1 %cond1, cond2
5675 // br i1 %cond.or label %dest1, label %dest2"
5676 BinaryOperator *LogicOp;
5677 BasicBlock *TBB, *FBB;
5678 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5679 continue;
5680
Sanjay Patel42574202015-09-02 19:23:23 +00005681 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5682 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5683 continue;
5684
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005685 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005686 Value *Cond1, *Cond2;
5687 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5688 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005689 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005690 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5691 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005692 Opc = Instruction::Or;
5693 else
5694 continue;
5695
5696 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5697 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5698 continue;
5699
5700 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5701
5702 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00005703 auto TmpBB =
5704 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
5705 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005706
5707 // Update original basic block by using the first condition directly by the
5708 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005709 Br1->setCondition(Cond1);
5710 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005711
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005712 // Depending on the conditon we have to either replace the true or the false
5713 // successor of the original branch instruction.
5714 if (Opc == Instruction::And)
5715 Br1->setSuccessor(0, TmpBB);
5716 else
5717 Br1->setSuccessor(1, TmpBB);
5718
5719 // Fill in the new basic block.
5720 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005721 if (auto *I = dyn_cast<Instruction>(Cond2)) {
5722 I->removeFromParent();
5723 I->insertBefore(Br2);
5724 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005725
5726 // Update PHI nodes in both successors. The original BB needs to be
5727 // replaced in one succesor's PHI nodes, because the branch comes now from
5728 // the newly generated BB (NewBB). In the other successor we need to add one
5729 // incoming edge to the PHI nodes, because both branch instructions target
5730 // now the same successor. Depending on the original branch condition
5731 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00005732 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005733 // This doesn't change the successor order of the just created branch
5734 // instruction (or any other instruction).
5735 if (Opc == Instruction::Or)
5736 std::swap(TBB, FBB);
5737
5738 // Replace the old BB with the new BB.
5739 for (auto &I : *TBB) {
5740 PHINode *PN = dyn_cast<PHINode>(&I);
5741 if (!PN)
5742 break;
5743 int i;
5744 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5745 PN->setIncomingBlock(i, TmpBB);
5746 }
5747
5748 // Add another incoming edge form the new BB.
5749 for (auto &I : *FBB) {
5750 PHINode *PN = dyn_cast<PHINode>(&I);
5751 if (!PN)
5752 break;
5753 auto *Val = PN->getIncomingValueForBlock(&BB);
5754 PN->addIncoming(Val, TmpBB);
5755 }
5756
5757 // Update the branch weights (from SelectionDAGBuilder::
5758 // FindMergedConditions).
5759 if (Opc == Instruction::Or) {
5760 // Codegen X | Y as:
5761 // BB1:
5762 // jmp_if_X TBB
5763 // jmp TmpBB
5764 // TmpBB:
5765 // jmp_if_Y TBB
5766 // jmp FBB
5767 //
5768
5769 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5770 // The requirement is that
5771 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5772 // = TrueProb for orignal BB.
5773 // Assuming the orignal weights are A and B, one choice is to set BB1's
5774 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5775 // assumes that
5776 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5777 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5778 // TmpBB, but the math is more complicated.
5779 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005780 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005781 uint64_t NewTrueWeight = TrueWeight;
5782 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5783 scaleWeights(NewTrueWeight, NewFalseWeight);
5784 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5785 .createBranchWeights(TrueWeight, FalseWeight));
5786
5787 NewTrueWeight = TrueWeight;
5788 NewFalseWeight = 2 * FalseWeight;
5789 scaleWeights(NewTrueWeight, NewFalseWeight);
5790 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5791 .createBranchWeights(TrueWeight, FalseWeight));
5792 }
5793 } else {
5794 // Codegen X & Y as:
5795 // BB1:
5796 // jmp_if_X TmpBB
5797 // jmp FBB
5798 // TmpBB:
5799 // jmp_if_Y TBB
5800 // jmp FBB
5801 //
5802 // This requires creation of TmpBB after CurBB.
5803
5804 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5805 // The requirement is that
5806 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5807 // = FalseProb for orignal BB.
5808 // Assuming the orignal weights are A and B, one choice is to set BB1's
5809 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5810 // assumes that
5811 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5812 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005813 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005814 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5815 uint64_t NewFalseWeight = FalseWeight;
5816 scaleWeights(NewTrueWeight, NewFalseWeight);
5817 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5818 .createBranchWeights(TrueWeight, FalseWeight));
5819
5820 NewTrueWeight = 2 * TrueWeight;
5821 NewFalseWeight = FalseWeight;
5822 scaleWeights(NewTrueWeight, NewFalseWeight);
5823 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5824 .createBranchWeights(TrueWeight, FalseWeight));
5825 }
5826 }
5827
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005828 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00005829 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005830 ModifiedDT = true;
5831
5832 MadeChange = true;
5833
5834 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5835 TmpBB->dump());
5836 }
5837 return MadeChange;
5838}
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005839
5840void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
Piotr Padlewskiea092882015-09-17 20:25:07 +00005841 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005842 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
5843}